Skip to main content

rustc_trait_selection/traits/
coherence.rs

1//! See Rustc Dev Guide chapters on [trait-resolution] and [trait-specialization] for more info on
2//! how this works.
3//!
4//! [trait-resolution]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
5//! [trait-specialization]: https://rustc-dev-guide.rust-lang.org/traits/specialization.html
6
7use std::fmt::Debug;
8
9use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
10use rustc_errors::{Diag, EmissionGuarantee};
11use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
12use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt};
13use rustc_infer::traits::{PredicateObligations, TraitErrors};
14use rustc_macros::{TypeFoldable, TypeVisitable};
15use rustc_middle::bug;
16use rustc_middle::traits::query::NoSolution;
17use rustc_middle::traits::solve::{CandidateSource, Certainty, Goal};
18use rustc_middle::traits::specialization_graph::OverlapMode;
19use rustc_middle::ty::fast_reject::DeepRejectCtxt;
20use rustc_middle::ty::{
21    self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
22    Unnormalized,
23};
24pub use rustc_next_trait_solver::coherence::*;
25use rustc_next_trait_solver::solve::SolverDelegateEvalExt;
26use rustc_span::{DUMMY_SP, Span};
27use tracing::{debug, instrument, warn};
28
29use super::ObligationCtxt;
30use crate::error_reporting::traits::suggest_new_overflow_limit;
31use crate::infer::InferOk;
32use crate::solve::inspect::{InferCtxtProofTreeExt, InspectGoal, ProofTreeVisitor};
33use crate::solve::{SolverDelegate, deeply_normalize_for_diagnostics, inspect};
34use crate::traits::query::evaluate_obligation::InferCtxtExt;
35use crate::traits::select::IntercrateAmbiguityCause;
36use crate::traits::{
37    FulfillmentErrorCode, NormalizeExt, Obligation, ObligationCause, PredicateObligation,
38    SelectionContext, SkipLeakCheck, util,
39};
40
41/// The "header" of an impl is everything outside the body: a Self type, a trait
42/// ref (in the case of a trait impl), and a set of predicates (from the
43/// bounds / where-clauses).
44#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ImplHeader<'tcx> {
    #[inline]
    fn clone(&self) -> ImplHeader<'tcx> {
        ImplHeader {
            impl_args: ::core::clone::Clone::clone(&self.impl_args),
            self_ty: ::core::clone::Clone::clone(&self.self_ty),
            trait_ref: ::core::clone::Clone::clone(&self.trait_ref),
            predicates: ::core::clone::Clone::clone(&self.predicates),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ImplHeader<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "ImplHeader",
            "impl_args", &self.impl_args, "self_ty", &self.self_ty,
            "trait_ref", &self.trait_ref, "predicates", &&self.predicates)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ImplHeader<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        ImplHeader {
                            impl_args: __binding_0,
                            self_ty: __binding_1,
                            trait_ref: __binding_2,
                            predicates: __binding_3 } => {
                            ImplHeader {
                                impl_args: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                self_ty: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                trait_ref: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                                predicates: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_3,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    ImplHeader {
                        impl_args: __binding_0,
                        self_ty: __binding_1,
                        trait_ref: __binding_2,
                        predicates: __binding_3 } => {
                        ImplHeader {
                            impl_args: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            self_ty: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            trait_ref: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                            predicates: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_3,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ImplHeader<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    ImplHeader {
                        impl_args: ref __binding_0,
                        self_ty: ref __binding_1,
                        trait_ref: ref __binding_2,
                        predicates: ref __binding_3 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_3,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
45pub struct ImplHeader<'tcx> {
46    pub impl_args: ty::GenericArgsRef<'tcx>,
47    pub self_ty: Ty<'tcx>,
48    pub trait_ref: Option<ty::TraitRef<'tcx>>,
49    pub predicates: Vec<ty::Predicate<'tcx>>,
50}
51
52pub struct OverlapResult<'tcx> {
53    pub impl_header: ImplHeader<'tcx>,
54    pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
55
56    /// `true` if the overlap might've been permitted before the shift
57    /// to universes.
58    pub involves_placeholder: bool,
59
60    /// Used in the new solver to suggest increasing the recursion limit.
61    pub overflowing_predicates: Vec<ty::Predicate<'tcx>>,
62}
63
64pub fn add_placeholder_note<G: EmissionGuarantee>(err: &mut Diag<'_, G>) {
65    err.note(
66        "this behavior recently changed as a result of a bug fix; \
67         see rust-lang/rust#56105 for details",
68    );
69}
70
71pub(crate) fn suggest_increasing_recursion_limit<'tcx, G: EmissionGuarantee>(
72    tcx: TyCtxt<'tcx>,
73    err: &mut Diag<'_, G>,
74    overflowing_predicates: &[ty::Predicate<'tcx>],
75) {
76    for pred in overflowing_predicates {
77        err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("overflow evaluating the requirement `{0}`",
                pred))
    })format!("overflow evaluating the requirement `{}`", pred));
78    }
79
80    suggest_new_overflow_limit(tcx, err);
81}
82
83#[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) -> TrackAmbiguityCauses { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for TrackAmbiguityCauses { }Copy)]
84enum TrackAmbiguityCauses {
85    Yes,
86    No,
87}
88
89impl TrackAmbiguityCauses {
90    fn is_yes(self) -> bool {
91        match self {
92            TrackAmbiguityCauses::Yes => true,
93            TrackAmbiguityCauses::No => false,
94        }
95    }
96}
97
98/// If there are types that satisfy both impls, returns `Some`
99/// with a suitably-freshened `ImplHeader` with those types
100/// instantiated. Otherwise, returns `None`.
101{}
#[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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(101u32),
                                    ::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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs:118",
                                        "rustc_trait_selection::traits::coherence",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                        ::tracing_core::__macro_support::Option::Some(118u32),
                                        ::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")]
