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;
11use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
12use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt};
13use rustc_infer::traits::{PredicateObligations, TraitErrors};
14use rustc_macros::{TypeFoldable, TypeVisitable};
15use rustc_middle::traits::query::NoSolution;
16use rustc_middle::traits::solve::{CandidateSource, Certainty, Goal};
17use rustc_middle::traits::specialization_graph::OverlapMode;
18use rustc_middle::ty::fast_reject::DeepRejectCtxt;
19use rustc_middle::ty::{
20    self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
21    Unnormalized,
22};
23pub use rustc_next_trait_solver::coherence::*;
24use rustc_next_trait_solver::solve::SolverDelegateEvalExt;
25use rustc_span::{DUMMY_SP, Span, bug};
26use tracing::{debug, instrument, warn};
27
28use super::ObligationCtxt;
29use crate::error_reporting::traits::suggest_new_overflow_limit;
30use crate::infer::InferOk;
31use crate::solve::inspect::{InferCtxtProofTreeExt, InspectGoal, ProofTreeVisitor};
32use crate::solve::{SolverDelegate, deeply_normalize_for_diagnostics, inspect};
33use crate::traits::query::evaluate_obligation::InferCtxtExt;
34use crate::traits::select::IntercrateAmbiguityCause;
35use crate::traits::{
36    FulfillmentErrorCode, NormalizeExt, Obligation, ObligationCause, PredicateObligation,
37    SelectionContext, SkipLeakCheck, util,
38};
39
40/// The "header" of an impl is everything outside the body: a Self type, a trait
41/// ref (in the case of a trait impl), and a set of predicates (from the
42/// bounds / where-clauses).
43#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ImplHeader<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            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)]
44pub struct ImplHeader<'tcx> {
45    pub impl_args: ty::GenericArgsRef<'tcx>,
46    pub self_ty: Ty<'tcx>,
47    pub trait_ref: Option<ty::TraitRef<'tcx>>,
48    pub predicates: Vec<ty::Predicate<'tcx>>,
49}
50
51pub struct OverlapResult<'tcx> {
52    pub impl_header: ImplHeader<'tcx>,
53    pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
54
55    /// `true` if the overlap might've been permitted before the shift
56    /// to universes.
57    pub involves_placeholder: bool,
58
59    /// Used in the new solver to suggest increasing the recursion limit.
60    pub overflowing_predicates: Vec<ty::Predicate<'tcx>>,
61}
62
63pub fn add_placeholder_note(err: &mut Diag<'_>) {
64    err.note(
65        "this behavior recently changed as a result of a bug fix; \
66         see rust-lang/rust#56105 for details",
67    );
68}
69
70pub(crate) fn suggest_increasing_recursion_limit<'tcx>(
71    tcx: TyCtxt<'tcx>,
72    err: &mut Diag<'_>,
73    overflowing_predicates: &[ty::Predicate<'tcx>],
74) {
75    for pred in overflowing_predicates {
76        err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("overflow evaluating the requirement `{0}`",
                pred))
    })format!("overflow evaluating the requirement `{}`", pred));
77    }
78
79    suggest_new_overflow_limit(tcx, err);
80}
81
82#[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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for TrackAmbiguityCauses { }
#[automatically_derived]
impl ::core::clone::Clone for TrackAmbiguityCauses {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for TrackAmbiguityCauses { }Copy)]
83enum TrackAmbiguityCauses {
84    Yes,
85    No,
86}
87
88impl TrackAmbiguityCauses {
89    fn is_yes(self) -> bool {
90        match self {
91            TrackAmbiguityCauses::Yes => true,
92            TrackAmbiguityCauses::No => false,
93        }
94    }
95}
96
97/// If there are types that satisfy both impls, returns `Some`
98/// with a suitably-freshened `ImplHeader` with those types
99/// instantiated. Otherwise, returns `None`.
100{}
#[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("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(100u32),
                                    ::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 /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs:117",
                                        "rustc_trait_selection::traits::coherence",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                        ::tracing_core::__macro_support::Option::Some(117u32),
                                        ::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")]
