Skip to main content

rustc_trait_selection/traits/
coherence.rs

1//! See Rustc Dev Guide chapters on [trait-resolution] and [trait-specialization] for more info on
2//! how this works.
3//!
4//! [trait-resolution]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
5//! [trait-specialization]: https://rustc-dev-guide.rust-lang.org/traits/specialization.html
6
7use std::fmt::Debug;
8
9use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
10use rustc_errors::{Diag, EmissionGuarantee};
11use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
12use rustc_hir::find_attr;
13use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt};
14use rustc_infer::traits::{PredicateObligations, TraitErrors};
15use rustc_macros::{TypeFoldable, TypeVisitable};
16use rustc_middle::bug;
17use rustc_middle::traits::query::NoSolution;
18use rustc_middle::traits::solve::{CandidateSource, Certainty, Goal};
19use rustc_middle::traits::specialization_graph::OverlapMode;
20use rustc_middle::ty::fast_reject::DeepRejectCtxt;
21use rustc_middle::ty::{
22    self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
23    Unnormalized,
24};
25pub use rustc_next_trait_solver::coherence::*;
26use rustc_next_trait_solver::solve::SolverDelegateEvalExt;
27use rustc_span::{DUMMY_SP, Span};
28use tracing::{debug, instrument, warn};
29
30use super::ObligationCtxt;
31use crate::error_reporting::traits::suggest_new_overflow_limit;
32use crate::infer::InferOk;
33use crate::solve::inspect::{InferCtxtProofTreeExt, InspectGoal, ProofTreeVisitor};
34use crate::solve::{SolverDelegate, deeply_normalize_for_diagnostics, inspect};
35use crate::traits::query::evaluate_obligation::InferCtxtExt;
36use crate::traits::select::IntercrateAmbiguityCause;
37use crate::traits::{
38    FulfillmentErrorCode, NormalizeExt, Obligation, ObligationCause, PredicateObligation,
39    SelectionContext, SkipLeakCheck, util,
40};
41
42/// The "header" of an impl is everything outside the body: a Self type, a trait
43/// ref (in the case of a trait impl), and a set of predicates (from the
44/// bounds / where-clauses).
45#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ImplHeader<'tcx> {
    #[inline]
    fn clone(&self) -> ImplHeader<'tcx> {
        ImplHeader {
            impl_args: ::core::clone::Clone::clone(&self.impl_args),
            self_ty: ::core::clone::Clone::clone(&self.self_ty),
            trait_ref: ::core::clone::Clone::clone(&self.trait_ref),
            predicates: ::core::clone::Clone::clone(&self.predicates),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ImplHeader<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "ImplHeader",
            "impl_args", &self.impl_args, "self_ty", &self.self_ty,
            "trait_ref", &self.trait_ref, "predicates", &&self.predicates)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ImplHeader<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        ImplHeader {
                            impl_args: __binding_0,
                            self_ty: __binding_1,
                            trait_ref: __binding_2,
                            predicates: __binding_3 } => {
                            ImplHeader {
                                impl_args: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                self_ty: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                trait_ref: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                                predicates: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_3,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    ImplHeader {
                        impl_args: __binding_0,
                        self_ty: __binding_1,
                        trait_ref: __binding_2,
                        predicates: __binding_3 } => {
                        ImplHeader {
                            impl_args: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            self_ty: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            trait_ref: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                            predicates: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_3,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ImplHeader<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    ImplHeader {
                        impl_args: ref __binding_0,
                        self_ty: ref __binding_1,
                        trait_ref: ref __binding_2,
                        predicates: ref __binding_3 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_3,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
46pub struct ImplHeader<'tcx> {
47    pub impl_args: ty::GenericArgsRef<'tcx>,
48    pub self_ty: Ty<'tcx>,
49    pub trait_ref: Option<ty::TraitRef<'tcx>>,
50    pub predicates: Vec<ty::Predicate<'tcx>>,
51}
52
53pub struct OverlapResult<'tcx> {
54    pub impl_header: ImplHeader<'tcx>,
55    pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
56
57    /// `true` if the overlap might've been permitted before the shift
58    /// to universes.
59    pub involves_placeholder: bool,
60
61    /// Used in the new solver to suggest increasing the recursion limit.
62    pub overflowing_predicates: Vec<ty::Predicate<'tcx>>,
63}
64
65pub fn add_placeholder_note<G: EmissionGuarantee>(err: &mut Diag<'_, G>) {
66    err.note(
67        "this behavior recently changed as a result of a bug fix; \
68         see rust-lang/rust#56105 for details",
69    );
70}
71
72pub(crate) fn suggest_increasing_recursion_limit<'tcx, G: EmissionGuarantee>(
73    tcx: TyCtxt<'tcx>,
74    err: &mut Diag<'_, G>,
75    overflowing_predicates: &[ty::Predicate<'tcx>],
76) {
77    for pred in overflowing_predicates {
78        err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("overflow evaluating the requirement `{0}`",
                pred))
    })format!("overflow evaluating the requirement `{}`", pred));
79    }
80
81    suggest_new_overflow_limit(tcx, err);
82}
83
84#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TrackAmbiguityCauses {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                TrackAmbiguityCauses::Yes => "Yes",
                TrackAmbiguityCauses::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for TrackAmbiguityCauses {
    #[inline]
    fn clone(&self) -> TrackAmbiguityCauses { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for TrackAmbiguityCauses { }Copy)]