102pub fn overlapping_inherent_impls(
103    tcx: TyCtxt<'_>,
104    impl1_def_id: DefId,
105    impl2_def_id: DefId,
106    skip_leak_check: SkipLeakCheck,
107    overlap_mode: OverlapMode,
108) -> Option<OverlapResult<'_>> {
109    // Before doing expensive operations like entering an inference context, do
110    // a quick check via fast_reject to tell if the impl headers could possibly
111    // unify.
112    let self_ty1 = tcx.type_of(impl1_def_id).skip_binder();
113    let self_ty2 = tcx.type_of(impl2_def_id).skip_binder();
114    let may_overlap = DeepRejectCtxt::relate_infer_infer(tcx).types_may_unify(self_ty1, self_ty2);
115
116    if !may_overlap {
117        // Some types involved are definitely different, so the impls couldn't possibly overlap.
118        debug!("overlapping_inherent_impls: fast_reject early-exit");
119        return None;
120    }
121
122    overlapping_impls(tcx, impl1_def_id, impl2_def_id, skip_leak_check, overlap_mode, false)
123}
124
125/// If there are types that satisfy both impls, returns `Some`
126/// with a suitably-freshened `ImplHeader` with those types
127/// instantiated. Otherwise, returns `None`.
128{}
#[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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(128u32),
                                    ::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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs:146",
                                        "rustc_trait_selection::traits::coherence",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                        ::tracing_core::__macro_support::Option::Some(146u32),
                                        ::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")]