101pub fn overlapping_inherent_impls(
102    tcx: TyCtxt<'_>,
103    impl1_def_id: DefId,
104    impl2_def_id: DefId,
105    skip_leak_check: SkipLeakCheck,
106    overlap_mode: OverlapMode,
107) -> Option<OverlapResult<'_>> {
108    // Before doing expensive operations like entering an inference context, do
109    // a quick check via fast_reject to tell if the impl headers could possibly
110    // unify.
111    let self_ty1 = tcx.type_of(impl1_def_id).skip_binder();
112    let self_ty2 = tcx.type_of(impl2_def_id).skip_binder();
113    let may_overlap = DeepRejectCtxt::relate_infer_infer(tcx).types_may_unify(self_ty1, self_ty2);
114
115    if !may_overlap {
116        // Some types involved are definitely different, so the impls couldn't possibly overlap.
117        debug!("overlapping_inherent_impls: fast_reject early-exit");
118        return None;
119    }
120
121    overlapping_impls(tcx, impl1_def_id, impl2_def_id, skip_leak_check, overlap_mode, false)
122}
123
124/// If there are types that satisfy both impls, returns `Some`
125/// with a suitably-freshened `ImplHeader` with those types
126/// instantiated. Otherwise, returns `None`.
127{}
#[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("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(127u32),
                                    ::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 /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs:145",
                                        "rustc_trait_selection::traits::coherence",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                        ::tracing_core::__macro_support::Option::Some(145u32),
                                        ::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")]
128pub fn overlapping_trait_impls(
129    tcx: TyCtxt<'_>,
130    impl1_def_id: DefId,
131    impl2_def_id: DefId,
132    skip_leak_check: SkipLeakCheck,
133    overlap_mode: OverlapMode,
134) -> Option<OverlapResult<'_>> {
135    // Before doing expensive operations like entering an inference context, do
136    // a quick check via fast_reject to tell if the impl headers could possibly
137    // unify.
138    let impl1_args = tcx.impl_trait_ref(impl1_def_id).skip_binder().args;
139    let impl2_args = tcx.impl_trait_ref(impl2_def_id).skip_binder().args;
140    let may_overlap =
141        DeepRejectCtxt::relate_infer_infer(tcx).args_may_unify(impl1_args, impl2_args);
142
143    if !may_overlap {
144        // Some types involved are definitely different, so the impls couldn't possibly overlap.
145        debug!("overlapping_impls: fast_reject early-exit");
146        return None;
147    }
148
149    overlapping_impls(tcx, impl1_def_id, impl2_def_id, skip_leak_check, overlap_mode, true)
150}
151
152fn overlapping_impls(
153    tcx: TyCtxt<'_>,
154    impl1_def_id: DefId,
155    impl2_def_id: DefId,
156    skip_leak_check: SkipLeakCheck,
157    overlap_mode: OverlapMode,
158    is_of_trait: bool,
159) -> Option<OverlapResult<'_>> {
160    if tcx.next_trait_solver_in_coherence() {
161        overlap(
162            tcx,
163            TrackAmbiguityCauses::Yes,
164            skip_leak_check,
165            impl1_def_id,
166            impl2_def_id,
167            overlap_mode,
168            is_of_trait,
169        )
170    } else {
171        let _overlap_with_bad_diagnostics = overlap(
172            tcx,
173            TrackAmbiguityCauses::No,
174            skip_leak_check,
175            impl1_def_id,
176            impl2_def_id,
177            overlap_mode,
178            is_of_trait,
179        )?;
180
181        // In the case where we detect an error, run the check again, but
182        // this time tracking intercrate ambiguity causes for better
183        // diagnostics. (These take time and can lead to false errors.)
184        let overlap = overlap(
185            tcx,
186            TrackAmbiguityCauses::Yes,
187            skip_leak_check,
188            impl1_def_id,
189            impl2_def_id,
190            overlap_mode,
191            is_of_trait,
192        )
193        .unwrap();
194        Some(overlap)
195    }
196}
197
198fn fresh_impl_header<'tcx>(
199    infcx: &InferCtxt<'tcx>,
200    impl_def_id: DefId,
201    is_of_trait: bool,
202) -> ImplHeader<'tcx> {
203    let tcx = infcx.tcx;
204    let impl_args = infcx.fresh_args_for_item(DUMMY_SP, impl_def_id);
205
206    ImplHeader {
207        impl_args,
208        self_ty: tcx.type_of(impl_def_id).instantiate(tcx, impl_args).skip_norm_wip(),
209        trait_ref: is_of_trait
210            .then(|| tcx.impl_trait_ref(impl_def_id).instantiate(tcx, impl_args).skip_norm_wip()),
211        predicates: tcx
212            .clauses_of(impl_def_id)
213            .instantiate(tcx, impl_args)
214            .iter()
215            .map(|(c, _)| c.skip_norm_wip().as_predicate())
216            .collect(),
217    }
218}
219
220fn fresh_impl_header_normalized<'tcx>(
221    infcx: &InferCtxt<'tcx>,
222    param_env: ty::ParamEnv<'tcx>,
223    impl_def_id: DefId,
224    is_of_trait: bool,
225) -> ImplHeader<'tcx> {
226    let header = fresh_impl_header(infcx, impl_def_id, is_of_trait);
227
228    let InferOk { value: mut header, obligations } =
229        infcx.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(header));
230
231    header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
232    header
233}
234
235/// Can both impl `a` and impl `b` be satisfied by a common type (including
236/// where-clauses)? If so, returns an `ImplHeader` that unifies the two impls.
237{}
#[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("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(237u32),
                                    ::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 /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs:292",
                                    "rustc_trait_selection::traits::coherence",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(292u32),
                                    ::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 /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs:313",
                                        "rustc_trait_selection::traits::coherence",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                        ::tracing_core::__macro_support::Option::Some(313u32),
                                        ::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 /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs:325",
                                    "rustc_trait_selection::traits::coherence",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(325u32),
                                    ::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.deeply_resolve_ignoring_regions(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))]
