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 =
                if tcx.next_trait_solver_in_coherence() {
                    fresh_impl_header(selcx.infcx, impl1_def_id, is_of_trait)
                } else {
                    fresh_impl_header_normalized(selcx.infcx, param_env,
                        impl1_def_id, is_of_trait)
                };
            let impl2_header =
                if tcx.next_trait_solver_in_coherence() {
                    fresh_impl_header(selcx.infcx, impl2_def_id, is_of_trait)
                } else {
                    fresh_impl_header_normalized(selcx.infcx, param_env,
                        impl2_def_id, is_of_trait)
                };
            let mut obligations =
                equate_impl_headers(selcx.infcx, param_env, &impl1_header,
                        &impl2_header)?;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/coherence.rs:296",
                                    "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(296u32),
                                    ::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:317",
                                        "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(317u32),
                                        ::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:329",
                                    "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(329u32),
                                    ::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 = if tcx.next_trait_solver_in_coherence() {
282        fresh_impl_header(selcx.infcx, impl1_def_id, is_of_trait)
283    } else {
284        fresh_impl_header_normalized(selcx.infcx, param_env, impl1_def_id, is_of_trait)
285    };
286    let impl2_header = if tcx.next_trait_solver_in_coherence() {
287        fresh_impl_header(selcx.infcx, impl2_def_id, is_of_trait)
288    } else {
289        fresh_impl_header_normalized(selcx.infcx, param_env, impl2_def_id, is_of_trait)
290    };
291
292    // Equate the headers to find their intersection (the general type, with infer vars,
293    // that may apply both impls).
294    let mut obligations =
295        equate_impl_headers(selcx.infcx, param_env, &impl1_header, &impl2_header)?;
296    debug!("overlap: unification check succeeded");
297
298    obligations.extend(
299        [&impl1_header.predicates, &impl2_header.predicates].into_iter().flatten().map(
300            |&predicate| Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, predicate),
301        ),
302    );
303
304    let mut overflowing_predicates = Vec::new();
305    if overlap_mode.use_implicit_negative() {
306        match impl_intersection_has_impossible_obligation(selcx, &obligations) {
307            IntersectionHasImpossibleObligations::Yes => return None,
308            IntersectionHasImpossibleObligations::No { overflowing_predicates: p } => {
309                overflowing_predicates = p
310            }
311        }
312    }
313
314    // We toggle the `leak_check` by using `skip_leak_check` when constructing the
315    // inference context, so this may be a noop.
316    if infcx.leak_check(ty::UniverseIndex::ROOT, None).is_err() {
317        debug!("overlap: leak check failed");
318        return None;
319    }
320
321    let intercrate_ambiguity_causes = if !overlap_mode.use_implicit_negative() {
322        Default::default()
323    } else if infcx.next_trait_solver() {
324        compute_intercrate_ambiguity_causes(&infcx, &obligations)
325    } else {
326        selcx.take_intercrate_ambiguity_causes()
327    };
328
329    debug!("overlap: intercrate_ambiguity_causes={:#?}", intercrate_ambiguity_causes);
330    let involves_placeholder = infcx
331        .inner
332        .borrow_mut()
333        .unwrap_region_constraints()
334        .data()
335        .constraints
336        .iter()
337        .any(|c| c.0.involves_placeholders());
338
339    let mut impl_header = infcx.resolve_vars_if_possible(impl1_header);
340
341    // Deeply normalize the impl header for diagnostics, ignoring any errors if this fails.
342    if infcx.next_trait_solver() {
343        impl_header = deeply_normalize_for_diagnostics(&infcx, param_env, impl_header);
344    }
345
346    Some(OverlapResult {
347        impl_header,
348        intercrate_ambiguity_causes,
349        involves_placeholder,
350        overflowing_predicates,
351    })
352}
353
354x;#[instrument(level = "debug", skip(infcx), ret)]
355fn equate_impl_headers<'tcx>(
356    infcx: &InferCtxt<'tcx>,
357    param_env: ty::ParamEnv<'tcx>,
358    impl1: &ImplHeader<'tcx>,
359    impl2: &ImplHeader<'tcx>,
360) -> Option<PredicateObligations<'tcx>> {
361    let result =
362        match (impl1.trait_ref, impl2.trait_ref) {
363            (Some(impl1_ref), Some(impl2_ref)) => infcx
364                .at(&ObligationCause::dummy(), param_env)
365                .eq(DefineOpaqueTypes::Yes, impl1_ref, impl2_ref),
366            (None, None) => infcx.at(&ObligationCause::dummy(), param_env).eq(
367                DefineOpaqueTypes::Yes,
368                impl1.self_ty,
369                impl2.self_ty,
370            ),
371            _ => bug!("equate_impl_headers given mismatched impl kinds"),
372        };
373
374    result.map(|infer_ok| infer_ok.obligations).ok()
375}
376
377/// The result of [fn impl_intersection_has_impossible_obligation].
378#[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)]
379enum IntersectionHasImpossibleObligations<'tcx> {
380    Yes,
381    No {
382        /// With `-Znext-solver=coherence`, some obligations may
383        /// fail if only the user increased the recursion limit.
384        ///
385        /// We return those obligations here and mention them in the
386        /// error message.
387        overflowing_predicates: Vec<ty::Predicate<'tcx>>,
388    },
389}
390
391/// Check if both impls can be satisfied by a common type by considering whether
392/// any of either impl's obligations is not known to hold.
393///
394/// For example, given these two impls:
395///     `impl From<MyLocalType> for Box<dyn Error>` (in my crate)
396///     `impl<E> From<E> for Box<dyn Error> where E: Error` (in libstd)
397///
398/// After replacing both impl headers with inference vars (which happens before
399/// this function is called), we get:
400///     `Box<dyn Error>: From<MyLocalType>`
401///     `Box<dyn Error>: From<?E>`
402///
403/// This gives us `?E = MyLocalType`. We then certainly know that `MyLocalType: Error`
404/// never holds in intercrate mode since a local impl does not exist, and a
405/// downstream impl cannot be added -- therefore can consider the intersection
406/// of the two impls above to be empty.
407///
408/// Importantly, this works even if there isn't a `impl !Error for MyLocalType`.
409x;#[instrument(level = "debug", skip(selcx), ret)]
410fn impl_intersection_has_impossible_obligation<'a, 'cx, 'tcx>(
411    selcx: &mut SelectionContext<'cx, 'tcx>,
412    obligations: &'a [PredicateObligation<'tcx>],
413) -> IntersectionHasImpossibleObligations<'tcx> {
414    let infcx = selcx.infcx;
415
416    if infcx.next_trait_solver() {
417        // A fast path optimization, try evaluating all goals with
418        // a very low recursion depth and bail if any of them don't
419        // hold.
420        if !obligations.iter().all(|o| {
421            <&SolverDelegate<'tcx>>::from(infcx)
422                .root_goal_may_hold_with_depth(8, Goal::new(infcx.tcx, o.param_env, o.predicate))
423        }) {
424            return IntersectionHasImpossibleObligations::Yes;
425        }
426
427        let ocx = ObligationCtxt::new(infcx);
428        ocx.register_obligations(obligations.iter().cloned());
429        let hard_errors = ocx.try_evaluate_obligations();
430        if !hard_errors.is_empty() {
431            assert!(
432                hard_errors.iter().all(|e| e.is_true_error()),
433                "should not have detected ambiguity during first pass"
434            );
435            return IntersectionHasImpossibleObligations::Yes;
436        }
437
438        // Make a new `ObligationCtxt` and re-prove the ambiguities with a richer
439        // `FulfillmentError`. This is so that we can detect overflowing obligations
440        // without needing to run the `BestObligation` visitor on true errors.
441        let ambiguities = ocx.into_pending_obligations();
442        let ocx = ObligationCtxt::new_with_diagnostics(infcx);
443        ocx.register_obligations(ambiguities);
444        let errors_and_ambiguities = ocx.evaluate_obligations_error_on_ambiguity();
445        // We only care about the obligations that are *definitely* true errors.
446        // Ambiguities do not prove the disjointness of two impls.
447        let (errors, ambiguities): (Vec<_>, Vec<_>) =
448            errors_and_ambiguities.into_iter().partition(|error| error.is_true_error());
449        assert!(errors.is_empty(), "should not have ambiguities during second pass");
450
451        IntersectionHasImpossibleObligations::No {
452            overflowing_predicates: ambiguities
453                .into_iter()
454                .filter(|error| {
455                    matches!(error.code, FulfillmentErrorCode::Ambiguity { overflow: Some(true) })
456                })
457                .map(|e| infcx.resolve_vars_if_possible(e.obligation.predicate))
458                .collect(),
459        }
460    } else {
461        for obligation in obligations {
462            // We use `evaluate_root_obligation` to correctly track intercrate
463            // ambiguity clauses.
464            let evaluation_result = selcx.evaluate_root_obligation(obligation);
465
466            match evaluation_result {
467                Ok(result) => {
468                    if !result.may_apply() {
469                        return IntersectionHasImpossibleObligations::Yes;
470                    }
471                }
472                // If overflow occurs, we need to conservatively treat the goal as possibly holding,
473                // since there can be instantiations of this goal that don't overflow and result in
474                // success. While this isn't much of a problem in the old solver, since we treat overflow
475                // fatally, this still can be encountered: <https://github.com/rust-lang/rust/issues/105231>.
476                Err(_overflow) => {}
477            }
478        }
479
480        IntersectionHasImpossibleObligations::No { overflowing_predicates: Vec::new() }
481    }
482}
483
484/// Check if both impls can be satisfied by a common type by considering whether
485/// any of first impl's obligations is known not to hold *via a negative predicate*.
486///
487/// For example, given these two impls:
488///     `struct MyCustomBox<T: ?Sized>(Box<T>);`
489///     `impl From<&str> for MyCustomBox<dyn Error>` (in my crate)
490///     `impl<E> From<E> for MyCustomBox<dyn Error> where E: Error` (in my crate)
491///
492/// After replacing the second impl's header with inference vars, we get:
493///     `MyCustomBox<dyn Error>: From<&str>`
494///     `MyCustomBox<dyn Error>: From<?E>`
495///
496/// This gives us `?E = &str`. We then try to prove the first impl's predicates
497/// after negating, giving us `&str: !Error`. This is a negative impl provided by
498/// libstd, and therefore we can guarantee for certain that libstd will never add
499/// a positive impl for `&str: Error` (without it being a breaking change).
500fn impl_intersection_has_negative_obligation(
501    tcx: TyCtxt<'_>,
502    impl1_def_id: DefId,
503    impl2_def_id: DefId,
504    is_of_trait: bool,
505) -> bool {
506    {
    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:506",
                        "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(506u32),
                        ::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);
507
508    // N.B. We need to unify impl headers *with* `TypingMode::Coherence`,
509    // even if proving negative predicates doesn't need `TypingMode::Coherence`.
510    let ref infcx = tcx.infer_ctxt().with_next_trait_solver(true).build(TypingMode::Coherence);
511    let root_universe = infcx.universe();
512    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);
513
514    let impl1_header = fresh_impl_header(infcx, impl1_def_id, is_of_trait);
515    let impl2_header = fresh_impl_header(infcx, impl2_def_id, is_of_trait);
516
517    // Equate the headers to find their intersection (the general type, with infer vars,
518    // that may apply both impls).
519    let Some(equate_obligations) =
520        equate_impl_headers(infcx, ty::ParamEnv::empty(), &impl1_header, &impl2_header)
521    else {
522        return false;
523    };
524
525    // FIXME(with_negative_coherence): the infcx has constraints from equating
526    // the impl headers. We should use these constraints as assumptions, not as
527    // requirements, when proving the negated where clauses below.
528    drop(equate_obligations);
529    drop(infcx.take_registered_region_obligations());
530    drop(infcx.take_registered_region_assumptions());
531    drop(infcx.take_and_reset_region_constraints());
532
533    plug_infer_with_placeholders(
534        infcx,
535        root_universe,
536        (impl1_header.impl_args, impl2_header.impl_args),
537    );
538
539    // Right above we plug inference variables with placeholders,
540    // this gets us new impl1_header_args with the inference variables actually resolved
541    // to those placeholders.
542    let impl1_header_args = infcx.resolve_vars_if_possible(impl1_header.impl_args);
543    // So there are no infer variables left now, except regions which aren't resolved by `resolve_vars_if_possible`.
544    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());
545
546    let param_env = ty::EarlyBinder::bind(tcx.param_env(impl1_def_id))
547        .instantiate(tcx, impl1_header_args)
548        .skip_norm_wip();
549
550    util::elaborate(
551        tcx,
552        tcx.predicates_of(impl2_def_id)
553            .instantiate(tcx, impl2_header.impl_args)
554            .into_iter()
555            .map(|(c, s)| (c.skip_norm_wip(), s)),
556    )
557    .elaborate_sized()
558    .any(|(clause, _)| try_prove_negated_where_clause(infcx, clause, param_env))
559}
560
561fn plug_infer_with_placeholders<'tcx>(
562    infcx: &InferCtxt<'tcx>,
563    universe: ty::UniverseIndex,
564    value: impl TypeVisitable<TyCtxt<'tcx>>,
565) {
566    struct PlugInferWithPlaceholder<'a, 'tcx> {
567        infcx: &'a InferCtxt<'tcx>,
568        universe: ty::UniverseIndex,
569        var: ty::BoundVar,
570    }
571
572    impl<'tcx> PlugInferWithPlaceholder<'_, 'tcx> {
573        fn next_var(&mut self) -> ty::BoundVar {
574            let var = self.var;
575            self.var = self.var + 1;
576            var
577        }
578    }
579
580    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for PlugInferWithPlaceholder<'_, 'tcx> {
581        fn visit_ty(&mut self, ty: Ty<'tcx>) {
582            let ty = self.infcx.shallow_resolve(ty);
583            if ty.is_ty_var() {
584                let Ok(InferOk { value: (), obligations }) =
585                    self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
586                        // Comparing against a type variable never registers hidden types anyway
587                        DefineOpaqueTypes::Yes,
588                        ty,
589                        Ty::new_placeholder(
590                            self.infcx.tcx,
591                            ty::PlaceholderType::new(
592                                self.universe,
593                                ty::BoundTy { var: self.next_var(), kind: ty::BoundTyKind::Anon },
594                            ),
595                        ),
596                    )
597                else {
598                    ::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")
599                };
600                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);
601            } else {
602                ty.super_visit_with(self);
603            }
604        }
605
606        fn visit_const(&mut self, ct: ty::Const<'tcx>) {
607            let ct = self.infcx.shallow_resolve_const(ct);
608            if ct.is_ct_infer() {
609                let Ok(InferOk { value: (), obligations }) =
610                    self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
611                        // The types of the constants are the same, so there is no hidden type
612                        // registration happening anyway.
613                        DefineOpaqueTypes::Yes,
614                        ct,
615                        ty::Const::new_placeholder(
616                            self.infcx.tcx,
617                            ty::PlaceholderConst::new(
618                                self.universe,
619                                ty::BoundConst::new(self.next_var()),
620                            ),
621                        ),
622                    )
623                else {
624                    ::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")
625                };
626                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);
627            } else {
628                ct.super_visit_with(self);
629            }
630        }
631
632        fn visit_region(&mut self, r: ty::Region<'tcx>) {
633            if let ty::ReVar(vid) = r.kind() {
634                let r = self
635                    .infcx
636                    .inner
637                    .borrow_mut()
638                    .unwrap_region_constraints()
639                    .opportunistic_resolve_var(self.infcx.tcx, vid);
640                if r.is_var() {
641                    let Ok(InferOk { value: (), obligations }) =
642                        self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
643                            // Lifetimes don't contain opaque types (or any types for that matter).
644                            DefineOpaqueTypes::Yes,
645                            r,
646                            ty::Region::new_placeholder(
647                                self.infcx.tcx,
648                                ty::PlaceholderRegion::new(
649                                    self.universe,
650                                    ty::BoundRegion {
651                                        var: self.next_var(),
652                                        kind: ty::BoundRegionKind::Anon,
653                                    },
654                                ),
655                            ),
656                        )
657                    else {
658                        ::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")
659                    };
660                    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);
661                }
662            }
663        }
664    }
665
666    value.visit_with(&mut PlugInferWithPlaceholder { infcx, universe, var: ty::BoundVar::ZERO });
667}
668
669fn try_prove_negated_where_clause<'tcx>(
670    root_infcx: &InferCtxt<'tcx>,
671    clause: ty::Clause<'tcx>,
672    param_env: ty::ParamEnv<'tcx>,
673) -> bool {
674    let Some(negative_predicate) = clause.as_predicate().flip_polarity(root_infcx.tcx) else {
675        return false;
676    };
677
678    // N.B. We don't need to use intercrate mode here because we're trying to prove
679    // the *existence* of a negative goal, not the non-existence of a positive goal.
680    // Without this, we over-eagerly register coherence ambiguity candidates when
681    // impl candidates do exist.
682    // FIXME(#132279): `TypingMode::non_body_analysis` is a bit questionable here as it
683    // would cause us to reveal opaque types to leak their auto traits.
684    let ref infcx = root_infcx.fork_with_typing_mode(TypingMode::non_body_analysis());
685    let ocx = ObligationCtxt::new(infcx);
686    ocx.register_obligation(Obligation::new(
687        infcx.tcx,
688        ObligationCause::dummy(),
689        param_env,
690        negative_predicate,
691    ));
692    if !ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
693        return false;
694    }
695
696    // FIXME: We could use the assumed_wf_types from both impls, I think,
697    // if that wasn't implemented just for LocalDefId, and we'd need to do
698    // the normalization ourselves since this is totally fallible...
699    let errors = ocx.resolve_regions(CRATE_DEF_ID, param_env, []);
700    if !errors.is_empty() {
701        return false;
702    }
703
704    true
705}
706
707/// Compute the `intercrate_ambiguity_causes` for the new solver using
708/// "proof trees".
709///
710/// This is a bit scuffed but seems to be good enough, at least
711/// when looking at UI tests. Given that it is only used to improve
712/// diagnostics this is good enough. We can always improve it once there
713/// are test cases where it is currently not enough.
714fn compute_intercrate_ambiguity_causes<'tcx>(
715    infcx: &InferCtxt<'tcx>,
716    obligations: &[PredicateObligation<'tcx>],
717) -> FxIndexSet<IntercrateAmbiguityCause<'tcx>> {
718    let mut causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>> = Default::default();
719
720    for obligation in obligations {
721        search_ambiguity_causes(infcx, obligation.as_goal(), &mut causes);
722    }
723
724    causes
725}
726
727struct AmbiguityCausesVisitor<'a, 'tcx> {
728    cache: FxHashSet<Goal<'tcx, ty::Predicate<'tcx>>>,
729    causes: &'a mut FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
730}
731
732impl<'a, 'tcx> ProofTreeVisitor<'tcx> for AmbiguityCausesVisitor<'a, 'tcx> {
733    fn span(&self) -> Span {
734        DUMMY_SP
735    }
736
737    fn visit_goal(&mut self, goal: &InspectGoal<'_, 'tcx>) {
738        if !self.cache.insert(goal.goal()) {
739            return;
740        }
741
742        let infcx = goal.infcx();
743        for cand in goal.candidates() {
744            cand.visit_nested_in_probe(self);
745        }
746        // When searching for intercrate ambiguity causes, we only need to look
747        // at ambiguous goals, as for others the coherence unknowable candidate
748        // was irrelevant.
749        match goal.result() {
750            Ok(Certainty::Yes) | Err(NoSolution) => return,
751            Ok(Certainty::Maybe(_)) => {}
752        }
753
754        // For bound predicates we simply call `infcx.enter_forall`
755        // and then prove the resulting predicate as a nested goal.
756        let Goal { param_env, predicate } = goal.goal();
757        let predicate_kind = goal.infcx().enter_forall_and_leak_universe(predicate.kind());
758        let trait_ref = match predicate_kind {
759            ty::PredicateKind::Clause(ty::ClauseKind::Trait(tr)) => tr.trait_ref,
760            ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj))
761                if #[allow(non_exhaustive_omitted_patterns)] match infcx.tcx.def_kind(proj.def_id())
    {
    DefKind::AssocTy | DefKind::AssocConst { .. } => true,
    _ => false,
}matches!(
762                    infcx.tcx.def_kind(proj.def_id()),
763                    DefKind::AssocTy | DefKind::AssocConst { .. }
764                ) =>
765            {
766                proj.projection_term.trait_ref(infcx.tcx)
767            }
768            _ => return,
769        };
770
771        if trait_ref.references_error() {
772            return;
773        }
774
775        let mut candidates = goal.candidates();
776        for cand in goal.candidates() {
777            if let inspect::ProbeKind::TraitCandidate {
778                source: CandidateSource::Impl(def_id),
779                result: Ok(_),
780            } = cand.kind()
781                && let ty::ImplPolarity::Reservation = infcx.tcx.impl_polarity(def_id)
782            {
783                if let Some(message) =
784                    {
    {
        '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)
785                {
786                    self.causes.insert(IntercrateAmbiguityCause::ReservationImpl { message });
787                }
788            }
789        }
790
791        // We also look for unknowable candidates. In case a goal is unknowable, there's
792        // always exactly 1 candidate.
793        let Some(cand) = candidates.pop() else {
794            return;
795        };
796
797        let inspect::ProbeKind::TraitCandidate {
798            source: CandidateSource::CoherenceUnknowable,
799            result: Ok(_),
800        } = cand.kind()
801        else {
802            return;
803        };
804
805        let lazily_normalize_ty = |mut ty: Ty<'tcx>| {
806            if #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Alias(..) => true,
    _ => false,
}matches!(ty.kind(), ty::Alias(..)) {
807                let ocx = ObligationCtxt::new(infcx);
808                ty = ocx
809                    .structurally_normalize_ty(
810                        &ObligationCause::dummy(),
811                        param_env,
812                        Unnormalized::new_wip(ty),
813                    )
814                    .map_err(|_| ())?;
815                if !ocx.try_evaluate_obligations().is_empty() {
816                    return Err(());
817                }
818            }
819            Ok(ty)
820        };
821
822        infcx.probe(|_| {
823            let conflict = match trait_ref_is_knowable(infcx, trait_ref, lazily_normalize_ty) {
824                Err(()) => return,
825                Ok(Ok(())) => {
826                    {
    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:826",
                        "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(826u32),
                        ::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:?}");
827                    return;
828                }
829                Ok(Err(conflict)) => conflict,
830            };
831
832            // It is only relevant that a goal is unknowable if it would have otherwise
833            // failed.
834            // FIXME(#132279): Forking with `TypingMode::non_body_analysis` is a bit questionable
835            // as it would allow us to reveal opaque types, potentially causing unexpected
836            // cycles.
837            let non_intercrate_infcx = infcx.fork_with_typing_mode(TypingMode::non_body_analysis());
838            if non_intercrate_infcx.predicate_may_hold(&Obligation::new(
839                infcx.tcx,
840                ObligationCause::dummy(),
841                param_env,
842                predicate,
843            )) {
844                return;
845            }
846
847            // Normalize the trait ref for diagnostics, ignoring any errors if this fails.
848            let trait_ref = deeply_normalize_for_diagnostics(infcx, param_env, trait_ref);
849            let self_ty = trait_ref.self_ty();
850            let self_ty = self_ty.has_concrete_skeleton().then(|| self_ty);
851            self.causes.insert(match conflict {
852                Conflict::Upstream => {
853                    IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_ref, self_ty }
854                }
855                Conflict::Downstream => {
856                    IntercrateAmbiguityCause::DownstreamCrate { trait_ref, self_ty }
857                }
858            });
859        });
860    }
861}
862
863fn search_ambiguity_causes<'tcx>(
864    infcx: &InferCtxt<'tcx>,
865    goal: Goal<'tcx, ty::Predicate<'tcx>>,
866    causes: &mut FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
867) {
868    infcx.probe(|_| {
869        infcx.visit_proof_tree(
870            goal,
871            &mut AmbiguityCausesVisitor { cache: Default::default(), causes },
872        )
873    });
874}