129pub fn overlapping_trait_impls(
130    tcx: TyCtxt<'_>,
131    impl1_def_id: DefId,
132    impl2_def_id: DefId,
133    skip_leak_check: SkipLeakCheck,
134    overlap_mode: OverlapMode,
135) -> Option<OverlapResult<'_>> {
136    // Before doing expensive operations like entering an inference context, do
137    // a quick check via fast_reject to tell if the impl headers could possibly
138    // unify.
139    let impl1_args = tcx.impl_trait_ref(impl1_def_id).skip_binder().args;
140    let impl2_args = tcx.impl_trait_ref(impl2_def_id).skip_binder().args;
141    let may_overlap =
142        DeepRejectCtxt::relate_infer_infer(tcx).args_may_unify(impl1_args, impl2_args);
143
144    if !may_overlap {
145        // Some types involved are definitely different, so the impls couldn't possibly overlap.
146        debug!("overlapping_impls: fast_reject early-exit");
147        return None;
148    }
149
150    overlapping_impls(tcx, impl1_def_id, impl2_def_id, skip_leak_check, overlap_mode, true)
151}
152
153fn overlapping_impls(
154    tcx: TyCtxt<'_>,
155    impl1_def_id: DefId,
156    impl2_def_id: DefId,
157    skip_leak_check: SkipLeakCheck,
158    overlap_mode: OverlapMode,
159    is_of_trait: bool,
160) -> Option<OverlapResult<'_>> {
161    if tcx.next_trait_solver_in_coherence() {
162        overlap(
163            tcx,
164            TrackAmbiguityCauses::Yes,
165            skip_leak_check,
166            impl1_def_id,
167            impl2_def_id,
168            overlap_mode,
169            is_of_trait,
170        )
171    } else {
172        let _overlap_with_bad_diagnostics = overlap(
173            tcx,
174            TrackAmbiguityCauses::No,
175            skip_leak_check,
176            impl1_def_id,
177            impl2_def_id,
178            overlap_mode,
179            is_of_trait,
180        )?;
181
182        // In the case where we detect an error, run the check again, but
183        // this time tracking intercrate ambiguity causes for better
184        // diagnostics. (These take time and can lead to false errors.)
185        let overlap = overlap(
186            tcx,
187            TrackAmbiguityCauses::Yes,
188            skip_leak_check,
189            impl1_def_id,
190            impl2_def_id,
191            overlap_mode,
192            is_of_trait,
193        )
194        .unwrap();
195        Some(overlap)
196    }
197}
198
199fn fresh_impl_header<'tcx>(
200    infcx: &InferCtxt<'tcx>,
201    impl_def_id: DefId,
202    is_of_trait: bool,
203) -> ImplHeader<'tcx> {
204    let tcx = infcx.tcx;
205    let impl_args = infcx.fresh_args_for_item(DUMMY_SP, impl_def_id);
206
207    ImplHeader {
208        impl_args,
209        self_ty: tcx.type_of(impl_def_id).instantiate(tcx, impl_args).skip_norm_wip(),
210        trait_ref: is_of_trait
211            .then(|| tcx.impl_trait_ref(impl_def_id).instantiate(tcx, impl_args).skip_norm_wip()),
212        predicates: tcx
213            .clauses_of(impl_def_id)
214            .instantiate(tcx, impl_args)
215            .iter()
216            .map(|(c, _)| c.skip_norm_wip().as_predicate())
217            .collect(),
218    }
219}
220
221fn fresh_impl_header_normalized<'tcx>(
222    infcx: &InferCtxt<'tcx>,
223    param_env: ty::ParamEnv<'tcx>,
224    impl_def_id: DefId,
225    is_of_trait: bool,
226) -> ImplHeader<'tcx> {
227    let header = fresh_impl_header(infcx, impl_def_id, is_of_trait);
228
229    let InferOk { value: mut header, obligations } =
230        infcx.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(header));
231
232    header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
233    header
234}
235
236/// Can both impl `a` and impl `b` be satisfied by a common type (including
237/// where-clauses)? If so, returns an `ImplHeader` that unifies the two impls.
238{}
#[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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(238u32),
                                    ::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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs:293",
                                    "rustc_trait_selection::traits::coherence",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(293u32),
                                    ::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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs:314",
                                        "rustc_trait_selection::traits::coherence",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                        ::tracing_core::__macro_support::Option::Some(314u32),
                                        ::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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs:326",
                                    "rustc_trait_selection::traits::coherence",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(326u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("overlap: intercrate_ambiguity_causes={0:#?}",
                                                                intercrate_ambiguity_causes) as
                                                        &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let involves_placeholder =
                infcx.inner.borrow_mut().unwrap_region_constraints().data().constraints.iter().any(|c|
                        c.0.involves_placeholders());
            let mut impl_header =
                infcx.resolve_vars_if_possible(impl1_header);
            if infcx.next_trait_solver() {
                impl_header =
                    deeply_normalize_for_diagnostics(&infcx, param_env,
                        impl_header);
            }
            Some(OverlapResult {
                    impl_header,
                    intercrate_ambiguity_causes,
                    involves_placeholder,
                    overflowing_predicates,
                })
        }
    }
}#[instrument(level = "debug", skip(tcx))]
239fn overlap<'tcx>(
240    tcx: TyCtxt<'tcx>,
241    track_ambiguity_causes: TrackAmbiguityCauses,
242    skip_leak_check: SkipLeakCheck,
243    impl1_def_id: DefId,
244    impl2_def_id: DefId,
245    overlap_mode: OverlapMode,
246    is_of_trait: bool,
247) -> Option<OverlapResult<'tcx>> {
248    if overlap_mode.use_negative_impl() {
249        if impl_intersection_has_negative_obligation(tcx, impl1_def_id, impl2_def_id, is_of_trait)
250            || impl_intersection_has_negative_obligation(
251                tcx,
252                impl2_def_id,
253                impl1_def_id,
254                is_of_trait,
255            )
256        {
257            return None;
258        }
259    }
260
261    let infcx = tcx
262        .infer_ctxt()
263        .skip_leak_check(skip_leak_check.is_yes())
264        .with_next_trait_solver(tcx.next_trait_solver_in_coherence())
265        .enable_next_solver_overflow_fcw(false)
266        .build(TypingMode::Coherence);
267    let selcx = &mut SelectionContext::new(&infcx);
268    if track_ambiguity_causes.is_yes() {
269        selcx.enable_tracking_intercrate_ambiguity_causes();
270    }
271
272    // For the purposes of this check, we don't bring any placeholder
273    // types into scope; instead, we replace the generic types with
274    // fresh type variables, and hence we do our evaluations in an
275    // empty environment.
276    let param_env = ty::ParamEnv::empty();
277
278    let impl1_header = if tcx.next_trait_solver_in_coherence() {
279        fresh_impl_header(selcx.infcx, impl1_def_id, is_of_trait)
280    } else {
281        fresh_impl_header_normalized(selcx.infcx, param_env, impl1_def_id, is_of_trait)
282    };
283    let impl2_header = if tcx.next_trait_solver_in_coherence() {
284        fresh_impl_header(selcx.infcx, impl2_def_id, is_of_trait)
285    } else {
286        fresh_impl_header_normalized(selcx.infcx, param_env, impl2_def_id, is_of_trait)
287    };
288
289    // Equate the headers to find their intersection (the general type, with infer vars,
290    // that may apply both impls).
291    let mut obligations =
292        equate_impl_headers(selcx.infcx, param_env, &impl1_header, &impl2_header)?;
293    debug!("overlap: unification check succeeded");
294
295    obligations.extend(
296        [&impl1_header.predicates, &impl2_header.predicates].into_iter().flatten().map(
297            |&predicate| Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, predicate),
298        ),
299    );
300
301    let mut overflowing_predicates = Vec::new();
302    if overlap_mode.use_implicit_negative() {
303        match impl_intersection_has_impossible_obligation(selcx, &obligations) {
304            IntersectionHasImpossibleObligations::Yes => return None,
305            IntersectionHasImpossibleObligations::No { overflowing_predicates: p } => {
306                overflowing_predicates = p
307            }
308        }
309    }
310
311    // We toggle the `leak_check` by using `skip_leak_check` when constructing the
312    // inference context, so this may be a noop.
313    if infcx.leak_check(ty::UniverseIndex::ROOT, None).is_err() {
314        debug!("overlap: leak check failed");
315        return None;
316    }
317
318    let intercrate_ambiguity_causes = if !overlap_mode.use_implicit_negative() {
319        Default::default()
320    } else if infcx.next_trait_solver() {
321        compute_intercrate_ambiguity_causes(&infcx, &obligations)
322    } else {
323        selcx.take_intercrate_ambiguity_causes()
324    };
325
326    debug!("overlap: intercrate_ambiguity_causes={:#?}", intercrate_ambiguity_causes);
327    let involves_placeholder = infcx
328        .inner
329        .borrow_mut()
330        .unwrap_region_constraints()
331        .data()
332        .constraints
333        .iter()
334        .any(|c| c.0.involves_placeholders());
335
336    let mut impl_header = infcx.resolve_vars_if_possible(impl1_header);
337
338    // Deeply normalize the impl header for diagnostics, ignoring any errors if this fails.
339    if infcx.next_trait_solver() {
340        impl_header = deeply_normalize_for_diagnostics(&infcx, param_env, impl_header);
341    }
342
343    Some(OverlapResult {
344        impl_header,
345        intercrate_ambiguity_causes,
346        involves_placeholder,
347        overflowing_predicates,
348    })
349}
350
351{}
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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                ::tracing_core::__macro_support::Option::Some(351u32),
                                ::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_middle::util::bug::bug_fmt(format_args!("equate_impl_headers given mismatched impl kinds")),
                            };
                        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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs:351",
                        "rustc_trait_selection::traits::coherence",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                        ::tracing_core::__macro_support::Option::Some(351u32),
                        ::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)]
