Skip to main content

rustc_trait_selection/traits/
coherence.rs

1//! See Rustc Dev Guide chapters on [trait-resolution] and [trait-specialization] for more info on
2//! how this works.
3//!
4//! [trait-resolution]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
5//! [trait-specialization]: https://rustc-dev-guide.rust-lang.org/traits/specialization.html
6
7use std::fmt::Debug;
8
9use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
10use rustc_errors::{Diag, EmissionGuarantee};
11use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
12use rustc_hir::find_attr;
13use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt};
14use rustc_infer::traits::PredicateObligations;
15use rustc_macros::{TypeFoldable, TypeVisitable};
16use rustc_middle::bug;
17use rustc_middle::traits::query::NoSolution;
18use rustc_middle::traits::solve::{CandidateSource, Certainty, Goal};
19use rustc_middle::traits::specialization_graph::OverlapMode;
20use rustc_middle::ty::fast_reject::DeepRejectCtxt;
21use rustc_middle::ty::{
22    self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
23    Unnormalized,
24};
25pub use rustc_next_trait_solver::coherence::*;
26use rustc_next_trait_solver::solve::SolverDelegateEvalExt;
27use rustc_span::{DUMMY_SP, Span};
28use tracing::{debug, instrument, warn};
29
30use super::ObligationCtxt;
31use crate::error_reporting::traits::suggest_new_overflow_limit;
32use crate::infer::InferOk;
33use crate::solve::inspect::{InferCtxtProofTreeExt, InspectGoal, ProofTreeVisitor};
34use crate::solve::{SolverDelegate, deeply_normalize_for_diagnostics, inspect};
35use crate::traits::query::evaluate_obligation::InferCtxtExt;
36use crate::traits::select::IntercrateAmbiguityCause;
37use crate::traits::{
38    FulfillmentErrorCode, NormalizeExt, Obligation, ObligationCause, PredicateObligation,
39    SelectionContext, SkipLeakCheck, util,
40};
41
42/// The "header" of an impl is everything outside the body: a Self type, a trait
43/// ref (in the case of a trait impl), and a set of predicates (from the
44/// bounds / where-clauses).
45#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ImplHeader<'tcx> {
    #[inline]
    fn clone(&self) -> ImplHeader<'tcx> {
        ImplHeader {
            impl_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)]
46pub struct ImplHeader<'tcx> {
47    pub impl_def_id: DefId,
48    pub impl_args: ty::GenericArgsRef<'tcx>,
49    pub self_ty: Ty<'tcx>,
50    pub trait_ref: Option<ty::TraitRef<'tcx>>,
51    pub predicates: Vec<ty::Predicate<'tcx>>,
52}
53
54pub struct OverlapResult<'tcx> {
55    pub impl_header: ImplHeader<'tcx>,
56    pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
57
58    /// `true` if the overlap might've been permitted before the shift
59    /// to universes.
60    pub involves_placeholder: bool,
61
62    /// Used in the new solver to suggest increasing the recursion limit.
63    pub overflowing_predicates: Vec<ty::Predicate<'tcx>>,
64}
65
66pub fn add_placeholder_note<G: EmissionGuarantee>(err: &mut Diag<'_, G>) {
67    err.note(
68        "this behavior recently changed as a result of a bug fix; \
69         see rust-lang/rust#56105 for details",
70    );
71}
72
73pub(crate) fn suggest_increasing_recursion_limit<'tcx, G: EmissionGuarantee>(
74    tcx: TyCtxt<'tcx>,
75    err: &mut Diag<'_, G>,
76    overflowing_predicates: &[ty::Predicate<'tcx>],
77) {
78    for pred in overflowing_predicates {
79        err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("overflow evaluating the requirement `{0}`",
                pred))
    })format!("overflow evaluating the requirement `{}`", pred));
80    }
81
82    suggest_new_overflow_limit(tcx, err);
83}
84
85#[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)]
86enum TrackAmbiguityCauses {
87    Yes,
88    No,
89}
90
91impl TrackAmbiguityCauses {
92    fn is_yes(self) -> bool {
93        match self {
94            TrackAmbiguityCauses::Yes => true,
95            TrackAmbiguityCauses::No => false,
96        }
97    }
98}
99
100/// If there are types that satisfy both impls, returns `Some`
101/// with a suitably-freshened `ImplHeader` with those types
102/// instantiated. Otherwise, returns `None`.
103#[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(103u32),
                                    ::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:120",
                                        "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(120u32),
                                        ::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")]
104pub fn overlapping_inherent_impls(
105    tcx: TyCtxt<'_>,
106    impl1_def_id: DefId,
107    impl2_def_id: DefId,
108    skip_leak_check: SkipLeakCheck,
109    overlap_mode: OverlapMode,
110) -> Option<OverlapResult<'_>> {
111    // Before doing expensive operations like entering an inference context, do
112    // a quick check via fast_reject to tell if the impl headers could possibly
113    // unify.
114    let self_ty1 = tcx.type_of(impl1_def_id).skip_binder();
115    let self_ty2 = tcx.type_of(impl2_def_id).skip_binder();
116    let may_overlap = DeepRejectCtxt::relate_infer_infer(tcx).types_may_unify(self_ty1, self_ty2);
117
118    if !may_overlap {
119        // Some types involved are definitely different, so the impls couldn't possibly overlap.
120        debug!("overlapping_inherent_impls: fast_reject early-exit");
121        return None;
122    }
123
124    overlapping_impls(tcx, impl1_def_id, impl2_def_id, skip_leak_check, overlap_mode, false)
125}
126
127/// If there are types that satisfy both impls, returns `Some`
128/// with a suitably-freshened `ImplHeader` with those types
129/// instantiated. Otherwise, returns `None`.
130#[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(130u32),
                                    ::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:148",
                                        "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(148u32),
                                        ::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")]