238fn overlap<'tcx>(
239    tcx: TyCtxt<'tcx>,
240    track_ambiguity_causes: TrackAmbiguityCauses,
241    skip_leak_check: SkipLeakCheck,
242    impl1_def_id: DefId,
243    impl2_def_id: DefId,
244    overlap_mode: OverlapMode,
245    is_of_trait: bool,
246) -> Option<OverlapResult<'tcx>> {
247    if overlap_mode.use_negative_impl() {
248        if impl_intersection_has_negative_obligation(tcx, impl1_def_id, impl2_def_id, is_of_trait)
249            || impl_intersection_has_negative_obligation(
250                tcx,
251                impl2_def_id,
252                impl1_def_id,
253                is_of_trait,
254            )
255        {
256            return None;
257        }
258    }
259
260    let infcx = tcx
261        .infer_ctxt()
262        .skip_leak_check(skip_leak_check.is_yes())
263        .with_next_trait_solver(tcx.next_trait_solver_in_coherence())
264        .enable_next_solver_overflow_fcw(false)
265        .build(TypingMode::Coherence);
266    let selcx = &mut SelectionContext::new(&infcx);
267    if track_ambiguity_causes.is_yes() {
268        selcx.enable_tracking_intercrate_ambiguity_causes();
269    }
270
271    // For the purposes of this check, we don't bring any placeholder
272    // types into scope; instead, we replace the generic types with
273    // fresh type variables, and hence we do our evaluations in an
274    // empty environment.
275    let param_env = ty::ParamEnv::empty();
276
277    let impl1_header = if tcx.next_trait_solver_in_coherence() {
278        fresh_impl_header(selcx.infcx, impl1_def_id, is_of_trait)
279    } else {
280        fresh_impl_header_normalized(selcx.infcx, param_env, impl1_def_id, is_of_trait)
281    };
282    let impl2_header = if tcx.next_trait_solver_in_coherence() {
283        fresh_impl_header(selcx.infcx, impl2_def_id, is_of_trait)
284    } else {
285        fresh_impl_header_normalized(selcx.infcx, param_env, impl2_def_id, is_of_trait)
286    };
287
288    // Equate the headers to find their intersection (the general type, with infer vars,
289    // that may apply both impls).
290    let mut obligations =
291        equate_impl_headers(selcx.infcx, param_env, &impl1_header, &impl2_header)?;
292    debug!("overlap: unification check succeeded");
293
294    obligations.extend(
295        [&impl1_header.predicates, &impl2_header.predicates].into_iter().flatten().map(
296            |&predicate| Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, predicate),
297        ),
298    );
299
300    let mut overflowing_predicates = Vec::new();
301    if overlap_mode.use_implicit_negative() {
302        match impl_intersection_has_impossible_obligation(selcx, &obligations) {
303            IntersectionHasImpossibleObligations::Yes => return None,
304            IntersectionHasImpossibleObligations::No { overflowing_predicates: p } => {
305                overflowing_predicates = p
306            }
307        }
308    }
309
310    // We toggle the `leak_check` by using `skip_leak_check` when constructing the
311    // inference context, so this may be a noop.
312    if infcx.leak_check(ty::UniverseIndex::ROOT, None).is_err() {
313        debug!("overlap: leak check failed");
314        return None;
315    }
316
317    let intercrate_ambiguity_causes = if !overlap_mode.use_implicit_negative() {
318        Default::default()
319    } else if infcx.next_trait_solver() {
320        compute_intercrate_ambiguity_causes(&infcx, &obligations)
321    } else {
322        selcx.take_intercrate_ambiguity_causes()
323    };
324
325    debug!("overlap: intercrate_ambiguity_causes={:#?}", intercrate_ambiguity_causes);
326    let involves_placeholder = infcx
327        .inner
328        .borrow_mut()
329        .unwrap_region_constraints()
330        .data()
331        .constraints
332        .iter()
333        .any(|c| c.0.involves_placeholders());
334
335    let mut impl_header = infcx.deeply_resolve_ignoring_regions(impl1_header);
336
337    // Deeply normalize the impl header for diagnostics, ignoring any errors if this fails.
338    if infcx.next_trait_solver() {
339        impl_header = deeply_normalize_for_diagnostics(&infcx, param_env, impl_header);
340    }
341
342    Some(OverlapResult {
343        impl_header,
344        intercrate_ambiguity_causes,
345        involves_placeholder,
346        overflowing_predicates,
347    })
348}
349
350{}
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("equate_impl_headers",
                                "rustc_trait_selection::traits::coherence",
                                ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                ::tracing_core::__macro_support::Option::Some(350u32),
                                ::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("param_env")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("param_env");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("impl1")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("impl1");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("impl2")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("impl2");
                                                    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(&param_env)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl1)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl2)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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<PredicateObligations<'tcx>> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let result =
                            match (impl1.trait_ref, impl2.trait_ref) {
                                (Some(impl1_ref), Some(impl2_ref)) =>
                                    infcx.at(&ObligationCause::dummy(),
                                            param_env).eq(DefineOpaqueTypes::Yes, impl1_ref, impl2_ref),
                                (None, None) =>
                                    infcx.at(&ObligationCause::dummy(),
                                            param_env).eq(DefineOpaqueTypes::Yes, impl1.self_ty,
                                        impl2.self_ty),
                                _ =>
                                    ::rustc_span::macros::bug_impl(None,
                                        format_args!("equate_impl_headers given mismatched impl kinds"),
                                        Location::caller()),
                            };
                        result.map(|infer_ok| infer_ok.obligations).ok()
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs:350",
                        "rustc_trait_selection::traits::coherence",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                        ::tracing_core::__macro_support::Option::Some(350u32),
                        ::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("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::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(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(infcx), ret)]
351fn equate_impl_headers<'tcx>(
352    infcx: &InferCtxt<'tcx>,
353    param_env: ty::ParamEnv<'tcx>,
354    impl1: &ImplHeader<'tcx>,
355    impl2: &ImplHeader<'tcx>,
356) -> Option<PredicateObligations<'tcx>> {
357    let result =
358        match (impl1.trait_ref, impl2.trait_ref) {
359            (Some(impl1_ref), Some(impl2_ref)) => infcx
360                .at(&ObligationCause::dummy(), param_env)
361                .eq(DefineOpaqueTypes::Yes, impl1_ref, impl2_ref),
362            (None, None) => infcx.at(&ObligationCause::dummy(), param_env).eq(
363                DefineOpaqueTypes::Yes,
364                impl1.self_ty,
365                impl2.self_ty,
366            ),
367            _ => bug!("equate_impl_headers given mismatched impl kinds"),
368        };
369
370    result.map(|infer_ok| infer_ok.obligations).ok()
371}
372
373/// The result of [fn impl_intersection_has_impossible_obligation].
374#[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 {
            Self::Yes => ::core::fmt::Formatter::write_str(f, "Yes"),
            Self::No { overflowing_predicates: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "No",
                    "overflowing_predicates", &__self_0),
        }
    }
}Debug)]
375enum IntersectionHasImpossibleObligations<'tcx> {
376    Yes,
377    No {
378        /// With `-Znext-solver=coherence`, some obligations may
379        /// fail if only the user increased the recursion limit.
380        ///
381        /// We return those obligations here and mention them in the
382        /// error message.
383        overflowing_predicates: Vec<ty::Predicate<'tcx>>,
384    },
385}
386
387/// Check if both impls can be satisfied by a common type by considering whether
388/// any of either impl's obligations is not known to hold.
389///
390/// For example, given these two impls:
391///     `impl From<MyLocalType> for Box<dyn Error>` (in my crate)
392///     `impl<E> From<E> for Box<dyn Error> where E: Error` (in libstd)
393///
394/// After replacing both impl headers with inference vars (which happens before
395/// this function is called), we get:
396///     `Box<dyn Error>: From<MyLocalType>`
397///     `Box<dyn Error>: From<?E>`
398///
399/// This gives us `?E = MyLocalType`. We then certainly know that `MyLocalType: Error`
400/// never holds in intercrate mode since a local impl does not exist, and a
401/// downstream impl cannot be added -- therefore can consider the intersection
402/// of the two impls above to be empty.
403///
404/// Importantly, this works even if there isn't a `impl !Error for MyLocalType`.
405{}
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("impl_intersection_has_impossible_obligation",
                                "rustc_trait_selection::traits::coherence",
                                ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                ::tracing_core::__macro_support::Option::Some(405u32),
                                ::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("obligations")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("obligations");
                                                    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(&obligations)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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:
                                IntersectionHasImpossibleObligations<'tcx> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let infcx = selcx.infcx;
                        if infcx.next_trait_solver() {
                            if !obligations.iter().all(|o|
                                            {
                                                <&SolverDelegate<'tcx>>::from(infcx).root_goal_may_hold_with_depth(8,
                                                    Goal::new(infcx.tcx, o.param_env, o.predicate))
                                            }) {
                                return IntersectionHasImpossibleObligations::Yes;
                            }
                            let ocx = ObligationCtxt::new(infcx);
                            ocx.register_obligations(obligations.iter().cloned());
                            let hard_errors = ocx.try_evaluate_obligations();
                            if let TraitErrors::HasErrors(hard_errors) = hard_errors {
                                if !hard_errors.iter().all(|e| e.is_true_error()) {
                                    {
                                        ::core::panicking::panic_fmt(format_args!("should not have detected ambiguity during first pass"));
                                    }
                                };
                                return IntersectionHasImpossibleObligations::Yes;
                            }
                            let ambiguities = ocx.into_pending_obligations();
                            let ocx = ObligationCtxt::new_with_diagnostics(infcx);
                            ocx.register_obligations(ambiguities);
                            let errors_and_ambiguities =
                                ocx.evaluate_obligations_error_on_ambiguity();
                            let (errors, ambiguities): (Vec<_>, Vec<_>) =
                                errors_and_ambiguities.into_iter().partition(|error|
                                        error.is_true_error());
                            if !errors.is_empty() {
                                {
                                    ::core::panicking::panic_fmt(format_args!("should not have ambiguities during second pass"));
                                }
                            };
                            IntersectionHasImpossibleObligations::No {
                                overflowing_predicates: ambiguities.into_iter().filter(|error|
                                                {

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