352fn equate_impl_headers<'tcx>(
353    infcx: &InferCtxt<'tcx>,
354    param_env: ty::ParamEnv<'tcx>,
355    impl1: &ImplHeader<'tcx>,
356    impl2: &ImplHeader<'tcx>,
357) -> Option<PredicateObligations<'tcx>> {
358    let result =
359        match (impl1.trait_ref, impl2.trait_ref) {
360            (Some(impl1_ref), Some(impl2_ref)) => infcx
361                .at(&ObligationCause::dummy(), param_env)
362                .eq(DefineOpaqueTypes::Yes, impl1_ref, impl2_ref),
363            (None, None) => infcx.at(&ObligationCause::dummy(), param_env).eq(
364                DefineOpaqueTypes::Yes,
365                impl1.self_ty,
366                impl2.self_ty,
367            ),
368            _ => bug!("equate_impl_headers given mismatched impl kinds"),
369        };
370
371    result.map(|infer_ok| infer_ok.obligations).ok()
372}
373
374/// The result of [fn impl_intersection_has_impossible_obligation].
375#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for IntersectionHasImpossibleObligations<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            IntersectionHasImpossibleObligations::Yes =>
                ::core::fmt::Formatter::write_str(f, "Yes"),
            IntersectionHasImpossibleObligations::No {
                overflowing_predicates: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "No",
                    "overflowing_predicates", &__self_0),
        }
    }
}Debug)]
376enum IntersectionHasImpossibleObligations<'tcx> {
377    Yes,
378    No {
379        /// With `-Znext-solver=coherence`, some obligations may
380        /// fail if only the user increased the recursion limit.
381        ///
382        /// We return those obligations here and mention them in the
383        /// error message.
384        overflowing_predicates: Vec<ty::Predicate<'tcx>>,
385    },
386}
387
388/// Check if both impls can be satisfied by a common type by considering whether
389/// any of either impl's obligations is not known to hold.
390///
391/// For example, given these two impls:
392///     `impl From<MyLocalType> for Box<dyn Error>` (in my crate)
393///     `impl<E> From<E> for Box<dyn Error> where E: Error` (in libstd)
394///
395/// After replacing both impl headers with inference vars (which happens before
396/// this function is called), we get:
397///     `Box<dyn Error>: From<MyLocalType>`
398///     `Box<dyn Error>: From<?E>`
399///
400/// This gives us `?E = MyLocalType`. We then certainly know that `MyLocalType: Error`
401/// never holds in intercrate mode since a local impl does not exist, and a
402/// downstream impl cannot be added -- therefore can consider the intersection
403/// of the two impls above to be empty.
404///
405/// Importantly, this works even if there isn't a `impl !Error for MyLocalType`.
406{}
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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                ::tracing_core::__macro_support::Option::Some(406u32),
                                ::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.resolve_vars_if_possible(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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs:406",
                        "rustc_trait_selection::traits::coherence",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                        ::tracing_core::__macro_support::Option::Some(406u32),
                        ::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)]