131pub fn overlapping_trait_impls(
132    tcx: TyCtxt<'_>,
133    impl1_def_id: DefId,
134    impl2_def_id: DefId,
135    skip_leak_check: SkipLeakCheck,
136    overlap_mode: OverlapMode,
137) -> Option<OverlapResult<'_>> {
138    // Before doing expensive operations like entering an inference context, do
139    // a quick check via fast_reject to tell if the impl headers could possibly
140    // unify.
141    let impl1_args = tcx.impl_trait_ref(impl1_def_id).skip_binder().args;
142    let impl2_args = tcx.impl_trait_ref(impl2_def_id).skip_binder().args;
143    let may_overlap =
144        DeepRejectCtxt::relate_infer_infer(tcx).args_may_unify(impl1_args, impl2_args);
145
146    if !may_overlap {
147        // Some types involved are definitely different, so the impls couldn't possibly overlap.
148        debug!("overlapping_impls: fast_reject early-exit");
149        return None;
150    }
151
152    overlapping_impls(tcx, impl1_def_id, impl2_def_id, skip_leak_check, overlap_mode, true)
153}
154
155fn overlapping_impls(
156    tcx: TyCtxt<'_>,
157    impl1_def_id: DefId,
158    impl2_def_id: DefId,
159    skip_leak_check: SkipLeakCheck,
160    overlap_mode: OverlapMode,
161    is_of_trait: bool,
162) -> Option<OverlapResult<'_>> {
163    if tcx.next_trait_solver_in_coherence() {
164        overlap(
165            tcx,
166            TrackAmbiguityCauses::Yes,
167            skip_leak_check,
168            impl1_def_id,
169            impl2_def_id,
170            overlap_mode,
171            is_of_trait,
172        )
173    } else {
174        let _overlap_with_bad_diagnostics = overlap(
175            tcx,
176            TrackAmbiguityCauses::No,
177            skip_leak_check,
178            impl1_def_id,
179            impl2_def_id,
180            overlap_mode,
181            is_of_trait,
182        )?;
183
184        // In the case where we detect an error, run the check again, but
185        // this time tracking intercrate ambiguity causes for better
186        // diagnostics. (These take time and can lead to false errors.)
187        let overlap = overlap(
188            tcx,
189            TrackAmbiguityCauses::Yes,
190            skip_leak_check,
191            impl1_def_id,
192            impl2_def_id,
193            overlap_mode,
194            is_of_trait,
195        )
196        .unwrap();
197        Some(overlap)
198    }
199}
200
201fn fresh_impl_header<'tcx>(
202    infcx: &InferCtxt<'tcx>,
203    impl_def_id: DefId,
204    is_of_trait: bool,
205) -> ImplHeader<'tcx> {
206    let tcx = infcx.tcx;
207    let impl_args = infcx.fresh_args_for_item(DUMMY_SP, impl_def_id);
208
209    ImplHeader {
210        impl_def_id,
211        impl_args,
212        self_ty: tcx.type_of(impl_def_id).instantiate(tcx, impl_args).skip_norm_wip(),
213        trait_ref: is_of_trait
214            .then(|| tcx.impl_trait_ref(impl_def_id).instantiate(tcx, impl_args).skip_norm_wip()),
215        predicates: tcx
216            .predicates_of(impl_def_id)
217            .instantiate(tcx, impl_args)
218            .iter()
219            .map(|(c, _)| c.skip_norm_wip().as_predicate())
220            .collect(),
221    }
222}
223
224fn fresh_impl_header_normalized<'tcx>(
225    infcx: &InferCtxt<'tcx>,
226    param_env: ty::ParamEnv<'tcx>,
227    impl_def_id: DefId,
228    is_of_trait: bool,
229) -> ImplHeader<'tcx> {
230    let header = fresh_impl_header(infcx, impl_def_id, is_of_trait);
231
232    let InferOk { value: mut header, obligations } =
233        infcx.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(header));
234
235    header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
236    header
237}
238
239/// Can both impl `a` and impl `b` be satisfied by a common type (including
240/// where-clauses)? If so, returns an `ImplHeader` that unifies the two impls.
241#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("overlap",
                                    "rustc_trait_selection::traits::coherence",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(241u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                    ::tracing_core::field::FieldSet::new(&["track_ambiguity_causes",
                                                    "skip_leak_check", "impl1_def_id", "impl2_def_id",
                                                    "overlap_mode", "is_of_trait"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&track_ambiguity_causes)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&skip_leak_check)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl1_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl2_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlap_mode)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&is_of_trait as
                                                            &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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