85enum TrackAmbiguityCauses {
86    Yes,
87    No,
88}
89
90impl TrackAmbiguityCauses {
91    fn is_yes(self) -> bool {
92        match self {
93            TrackAmbiguityCauses::Yes => true,
94            TrackAmbiguityCauses::No => false,
95        }
96    }
97}
98
99/// If there are types that satisfy both impls, returns `Some`
100/// with a suitably-freshened `ImplHeader` with those types
101/// instantiated. Otherwise, returns `None`.
102#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("overlapping_inherent_impls",
                                    "rustc_trait_selection::traits::coherence",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(102u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl1_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl1_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl2_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl2_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("overlap_mode")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("overlap_mode");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl1_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl2_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlap_mode)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<OverlapResult<'_>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let self_ty1 = tcx.type_of(impl1_def_id).skip_binder();
            let self_ty2 = tcx.type_of(impl2_def_id).skip_binder();
            let may_overlap =
                DeepRejectCtxt::relate_infer_infer(tcx).types_may_unify(self_ty1,
                    self_ty2);
            if !may_overlap {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/coherence.rs:119",
                                        "rustc_trait_selection::traits::coherence",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                        ::tracing_core::__macro_support::Option::Some(119u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("overlapping_inherent_impls: fast_reject early-exit")
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                return None;
            }
            overlapping_impls(tcx, impl1_def_id, impl2_def_id,
                skip_leak_check, overlap_mode, false)
        }
    }
}#[instrument(skip(tcx, skip_leak_check), level = "debug")]
103pub fn overlapping_inherent_impls(
104    tcx: TyCtxt<'_>,
105    impl1_def_id: DefId,
106    impl2_def_id: DefId,
107    skip_leak_check: SkipLeakCheck,
108    overlap_mode: OverlapMode,
109) -> Option<OverlapResult<'_>> {
110    // Before doing expensive operations like entering an inference context, do
111    // a quick check via fast_reject to tell if the impl headers could possibly
112    // unify.
113    let self_ty1 = tcx.type_of(impl1_def_id).skip_binder();
114    let self_ty2 = tcx.type_of(impl2_def_id).skip_binder();
115    let may_overlap = DeepRejectCtxt::relate_infer_infer(tcx).types_may_unify(self_ty1, self_ty2);
116
117    if !may_overlap {
118        // Some types involved are definitely different, so the impls couldn't possibly overlap.
119        debug!("overlapping_inherent_impls: fast_reject early-exit");
120        return None;
121    }
122
123    overlapping_impls(tcx, impl1_def_id, impl2_def_id, skip_leak_check, overlap_mode, false)
124}
125
126/// If there are types that satisfy both impls, returns `Some`
127/// with a suitably-freshened `ImplHeader` with those types
128/// instantiated. Otherwise, returns `None`.
129#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("overlapping_trait_impls",
                                    "rustc_trait_selection::traits::coherence",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(129u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl1_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl1_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl2_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl2_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("overlap_mode")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("overlap_mode");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl1_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl2_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlap_mode)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<OverlapResult<'_>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let impl1_args =
                tcx.impl_trait_ref(impl1_def_id).skip_binder().args;
            let impl2_args =
                tcx.impl_trait_ref(impl2_def_id).skip_binder().args;
            let may_overlap =
                DeepRejectCtxt::relate_infer_infer(tcx).args_may_unify(impl1_args,
                    impl2_args);
            if !may_overlap {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/coherence.rs:147",
                                        "rustc_trait_selection::traits::coherence",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                        ::tracing_core::__macro_support::Option::Some(147u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("overlapping_impls: fast_reject early-exit")
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                return None;
            }
            overlapping_impls(tcx, impl1_def_id, impl2_def_id,
                skip_leak_check, overlap_mode, true)
        }
    }
}#[instrument(skip(tcx, skip_leak_check), level = "debug")]
130pub fn overlapping_trait_impls(
131    tcx: TyCtxt<'_>,
132    impl1_def_id: DefId,
133    impl2_def_id: DefId,
134    skip_leak_check: SkipLeakCheck,
135    overlap_mode: OverlapMode,
136) -> Option<OverlapResult<'_>> {
137    // Before doing expensive operations like entering an inference context, do
138    // a quick check via fast_reject to tell if the impl headers could possibly
139    // unify.
140    let impl1_args = tcx.impl_trait_ref(impl1_def_id).skip_binder().args;
141    let impl2_args = tcx.impl_trait_ref(impl2_def_id).skip_binder().args;
142    let may_overlap =
143        DeepRejectCtxt::relate_infer_infer(tcx).args_may_unify(impl1_args, impl2_args);
144
145    if !may_overlap {
146        // Some types involved are definitely different, so the impls couldn't possibly overlap.
147        debug!("overlapping_impls: fast_reject early-exit");
148        return None;
149    }
150
151    overlapping_impls(tcx, impl1_def_id, impl2_def_id, skip_leak_check, overlap_mode, true)
152}
153
154fn overlapping_impls(
155    tcx: TyCtxt<'_>,
156    impl1_def_id: DefId,
157    impl2_def_id: DefId,
158    skip_leak_check: SkipLeakCheck,
159    overlap_mode: OverlapMode,
160    is_of_trait: bool,
161) -> Option<OverlapResult<'_>> {
162    if tcx.next_trait_solver_in_coherence() {
163        overlap(
164            tcx,
165            TrackAmbiguityCauses::Yes,
166            skip_leak_check,
167            impl1_def_id,
168            impl2_def_id,
169            overlap_mode,
170            is_of_trait,
171        )
172    } else {
173        let _overlap_with_bad_diagnostics = overlap(
174            tcx,
175            TrackAmbiguityCauses::No,
176            skip_leak_check,
177            impl1_def_id,
178            impl2_def_id,
179            overlap_mode,
180            is_of_trait,
181        )?;
182
183        // In the case where we detect an error, run the check again, but
184        // this time tracking intercrate ambiguity causes for better
185        // diagnostics. (These take time and can lead to false errors.)
186        let overlap = overlap(
187            tcx,
188            TrackAmbiguityCauses::Yes,
189            skip_leak_check,
190            impl1_def_id,
191            impl2_def_id,
192            overlap_mode,
193            is_of_trait,
194        )
195        .unwrap();
196        Some(overlap)
197    }
198}
199
200fn fresh_impl_header<'tcx>(
201    infcx: &InferCtxt<'tcx>,
202    impl_def_id: DefId,
203    is_of_trait: bool,
204) -> ImplHeader<'tcx> {
205    let tcx = infcx.tcx;
206    let impl_args = infcx.fresh_args_for_item(DUMMY_SP, impl_def_id);
207
208    ImplHeader {
209        impl_args,
210        self_ty: tcx.type_of(impl_def_id).instantiate(tcx, impl_args).skip_norm_wip(),
211        trait_ref: is_of_trait
212            .then(|| tcx.impl_trait_ref(impl_def_id).instantiate(tcx, impl_args).skip_norm_wip()),
213        predicates: tcx
214            .clauses_of(impl_def_id)
215            .instantiate(tcx, impl_args)
216            .iter()
217            .map(|(c, _)| c.skip_norm_wip().as_predicate())
218            .collect(),
219    }
220}
221
222fn fresh_impl_header_normalized<'tcx>(
223    infcx: &InferCtxt<'tcx>,
224    param_env: ty::ParamEnv<'tcx>,
225    impl_def_id: DefId,
226    is_of_trait: bool,
227) -> ImplHeader<'tcx> {
228    let header = fresh_impl_header(infcx, impl_def_id, is_of_trait);
229
230    let InferOk { value: mut header, obligations } =
231        infcx.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(header));
232
233    header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
234    header
235}
236
237/// Can both impl `a` and impl `b` be satisfied by a common type (including
238/// where-clauses)? If so, returns an `ImplHeader` that unifies the two impls.
239#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("overlap",
                                    "rustc_trait_selection::traits::coherence",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(239u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("track_ambiguity_causes")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("track_ambiguity_causes");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("skip_leak_check")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("skip_leak_check");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl1_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl1_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl2_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl2_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("overlap_mode")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("overlap_mode");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("is_of_trait")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("is_of_trait");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&track_ambiguity_causes)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&skip_leak_check)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl1_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl2_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlap_mode)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&is_of_trait as
                                                            &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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