407fn impl_intersection_has_impossible_obligation<'a, 'cx, 'tcx>(
408    selcx: &mut SelectionContext<'cx, 'tcx>,
409    obligations: &'a [PredicateObligation<'tcx>],
410) -> IntersectionHasImpossibleObligations<'tcx> {
411    let infcx = selcx.infcx;
412
413    if infcx.next_trait_solver() {
414        // A fast path optimization, try evaluating all goals with
415        // a very low recursion depth and bail if any of them don't
416        // hold.
417        if !obligations.iter().all(|o| {
418            <&SolverDelegate<'tcx>>::from(infcx)
419                .root_goal_may_hold_with_depth(8, Goal::new(infcx.tcx, o.param_env, o.predicate))
420        }) {
421            return IntersectionHasImpossibleObligations::Yes;
422        }
423
424        let ocx = ObligationCtxt::new(infcx);
425        ocx.register_obligations(obligations.iter().cloned());
426        let hard_errors = ocx.try_evaluate_obligations();
427        if let TraitErrors::HasErrors(hard_errors) = hard_errors {
428            assert!(
429                hard_errors.iter().all(|e| e.is_true_error()),
430                "should not have detected ambiguity during first pass"
431            );
432            return IntersectionHasImpossibleObligations::Yes;
433        }
434
435        // Make a new `ObligationCtxt` and re-prove the ambiguities with a richer
436        // `FulfillmentError`. This is so that we can detect overflowing obligations
437        // without needing to run the `BestObligation` visitor on true errors.
438        let ambiguities = ocx.into_pending_obligations();
439        let ocx = ObligationCtxt::new_with_diagnostics(infcx);
440        ocx.register_obligations(ambiguities);
441        let errors_and_ambiguities = ocx.evaluate_obligations_error_on_ambiguity();
442        // We only care about the obligations that are *definitely* true errors.
443        // Ambiguities do not prove the disjointness of two impls.
444        let (errors, ambiguities): (Vec<_>, Vec<_>) =
445            errors_and_ambiguities.into_iter().partition(|error| error.is_true_error());
446        assert!(errors.is_empty(), "should not have ambiguities during second pass");
447
448        IntersectionHasImpossibleObligations::No {
449            overflowing_predicates: ambiguities
450                .into_iter()
451                .filter(|error| {
452                    matches!(error.code, FulfillmentErrorCode::Ambiguity { overflow: Some(true) })
453                })
454                .map(|e| infcx.resolve_vars_if_possible(e.obligation.predicate))
455                .collect(),
456        }
457    } else {
458        for obligation in obligations {
459            // We use `evaluate_root_obligation` to correctly track intercrate
460            // ambiguity clauses.
461            let evaluation_result = selcx.evaluate_root_obligation(obligation);
462
463            match evaluation_result {
464                Ok(result) => {
465                    if !result.may_apply() {
466                        return IntersectionHasImpossibleObligations::Yes;
467                    }
468                }
469                // If overflow occurs, we need to conservatively treat the goal as possibly holding,
470                // since there can be instantiations of this goal that don't overflow and result in
471                // success. While this isn't much of a problem in the old solver, since we treat overflow
472                // fatally, this still can be encountered: <https://github.com/rust-lang/rust/issues/105231>.
473                Err(_overflow) => {}
474            }
475        }
476
477        IntersectionHasImpossibleObligations::No { overflowing_predicates: Vec::new() }
478    }
479}
480
481/// Check if both impls can be satisfied by a common type by considering whether
482/// any of first impl's obligations is known not to hold *via a negative predicate*.
483///
484/// For example, given these two impls:
485///     `struct MyCustomBox<T: ?Sized>(Box<T>);`
486///     `impl From<&str> for MyCustomBox<dyn Error>` (in my crate)
487///     `impl<E> From<E> for MyCustomBox<dyn Error> where E: Error` (in my crate)
488///
489/// After replacing the second impl's header with inference vars, we get:
490///     `MyCustomBox<dyn Error>: From<&str>`
491///     `MyCustomBox<dyn Error>: From<?E>`
492///
493/// This gives us `?E = &str`. We then try to prove the first impl's predicates
494/// after negating, giving us `&str: !Error`. This is a negative impl provided by
495/// libstd, and therefore we can guarantee for certain that libstd will never add
496/// a positive impl for `&str: Error` (without it being a breaking change).
497fn impl_intersection_has_negative_obligation(
498    tcx: TyCtxt<'_>,
499    impl1_def_id: DefId,
500    impl2_def_id: DefId,
501    is_of_trait: bool,
502) -> bool {
503    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs:503",
                        "rustc_trait_selection::traits::coherence",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/coherence.rs"),
                        ::tracing_core::__macro_support::Option::Some(503u32),
                        ::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);
504
505    // N.B. We need to unify impl headers *with* `TypingMode::Coherence`,
506    // even if proving negative predicates doesn't need `TypingMode::Coherence`.
507    let ref infcx = tcx
508        .infer_ctxt()
509        .with_next_trait_solver(true)
510        .enable_next_solver_overflow_fcw(false)
511        .build(TypingMode::Coherence);
512    let root_universe = infcx.universe();
513    {
    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);
514
515    let impl1_header = fresh_impl_header(infcx, impl1_def_id, is_of_trait);
516    let impl2_header = fresh_impl_header(infcx, impl2_def_id, is_of_trait);
517
518    // Equate the headers to find their intersection (the general type, with infer vars,
519    // that may apply both impls).
520    let Some(equate_obligations) =
521        equate_impl_headers(infcx, ty::ParamEnv::empty(), &impl1_header, &impl2_header)
522    else {
523        return false;
524    };
525
526    // FIXME(with_negative_coherence): the infcx has constraints from equating
527    // the impl headers. We should use these constraints as assumptions, not as
528    // requirements, when proving the negated where clauses below.
529    drop(equate_obligations);
530    drop(infcx.take_registered_region_obligations());
531    drop(infcx.take_registered_region_assumptions());
532    drop(infcx.take_and_reset_region_constraints());
533
534    plug_infer_with_placeholders(
535        infcx,
536        root_universe,
537        (impl1_header.impl_args, impl2_header.impl_args),
538    );
539
540    // Right above we plug inference variables with placeholders,
541    // this gets us new impl1_header_args with the inference variables actually resolved
542    // to those placeholders.
543    let impl1_header_args = infcx.resolve_vars_if_possible(impl1_header.impl_args);
544    // So there are no infer variables left now, except regions which aren't resolved by `resolve_vars_if_possible`.
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_middle::util::bug::bug_fmt(format_args!("we always expect to be able to plug an infer var with placeholder"))bug!("we always expect to be able to plug an infer var with placeholder")
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_middle::util::bug::bug_fmt(format_args!("we always expect to be able to plug an infer var with placeholder"))bug!("we always expect to be able to plug an infer var with placeholder")
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                    .opportunistic_resolve_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_middle::util::bug::bug_fmt(format_args!("we always expect to be able to plug an infer var with placeholder"))bug!("we always expect to be able to plug an infer var with placeholder")
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/cea272fa356e94bd2ee2cadf376630aa0683867a/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/cea272fa356e94bd2ee2cadf376630aa0683867a/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}