Skip to main content

rustc_hir_analysis/check/
compare_impl_item.rs

1use core::ops::ControlFlow;
2use std::borrow::Cow;
3use std::iter;
4
5use hir::def_id::{DefId, DefIdMap, LocalDefId};
6use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
7use rustc_errors::codes::*;
8use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan, pluralize, struct_span_code_err};
9use rustc_hir::def::{DefKind, Res};
10use rustc_hir::intravisit::VisitorExt;
11use rustc_hir::{self as hir, AmbigArg, GenericParamKind, ImplItemKind, intravisit};
12use rustc_infer::infer::{self, BoundRegionConversionTime, InferCtxt, TyCtxtInferExt};
13use rustc_infer::traits::util;
14use rustc_middle::ty::error::{ExpectedFound, TypeError};
15use rustc_middle::ty::{
16    self, BottomUpFolder, GenericArgs, GenericParamDefKind, Generics, Ty, TyCtxt, TypeFoldable,
17    TypeFolder, TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
18    Upcast,
19};
20use rustc_middle::{bug, span_bug};
21use rustc_span::{DUMMY_SP, Span};
22use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
23use rustc_trait_selection::infer::InferCtxtExt;
24use rustc_trait_selection::regions::InferCtxtRegionExt;
25use rustc_trait_selection::traits::{
26    self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
27};
28use tracing::{debug, instrument};
29
30use super::potentially_plural_count;
31use crate::errors::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture};
32
33pub(super) mod refine;
34
35/// Call the query `tcx.compare_impl_item()` directly instead.
36pub(super) fn compare_impl_item(
37    tcx: TyCtxt<'_>,
38    impl_item_def_id: LocalDefId,
39) -> Result<(), ErrorGuaranteed> {
40    let impl_item = tcx.associated_item(impl_item_def_id);
41    let trait_item = tcx.associated_item(impl_item.expect_trait_impl()?);
42    let impl_trait_ref = tcx.impl_trait_ref(impl_item.container_id(tcx)).instantiate_identity();
43    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:43",
                        "rustc_hir_analysis::check::compare_impl_item",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                        ::tracing_core::__macro_support::Option::Some(43u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                        ::tracing_core::field::FieldSet::new(&["impl_trait_ref"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&impl_trait_ref)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?impl_trait_ref);
44
45    match impl_item.kind {
46        ty::AssocKind::Fn { .. } => compare_impl_method(tcx, impl_item, trait_item, impl_trait_ref),
47        ty::AssocKind::Type { .. } => compare_impl_ty(tcx, impl_item, trait_item, impl_trait_ref),
48        ty::AssocKind::Const { .. } => {
49            compare_impl_const(tcx, impl_item, trait_item, impl_trait_ref)
50        }
51    }
52}
53
54/// Checks that a method from an impl conforms to the signature of
55/// the same method as declared in the trait.
56///
57/// # Parameters
58///
59/// - `impl_m`: type of the method we are checking
60/// - `trait_m`: the method in the trait
61/// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
62#[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("compare_impl_method",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(62u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["impl_m", "trait_m",
                                                    "impl_trait_ref"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_m)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_m)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            check_method_is_structurally_compatible(tcx, impl_m, trait_m,
                    impl_trait_ref, false)?;
            compare_method_predicate_entailment(tcx, impl_m, trait_m,
                    impl_trait_ref)?;
            Ok(())
        }
    }
}#[instrument(level = "debug", skip(tcx))]
63fn compare_impl_method<'tcx>(
64    tcx: TyCtxt<'tcx>,
65    impl_m: ty::AssocItem,
66    trait_m: ty::AssocItem,
67    impl_trait_ref: ty::TraitRef<'tcx>,
68) -> Result<(), ErrorGuaranteed> {
69    check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, false)?;
70    compare_method_predicate_entailment(tcx, impl_m, trait_m, impl_trait_ref)?;
71    Ok(())
72}
73
74/// Checks a bunch of different properties of the impl/trait methods for
75/// compatibility, such as asyncness, number of argument, self receiver kind,
76/// and number of early- and late-bound generics.
77fn check_method_is_structurally_compatible<'tcx>(
78    tcx: TyCtxt<'tcx>,
79    impl_m: ty::AssocItem,
80    trait_m: ty::AssocItem,
81    impl_trait_ref: ty::TraitRef<'tcx>,
82    delay: bool,
83) -> Result<(), ErrorGuaranteed> {
84    compare_self_type(tcx, impl_m, trait_m, impl_trait_ref, delay)?;
85    compare_number_of_generics(tcx, impl_m, trait_m, delay)?;
86    compare_generic_param_kinds(tcx, impl_m, trait_m, delay)?;
87    compare_number_of_method_arguments(tcx, impl_m, trait_m, delay)?;
88    compare_synthetic_generics(tcx, impl_m, trait_m, delay)?;
89    check_region_bounds_on_impl_item(tcx, impl_m, trait_m, delay)?;
90    Ok(())
91}
92
93/// This function is best explained by example. Consider a trait with its implementation:
94///
95/// ```rust
96/// trait Trait<'t, T> {
97///     // `trait_m`
98///     fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
99/// }
100///
101/// struct Foo;
102///
103/// impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
104///     // `impl_m`
105///     fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo { Foo }
106/// }
107/// ```
108///
109/// We wish to decide if those two method types are compatible.
110/// For this we have to show that, assuming the bounds of the impl hold, the
111/// bounds of `trait_m` imply the bounds of `impl_m`.
112///
113/// We start out with `trait_to_impl_args`, that maps the trait
114/// type parameters to impl type parameters. This is taken from the
115/// impl trait reference:
116///
117/// ```rust,ignore (pseudo-Rust)
118/// trait_to_impl_args = {'t => 'j, T => &'i U, Self => Foo}
119/// ```
120///
121/// We create a mapping `dummy_args` that maps from the impl type
122/// parameters to fresh types and regions. For type parameters,
123/// this is the identity transform, but we could as well use any
124/// placeholder types. For regions, we convert from bound to free
125/// regions (Note: but only early-bound regions, i.e., those
126/// declared on the impl or used in type parameter bounds).
127///
128/// ```rust,ignore (pseudo-Rust)
129/// impl_to_placeholder_args = {'i => 'i0, U => U0, N => N0 }
130/// ```
131///
132/// Now we can apply `placeholder_args` to the type of the impl method
133/// to yield a new function type in terms of our fresh, placeholder
134/// types:
135///
136/// ```rust,ignore (pseudo-Rust)
137/// <'b> fn(t: &'i0 U0, m: &'b N0) -> Foo
138/// ```
139///
140/// We now want to extract and instantiate the type of the *trait*
141/// method and compare it. To do so, we must create a compound
142/// instantiation by combining `trait_to_impl_args` and
143/// `impl_to_placeholder_args`, and also adding a mapping for the method
144/// type parameters. We extend the mapping to also include
145/// the method parameters.
146///
147/// ```rust,ignore (pseudo-Rust)
148/// trait_to_placeholder_args = { T => &'i0 U0, Self => Foo, M => N0 }
149/// ```
150///
151/// Applying this to the trait method type yields:
152///
153/// ```rust,ignore (pseudo-Rust)
154/// <'a> fn(t: &'i0 U0, m: &'a N0) -> Foo
155/// ```
156///
157/// This type is also the same but the name of the bound region (`'a`
158/// vs `'b`). However, the normal subtyping rules on fn types handle
159/// this kind of equivalency just fine.
160///
161/// We now use these generic parameters to ensure that all declared bounds
162/// are satisfied by the implementation's method.
163///
164/// We do this by creating a parameter environment which contains a
165/// generic parameter corresponding to `impl_to_placeholder_args`. We then build
166/// `trait_to_placeholder_args` and use it to convert the predicates contained
167/// in the `trait_m` generics to the placeholder form.
168///
169/// Finally we register each of these predicates as an obligation and check that
170/// they hold.
171#[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("compare_method_predicate_entailment",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(171u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["impl_m", "trait_m"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_m)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_m)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let impl_m_def_id = impl_m.def_id.expect_local();
            let impl_m_span = tcx.def_span(impl_m_def_id);
            let cause =
                ObligationCause::new(impl_m_span, impl_m_def_id,
                    ObligationCauseCode::CompareImplItem {
                        impl_item_def_id: impl_m_def_id,
                        trait_item_def_id: trait_m.def_id,
                        kind: impl_m.kind,
                    });
            let impl_def_id = impl_m.container_id(tcx);
            let trait_to_impl_args =
                GenericArgs::identity_for_item(tcx,
                        impl_m.def_id).rebase_onto(tcx, impl_m.container_id(tcx),
                    impl_trait_ref.args);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:202",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(202u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["trait_to_impl_args"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&trait_to_impl_args)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
            let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
            let impl_predicates =
                tcx.predicates_of(impl_m_predicates.parent.unwrap());
            let mut hybrid_preds =
                impl_predicates.instantiate_identity(tcx).predicates;
            hybrid_preds.extend(trait_m_predicates.instantiate_own(tcx,
                        trait_to_impl_args).map(|(predicate, _)| predicate));
            let is_conditionally_const =
                tcx.is_conditionally_const(impl_m.def_id);
            if is_conditionally_const {
                hybrid_preds.extend(tcx.const_conditions(impl_def_id).instantiate_identity(tcx).into_iter().chain(tcx.const_conditions(trait_m.def_id).instantiate_own(tcx,
                                trait_to_impl_args)).map(|(trait_ref, _)|
                            {
                                trait_ref.to_host_effect_clause(tcx,
                                    ty::BoundConstness::Maybe)
                            }));
            }
            let normalize_cause =
                traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
            let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
            let param_env =
                if tcx.next_trait_solver_globally() {
                    traits::deeply_normalize_param_env_ignoring_regions(tcx,
                        param_env, normalize_cause)
                } else {
                    traits::normalize_param_env_or_error(tcx, param_env,
                        normalize_cause)
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:259",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(259u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["caller_bounds"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&param_env.caller_bounds())
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let infcx =
                &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
            let ocx = ObligationCtxt::new_with_diagnostics(infcx);
            let impl_m_own_bounds =
                impl_m_predicates.instantiate_own_identity();
            for (predicate, span) in impl_m_own_bounds {
                let normalize_cause =
                    traits::ObligationCause::misc(span, impl_m_def_id);
                let predicate =
                    ocx.normalize(&normalize_cause, param_env, predicate);
                let cause =
                    ObligationCause::new(span, impl_m_def_id,
                        ObligationCauseCode::CompareImplItem {
                            impl_item_def_id: impl_m_def_id,
                            trait_item_def_id: trait_m.def_id,
                            kind: impl_m.kind,
                        });
                ocx.register_obligation(traits::Obligation::new(tcx, cause,
                        param_env, predicate));
            }
            if is_conditionally_const {
                for (const_condition, span) in
                    tcx.const_conditions(impl_m.def_id).instantiate_own_identity()
                    {
                    let normalize_cause =
                        traits::ObligationCause::misc(span, impl_m_def_id);
                    let const_condition =
                        ocx.normalize(&normalize_cause, param_env, const_condition);
                    let cause =
                        ObligationCause::new(span, impl_m_def_id,
                            ObligationCauseCode::CompareImplItem {
                                impl_item_def_id: impl_m_def_id,
                                trait_item_def_id: trait_m.def_id,
                                kind: impl_m.kind,
                            });
                    ocx.register_obligation(traits::Obligation::new(tcx, cause,
                            param_env,
                            const_condition.to_host_effect_clause(tcx,
                                ty::BoundConstness::Maybe)));
                }
            }
            let mut wf_tys = FxIndexSet::default();
            let unnormalized_impl_sig =
                infcx.instantiate_binder_with_fresh_vars(impl_m_span,
                    BoundRegionConversionTime::HigherRankedType,
                    tcx.fn_sig(impl_m.def_id).instantiate_identity());
            let norm_cause =
                ObligationCause::misc(impl_m_span, impl_m_def_id);
            let impl_sig =
                ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:334",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(334u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["impl_sig"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&impl_sig)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let trait_sig =
                tcx.fn_sig(trait_m.def_id).instantiate(tcx,
                    trait_to_impl_args);
            let trait_sig =
                tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
            wf_tys.extend(trait_sig.inputs_and_output.iter());
            let trait_sig = ocx.normalize(&norm_cause, param_env, trait_sig);
            wf_tys.extend(trait_sig.inputs_and_output.iter());
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:347",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(347u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["trait_sig"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&trait_sig)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
            if let Err(terr) = result {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:359",
                                        "rustc_hir_analysis::check::compare_impl_item",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                        ::tracing_core::__macro_support::Option::Some(359u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                        ::tracing_core::field::FieldSet::new(&["message",
                                                        "impl_sig", "trait_sig", "terr"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("sub_types failed")
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&impl_sig)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&trait_sig)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&terr) as
                                                            &dyn Value))])
                            });
                    } else { ; }
                };
                let emitted =
                    report_trait_method_mismatch(infcx, cause, param_env, terr,
                        (trait_m, trait_sig), (impl_m, impl_sig), impl_trait_ref);
                return Err(emitted);
            }
            if !(impl_sig, trait_sig).references_error() {
                for ty in unnormalized_impl_sig.inputs_and_output {
                    ocx.register_obligation(traits::Obligation::new(infcx.tcx,
                            cause.clone(), param_env,
                            ty::ClauseKind::WellFormed(ty.into())));
                }
            }
            let errors = ocx.evaluate_obligations_error_on_ambiguity();
            if !errors.is_empty() {
                let reported =
                    infcx.err_ctxt().report_fulfillment_errors(errors);
                return Err(reported);
            }
            let errors =
                infcx.resolve_regions(impl_m_def_id, param_env, wf_tys);
            if !errors.is_empty() {
                return Err(infcx.tainted_by_errors().unwrap_or_else(||
                                infcx.err_ctxt().report_region_errors(impl_m_def_id,
                                    &errors)));
            }
            Ok(())
        }
    }
}#[instrument(level = "debug", skip(tcx, impl_trait_ref))]
172fn compare_method_predicate_entailment<'tcx>(
173    tcx: TyCtxt<'tcx>,
174    impl_m: ty::AssocItem,
175    trait_m: ty::AssocItem,
176    impl_trait_ref: ty::TraitRef<'tcx>,
177) -> Result<(), ErrorGuaranteed> {
178    // This node-id should be used for the `body_id` field on each
179    // `ObligationCause` (and the `FnCtxt`).
180    //
181    // FIXME(@lcnr): remove that after removing `cause.body_id` from
182    // obligations.
183    let impl_m_def_id = impl_m.def_id.expect_local();
184    let impl_m_span = tcx.def_span(impl_m_def_id);
185    let cause = ObligationCause::new(
186        impl_m_span,
187        impl_m_def_id,
188        ObligationCauseCode::CompareImplItem {
189            impl_item_def_id: impl_m_def_id,
190            trait_item_def_id: trait_m.def_id,
191            kind: impl_m.kind,
192        },
193    );
194
195    // Create mapping from trait method to impl method.
196    let impl_def_id = impl_m.container_id(tcx);
197    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
198        tcx,
199        impl_m.container_id(tcx),
200        impl_trait_ref.args,
201    );
202    debug!(?trait_to_impl_args);
203
204    let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
205    let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
206
207    // This is the only tricky bit of the new way we check implementation methods
208    // We need to build a set of predicates where only the method-level bounds
209    // are from the trait and we assume all other bounds from the implementation
210    // to be previously satisfied.
211    //
212    // We then register the obligations from the impl_m and check to see
213    // if all constraints hold.
214    let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
215    let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
216    hybrid_preds.extend(
217        trait_m_predicates.instantiate_own(tcx, trait_to_impl_args).map(|(predicate, _)| predicate),
218    );
219
220    let is_conditionally_const = tcx.is_conditionally_const(impl_m.def_id);
221    if is_conditionally_const {
222        // Augment the hybrid param-env with the const conditions
223        // of the impl header and the trait method.
224        hybrid_preds.extend(
225            tcx.const_conditions(impl_def_id)
226                .instantiate_identity(tcx)
227                .into_iter()
228                .chain(
229                    tcx.const_conditions(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args),
230                )
231                .map(|(trait_ref, _)| {
232                    trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
233                }),
234        );
235    }
236
237    let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
238    let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
239    // FIXME(-Zhigher-ranked-assumptions): The `hybrid_preds`
240    // should be well-formed. However, using them may result in
241    // region errors as we currently don't track placeholder
242    // assumptions.
243    //
244    // To avoid being backwards incompatible with the old solver,
245    // we also eagerly normalize the where-bounds in the new solver
246    // here while ignoring region constraints. This means we can then
247    // use where-bounds whose normalization results in placeholder
248    // errors further down without getting any errors.
249    //
250    // It should be sound to do so as the only region errors here
251    // should be due to missing implied bounds.
252    //
253    // cc trait-system-refactor-initiative/issues/166.
254    let param_env = if tcx.next_trait_solver_globally() {
255        traits::deeply_normalize_param_env_ignoring_regions(tcx, param_env, normalize_cause)
256    } else {
257        traits::normalize_param_env_or_error(tcx, param_env, normalize_cause)
258    };
259    debug!(caller_bounds=?param_env.caller_bounds());
260
261    let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
262    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
263
264    // Create obligations for each predicate declared by the impl
265    // definition in the context of the hybrid param-env. This makes
266    // sure that the impl's method's where clauses are not more
267    // restrictive than the trait's method (and the impl itself).
268    let impl_m_own_bounds = impl_m_predicates.instantiate_own_identity();
269    for (predicate, span) in impl_m_own_bounds {
270        let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
271        let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
272
273        let cause = ObligationCause::new(
274            span,
275            impl_m_def_id,
276            ObligationCauseCode::CompareImplItem {
277                impl_item_def_id: impl_m_def_id,
278                trait_item_def_id: trait_m.def_id,
279                kind: impl_m.kind,
280            },
281        );
282        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
283    }
284
285    // If we're within a const implementation, we need to make sure that the method
286    // does not assume stronger `[const]` bounds than the trait definition.
287    //
288    // This registers the `[const]` bounds of the impl method, which we will prove
289    // using the hybrid param-env that we earlier augmented with the const conditions
290    // from the impl header and trait method declaration.
291    if is_conditionally_const {
292        for (const_condition, span) in
293            tcx.const_conditions(impl_m.def_id).instantiate_own_identity()
294        {
295            let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
296            let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
297
298            let cause = ObligationCause::new(
299                span,
300                impl_m_def_id,
301                ObligationCauseCode::CompareImplItem {
302                    impl_item_def_id: impl_m_def_id,
303                    trait_item_def_id: trait_m.def_id,
304                    kind: impl_m.kind,
305                },
306            );
307            ocx.register_obligation(traits::Obligation::new(
308                tcx,
309                cause,
310                param_env,
311                const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
312            ));
313        }
314    }
315
316    // We now need to check that the signature of the impl method is
317    // compatible with that of the trait method. We do this by
318    // checking that `impl_fty <: trait_fty`.
319    //
320    // FIXME: We manually instantiate the trait method here as we need
321    // to manually compute its implied bounds. Otherwise this could just
322    // be `ocx.sub(impl_sig, trait_sig)`.
323
324    let mut wf_tys = FxIndexSet::default();
325
326    let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars(
327        impl_m_span,
328        BoundRegionConversionTime::HigherRankedType,
329        tcx.fn_sig(impl_m.def_id).instantiate_identity(),
330    );
331
332    let norm_cause = ObligationCause::misc(impl_m_span, impl_m_def_id);
333    let impl_sig = ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig);
334    debug!(?impl_sig);
335
336    let trait_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args);
337    let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
338
339    // Next, add all inputs and output as well-formed tys. Importantly,
340    // we have to do this before normalization, since the normalized ty may
341    // not contain the input parameters. See issue #87748.
342    wf_tys.extend(trait_sig.inputs_and_output.iter());
343    let trait_sig = ocx.normalize(&norm_cause, param_env, trait_sig);
344    // We also have to add the normalized trait signature
345    // as we don't normalize during implied bounds computation.
346    wf_tys.extend(trait_sig.inputs_and_output.iter());
347    debug!(?trait_sig);
348
349    // FIXME: We'd want to keep more accurate spans than "the method signature" when
350    // processing the comparison between the trait and impl fn, but we sadly lose them
351    // and point at the whole signature when a trait bound or specific input or output
352    // type would be more appropriate. In other places we have a `Vec<Span>`
353    // corresponding to their `Vec<Predicate>`, but we don't have that here.
354    // Fixing this would improve the output of test `issue-83765.rs`.
355    // There's the same issue in compare_eii code.
356    let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
357
358    if let Err(terr) = result {
359        debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
360
361        let emitted = report_trait_method_mismatch(
362            infcx,
363            cause,
364            param_env,
365            terr,
366            (trait_m, trait_sig),
367            (impl_m, impl_sig),
368            impl_trait_ref,
369        );
370        return Err(emitted);
371    }
372
373    if !(impl_sig, trait_sig).references_error() {
374        for ty in unnormalized_impl_sig.inputs_and_output {
375            ocx.register_obligation(traits::Obligation::new(
376                infcx.tcx,
377                cause.clone(),
378                param_env,
379                ty::ClauseKind::WellFormed(ty.into()),
380            ));
381        }
382    }
383
384    // Check that all obligations are satisfied by the implementation's
385    // version.
386    let errors = ocx.evaluate_obligations_error_on_ambiguity();
387    if !errors.is_empty() {
388        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
389        return Err(reported);
390    }
391
392    // Finally, resolve all regions. This catches wily misuses of
393    // lifetime parameters.
394    let errors = infcx.resolve_regions(impl_m_def_id, param_env, wf_tys);
395    if !errors.is_empty() {
396        return Err(infcx
397            .tainted_by_errors()
398            .unwrap_or_else(|| infcx.err_ctxt().report_region_errors(impl_m_def_id, &errors)));
399    }
400
401    Ok(())
402}
403
404struct RemapLateParam<'tcx> {
405    tcx: TyCtxt<'tcx>,
406    mapping: FxIndexMap<ty::LateParamRegionKind, ty::LateParamRegionKind>,
407}
408
409impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateParam<'tcx> {
410    fn cx(&self) -> TyCtxt<'tcx> {
411        self.tcx
412    }
413
414    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
415        if let ty::ReLateParam(fr) = r.kind() {
416            ty::Region::new_late_param(
417                self.tcx,
418                fr.scope,
419                self.mapping.get(&fr.kind).copied().unwrap_or(fr.kind),
420            )
421        } else {
422            r
423        }
424    }
425}
426
427/// Given a method def-id in an impl, compare the method signature of the impl
428/// against the trait that it's implementing. In doing so, infer the hidden types
429/// that this method's signature provides to satisfy each return-position `impl Trait`
430/// in the trait signature.
431///
432/// The method is also responsible for making sure that the hidden types for each
433/// RPITIT actually satisfy the bounds of the `impl Trait`, i.e. that if we infer
434/// `impl Trait = Foo`, that `Foo: Trait` holds.
435///
436/// For example, given the sample code:
437///
438/// ```
439/// use std::ops::Deref;
440///
441/// trait Foo {
442///     fn bar() -> impl Deref<Target = impl Sized>;
443///     //          ^- RPITIT #1        ^- RPITIT #2
444/// }
445///
446/// impl Foo for () {
447///     fn bar() -> Box<String> { Box::new(String::new()) }
448/// }
449/// ```
450///
451/// The hidden types for the RPITITs in `bar` would be inferred to:
452///     * `impl Deref` (RPITIT #1) = `Box<String>`
453///     * `impl Sized` (RPITIT #2) = `String`
454///
455/// The relationship between these two types is straightforward in this case, but
456/// may be more tenuously connected via other `impl`s and normalization rules for
457/// cases of more complicated nested RPITITs.
458x;#[instrument(skip(tcx), level = "debug", ret)]
459pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
460    tcx: TyCtxt<'tcx>,
461    impl_m_def_id: LocalDefId,
462) -> Result<&'tcx DefIdMap<ty::EarlyBinder<'tcx, Ty<'tcx>>>, ErrorGuaranteed> {
463    let impl_m = tcx.associated_item(impl_m_def_id.to_def_id());
464    let trait_m = tcx.associated_item(impl_m.expect_trait_impl()?);
465    let impl_trait_ref =
466        tcx.impl_trait_ref(tcx.parent(impl_m_def_id.to_def_id())).instantiate_identity();
467    // First, check a few of the same things as `compare_impl_method`,
468    // just so we don't ICE during instantiation later.
469    check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?;
470
471    let impl_m_hir_id = tcx.local_def_id_to_hir_id(impl_m_def_id);
472    let return_span = tcx.hir_fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
473    let cause = ObligationCause::new(
474        return_span,
475        impl_m_def_id,
476        ObligationCauseCode::CompareImplItem {
477            impl_item_def_id: impl_m_def_id,
478            trait_item_def_id: trait_m.def_id,
479            kind: impl_m.kind,
480        },
481    );
482
483    // Create mapping from trait to impl (i.e. impl trait header + impl method identity args).
484    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
485        tcx,
486        impl_m.container_id(tcx),
487        impl_trait_ref.args,
488    );
489
490    let hybrid_preds = tcx
491        .predicates_of(impl_m.container_id(tcx))
492        .instantiate_identity(tcx)
493        .into_iter()
494        .chain(tcx.predicates_of(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args))
495        .map(|(clause, _)| clause);
496    let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
497    let param_env = traits::normalize_param_env_or_error(
498        tcx,
499        param_env,
500        ObligationCause::misc(tcx.def_span(impl_m_def_id), impl_m_def_id),
501    );
502
503    let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
504    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
505
506    // Check that the where clauses of the impl are satisfied by the hybrid param env.
507    // You might ask -- what does this have to do with RPITIT inference? Nothing.
508    // We check these because if the where clauses of the signatures do not match
509    // up, then we don't want to give spurious other errors that point at the RPITITs.
510    // They're not necessary to check, though, because we already check them in
511    // `compare_method_predicate_entailment`.
512    let impl_m_own_bounds = tcx.predicates_of(impl_m_def_id).instantiate_own_identity();
513    for (predicate, span) in impl_m_own_bounds {
514        let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
515        let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
516
517        let cause = ObligationCause::new(
518            span,
519            impl_m_def_id,
520            ObligationCauseCode::CompareImplItem {
521                impl_item_def_id: impl_m_def_id,
522                trait_item_def_id: trait_m.def_id,
523                kind: impl_m.kind,
524            },
525        );
526        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
527    }
528
529    // Normalize the impl signature with fresh variables for lifetime inference.
530    let misc_cause = ObligationCause::misc(return_span, impl_m_def_id);
531    let impl_sig = ocx.normalize(
532        &misc_cause,
533        param_env,
534        infcx.instantiate_binder_with_fresh_vars(
535            return_span,
536            BoundRegionConversionTime::HigherRankedType,
537            tcx.fn_sig(impl_m.def_id).instantiate_identity(),
538        ),
539    );
540    impl_sig.error_reported()?;
541    let impl_return_ty = impl_sig.output();
542
543    // Normalize the trait signature with liberated bound vars, passing it through
544    // the ImplTraitInTraitCollector, which gathers all of the RPITITs and replaces
545    // them with inference variables.
546    // We will use these inference variables to collect the hidden types of RPITITs.
547    let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_def_id);
548    let unnormalized_trait_sig = tcx
549        .liberate_late_bound_regions(
550            impl_m.def_id,
551            tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args),
552        )
553        .fold_with(&mut collector);
554
555    let trait_sig = ocx.normalize(&misc_cause, param_env, unnormalized_trait_sig);
556    trait_sig.error_reported()?;
557    let trait_return_ty = trait_sig.output();
558
559    // RPITITs are allowed to use the implied predicates of the method that
560    // defines them. This is because we want code like:
561    // ```
562    // trait Foo {
563    //     fn test<'a, T>(_: &'a T) -> impl Sized;
564    // }
565    // impl Foo for () {
566    //     fn test<'a, T>(x: &'a T) -> &'a T { x }
567    // }
568    // ```
569    // .. to compile. However, since we use both the normalized and unnormalized
570    // inputs and outputs from the instantiated trait signature, we will end up
571    // seeing the hidden type of an RPIT in the signature itself. Naively, this
572    // means that we will use the hidden type to imply the hidden type's own
573    // well-formedness.
574    //
575    // To avoid this, we replace the infer vars used for hidden type inference
576    // with placeholders, which imply nothing about outlives bounds, and then
577    // prove below that the hidden types are well formed.
578    let universe = infcx.create_next_universe();
579    let mut idx = ty::BoundVar::ZERO;
580    let mapping: FxIndexMap<_, _> = collector
581        .types
582        .iter()
583        .map(|(_, &(ty, _))| {
584            assert!(
585                infcx.resolve_vars_if_possible(ty) == ty && ty.is_ty_var(),
586                "{ty:?} should not have been constrained via normalization",
587                ty = infcx.resolve_vars_if_possible(ty)
588            );
589            idx += 1;
590            (
591                ty,
592                Ty::new_placeholder(
593                    tcx,
594                    ty::PlaceholderType::new(
595                        universe,
596                        ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
597                    ),
598                ),
599            )
600        })
601        .collect();
602    let mut type_mapper = BottomUpFolder {
603        tcx,
604        ty_op: |ty| *mapping.get(&ty).unwrap_or(&ty),
605        lt_op: |lt| lt,
606        ct_op: |ct| ct,
607    };
608    let wf_tys = FxIndexSet::from_iter(
609        unnormalized_trait_sig
610            .inputs_and_output
611            .iter()
612            .chain(trait_sig.inputs_and_output.iter())
613            .map(|ty| ty.fold_with(&mut type_mapper)),
614    );
615
616    match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
617        Ok(()) => {}
618        Err(terr) => {
619            let mut diag = struct_span_code_err!(
620                tcx.dcx(),
621                cause.span,
622                E0053,
623                "method `{}` has an incompatible return type for trait",
624                trait_m.name()
625            );
626            infcx.err_ctxt().note_type_err(
627                &mut diag,
628                &cause,
629                tcx.hir_get_if_local(impl_m.def_id)
630                    .and_then(|node| node.fn_decl())
631                    .map(|decl| (decl.output.span(), Cow::from("return type in trait"), false)),
632                Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
633                    expected: trait_return_ty.into(),
634                    found: impl_return_ty.into(),
635                }))),
636                terr,
637                false,
638                None,
639            );
640            return Err(diag.emit());
641        }
642    }
643
644    debug!(?trait_sig, ?impl_sig, "equating function signatures");
645
646    // Unify the whole function signature. We need to do this to fully infer
647    // the lifetimes of the return type, but do this after unifying just the
648    // return types, since we want to avoid duplicating errors from
649    // `compare_method_predicate_entailment`.
650    match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
651        Ok(()) => {}
652        Err(terr) => {
653            // This function gets called during `compare_method_predicate_entailment` when normalizing a
654            // signature that contains RPITIT. When the method signatures don't match, we have to
655            // emit an error now because `compare_method_predicate_entailment` will not report the error
656            // when normalization fails.
657            let emitted = report_trait_method_mismatch(
658                infcx,
659                cause,
660                param_env,
661                terr,
662                (trait_m, trait_sig),
663                (impl_m, impl_sig),
664                impl_trait_ref,
665            );
666            return Err(emitted);
667        }
668    }
669
670    if !unnormalized_trait_sig.output().references_error() && collector.types.is_empty() {
671        tcx.dcx().delayed_bug(
672            "expect >0 RPITITs in call to `collect_return_position_impl_trait_in_trait_tys`",
673        );
674    }
675
676    // FIXME: This has the same issue as #108544, but since this isn't breaking
677    // existing code, I'm not particularly inclined to do the same hack as above
678    // where we process wf obligations manually. This can be fixed in a forward-
679    // compatible way later.
680    let collected_types = collector.types;
681    for (_, &(ty, _)) in &collected_types {
682        ocx.register_obligation(traits::Obligation::new(
683            tcx,
684            misc_cause.clone(),
685            param_env,
686            ty::ClauseKind::WellFormed(ty.into()),
687        ));
688    }
689
690    // Check that all obligations are satisfied by the implementation's
691    // RPITs.
692    let errors = ocx.evaluate_obligations_error_on_ambiguity();
693    if !errors.is_empty() {
694        if let Err(guar) = try_report_async_mismatch(tcx, infcx, &errors, trait_m, impl_m, impl_sig)
695        {
696            return Err(guar);
697        }
698
699        let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
700        return Err(guar);
701    }
702
703    // Finally, resolve all regions. This catches wily misuses of
704    // lifetime parameters.
705    ocx.resolve_regions_and_report_errors(impl_m_def_id, param_env, wf_tys)?;
706
707    let mut remapped_types = DefIdMap::default();
708    for (def_id, (ty, args)) in collected_types {
709        match infcx.fully_resolve(ty) {
710            Ok(ty) => {
711                // `ty` contains free regions that we created earlier while liberating the
712                // trait fn signature. However, projection normalization expects `ty` to
713                // contains `def_id`'s early-bound regions.
714                let id_args = GenericArgs::identity_for_item(tcx, def_id);
715                debug!(?id_args, ?args);
716                let map: FxIndexMap<_, _> = std::iter::zip(args, id_args)
717                    .skip(tcx.generics_of(trait_m.def_id).count())
718                    .filter_map(|(a, b)| Some((a.as_region()?, b.as_region()?)))
719                    .collect();
720                debug!(?map);
721
722                // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound
723                // region args that are synthesized during AST lowering. These are args
724                // that are appended to the parent args (trait and trait method). However,
725                // we're trying to infer the uninstantiated type value of the RPITIT inside
726                // the *impl*, so we can later use the impl's method args to normalize
727                // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`).
728                //
729                // Due to the design of RPITITs, during AST lowering, we have no idea that
730                // an impl method corresponds to a trait method with RPITITs in it. Therefore,
731                // we don't have a list of early-bound region args for the RPITIT in the impl.
732                // Since early region parameters are index-based, we can't just rebase these
733                // (trait method) early-bound region args onto the impl, and there's no
734                // guarantee that the indices from the trait args and impl args line up.
735                // So to fix this, we subtract the number of trait args and add the number of
736                // impl args to *renumber* these early-bound regions to their corresponding
737                // indices in the impl's generic parameters list.
738                //
739                // Also, we only need to account for a difference in trait and impl args,
740                // since we previously enforce that the trait method and impl method have the
741                // same generics.
742                let num_trait_args = impl_trait_ref.args.len();
743                let num_impl_args = tcx.generics_of(impl_m.container_id(tcx)).own_params.len();
744                let ty = match ty.try_fold_with(&mut RemapHiddenTyRegions {
745                    tcx,
746                    map,
747                    num_trait_args,
748                    num_impl_args,
749                    def_id,
750                    impl_m_def_id: impl_m.def_id,
751                    ty,
752                    return_span,
753                }) {
754                    Ok(ty) => ty,
755                    Err(guar) => Ty::new_error(tcx, guar),
756                };
757                remapped_types.insert(def_id, ty::EarlyBinder::bind(ty));
758            }
759            Err(err) => {
760                // This code path is not reached in any tests, but may be
761                // reachable. If this is triggered, it should be converted to
762                // `span_delayed_bug` and the triggering case turned into a
763                // test.
764                tcx.dcx()
765                    .span_bug(return_span, format!("could not fully resolve: {ty} => {err:?}"));
766            }
767        }
768    }
769
770    // We may not collect all RPITITs that we see in the HIR for a trait signature
771    // because an RPITIT was located within a missing item. Like if we have a sig
772    // returning `-> Missing<impl Sized>`, that gets converted to `-> {type error}`,
773    // and when walking through the signature we end up never collecting the def id
774    // of the `impl Sized`. Insert that here, so we don't ICE later.
775    for assoc_item in tcx.associated_types_for_impl_traits_in_associated_fn(trait_m.def_id) {
776        if !remapped_types.contains_key(assoc_item) {
777            remapped_types.insert(
778                *assoc_item,
779                ty::EarlyBinder::bind(Ty::new_error_with_message(
780                    tcx,
781                    return_span,
782                    "missing synthetic item for RPITIT",
783                )),
784            );
785        }
786    }
787
788    Ok(&*tcx.arena.alloc(remapped_types))
789}
790
791struct ImplTraitInTraitCollector<'a, 'tcx, E> {
792    ocx: &'a ObligationCtxt<'a, 'tcx, E>,
793    types: FxIndexMap<DefId, (Ty<'tcx>, ty::GenericArgsRef<'tcx>)>,
794    span: Span,
795    param_env: ty::ParamEnv<'tcx>,
796    body_id: LocalDefId,
797}
798
799impl<'a, 'tcx, E> ImplTraitInTraitCollector<'a, 'tcx, E>
800where
801    E: 'tcx,
802{
803    fn new(
804        ocx: &'a ObligationCtxt<'a, 'tcx, E>,
805        span: Span,
806        param_env: ty::ParamEnv<'tcx>,
807        body_id: LocalDefId,
808    ) -> Self {
809        ImplTraitInTraitCollector { ocx, types: FxIndexMap::default(), span, param_env, body_id }
810    }
811}
812
813impl<'tcx, E> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx, E>
814where
815    E: 'tcx,
816{
817    fn cx(&self) -> TyCtxt<'tcx> {
818        self.ocx.infcx.tcx
819    }
820
821    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
822        if let ty::Alias(ty::Projection, proj) = ty.kind()
823            && self.cx().is_impl_trait_in_trait(proj.def_id)
824        {
825            if let Some((ty, _)) = self.types.get(&proj.def_id) {
826                return *ty;
827            }
828            //FIXME(RPITIT): Deny nested RPITIT in args too
829            if proj.args.has_escaping_bound_vars() {
830                ::rustc_middle::util::bug::bug_fmt(format_args!("FIXME(RPITIT): error here"));bug!("FIXME(RPITIT): error here");
831            }
832            // Replace with infer var
833            let infer_ty = self.ocx.infcx.next_ty_var(self.span);
834            self.types.insert(proj.def_id, (infer_ty, proj.args));
835            // Recurse into bounds
836            for (pred, pred_span) in self
837                .cx()
838                .explicit_item_bounds(proj.def_id)
839                .iter_instantiated_copied(self.cx(), proj.args)
840            {
841                let pred = pred.fold_with(self);
842                let pred = self.ocx.normalize(
843                    &ObligationCause::misc(self.span, self.body_id),
844                    self.param_env,
845                    pred,
846                );
847
848                self.ocx.register_obligation(traits::Obligation::new(
849                    self.cx(),
850                    ObligationCause::new(
851                        self.span,
852                        self.body_id,
853                        ObligationCauseCode::WhereClause(proj.def_id, pred_span),
854                    ),
855                    self.param_env,
856                    pred,
857                ));
858            }
859            infer_ty
860        } else {
861            ty.super_fold_with(self)
862        }
863    }
864}
865
866struct RemapHiddenTyRegions<'tcx> {
867    tcx: TyCtxt<'tcx>,
868    /// Map from early/late params of the impl to identity regions of the RPITIT (GAT)
869    /// in the trait.
870    map: FxIndexMap<ty::Region<'tcx>, ty::Region<'tcx>>,
871    num_trait_args: usize,
872    num_impl_args: usize,
873    /// Def id of the RPITIT (GAT) in the *trait*.
874    def_id: DefId,
875    /// Def id of the impl method which owns the opaque hidden type we're remapping.
876    impl_m_def_id: DefId,
877    /// The hidden type we're remapping. Useful for diagnostics.
878    ty: Ty<'tcx>,
879    /// Span of the return type. Useful for diagnostics.
880    return_span: Span,
881}
882
883impl<'tcx> ty::FallibleTypeFolder<TyCtxt<'tcx>> for RemapHiddenTyRegions<'tcx> {
884    type Error = ErrorGuaranteed;
885
886    fn cx(&self) -> TyCtxt<'tcx> {
887        self.tcx
888    }
889
890    fn try_fold_region(
891        &mut self,
892        region: ty::Region<'tcx>,
893    ) -> Result<ty::Region<'tcx>, Self::Error> {
894        match region.kind() {
895            // Never remap bound regions or `'static`
896            ty::ReBound(..) | ty::ReStatic | ty::ReError(_) => return Ok(region),
897            // We always remap liberated late-bound regions from the function.
898            ty::ReLateParam(_) => {}
899            // Remap early-bound regions as long as they don't come from the `impl` itself,
900            // in which case we don't really need to renumber them.
901            ty::ReEarlyParam(ebr) => {
902                if ebr.index as usize >= self.num_impl_args {
903                    // Remap
904                } else {
905                    return Ok(region);
906                }
907            }
908            ty::ReVar(_) | ty::RePlaceholder(_) | ty::ReErased => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("should not have leaked vars or placeholders into hidden type of RPITIT")));
}unreachable!(
909                "should not have leaked vars or placeholders into hidden type of RPITIT"
910            ),
911        }
912
913        let e = if let Some(id_region) = self.map.get(&region) {
914            if let ty::ReEarlyParam(e) = id_region.kind() {
915                e
916            } else {
917                ::rustc_middle::util::bug::bug_fmt(format_args!("expected to map region {0} to early-bound identity region, but got {1}",
        region, id_region));bug!(
918                    "expected to map region {region} to early-bound identity region, but got {id_region}"
919                );
920            }
921        } else {
922            let guar = match region.opt_param_def_id(self.tcx, self.impl_m_def_id) {
923                Some(def_id) => {
924                    let return_span = if let ty::Alias(ty::Opaque, opaque_ty) = self.ty.kind() {
925                        self.tcx.def_span(opaque_ty.def_id)
926                    } else {
927                        self.return_span
928                    };
929                    self.tcx
930                        .dcx()
931                        .struct_span_err(
932                            return_span,
933                            "return type captures more lifetimes than trait definition",
934                        )
935                        .with_span_label(self.tcx.def_span(def_id), "this lifetime was captured")
936                        .with_span_note(
937                            self.tcx.def_span(self.def_id),
938                            "hidden type must only reference lifetimes captured by this impl trait",
939                        )
940                        .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("hidden type inferred to be `{0}`",
                self.ty))
    })format!("hidden type inferred to be `{}`", self.ty))
941                        .emit()
942                }
943                None => {
944                    // This code path is not reached in any tests, but may be
945                    // reachable. If this is triggered, it should be converted
946                    // to `delayed_bug` and the triggering case turned into a
947                    // test.
948                    self.tcx.dcx().bug("should've been able to remap region");
949                }
950            };
951            return Err(guar);
952        };
953
954        Ok(ty::Region::new_early_param(
955            self.tcx,
956            ty::EarlyParamRegion {
957                name: e.name,
958                index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32,
959            },
960        ))
961    }
962}
963
964/// Gets the string for an explicit self declaration, e.g. "self", "&self",
965/// etc.
966fn get_self_string<'tcx, P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> String
967where
968    P: Fn(Ty<'tcx>) -> bool,
969{
970    if is_self_ty(self_arg_ty) {
971        "self".to_owned()
972    } else if let ty::Ref(_, ty, mutbl) = self_arg_ty.kind()
973        && is_self_ty(*ty)
974    {
975        match mutbl {
976            hir::Mutability::Not => "&self".to_owned(),
977            hir::Mutability::Mut => "&mut self".to_owned(),
978        }
979    } else {
980        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("self: {0}", self_arg_ty))
    })format!("self: {self_arg_ty}")
981    }
982}
983
984fn report_trait_method_mismatch<'tcx>(
985    infcx: &InferCtxt<'tcx>,
986    mut cause: ObligationCause<'tcx>,
987    param_env: ty::ParamEnv<'tcx>,
988    terr: TypeError<'tcx>,
989    (trait_m, trait_sig): (ty::AssocItem, ty::FnSig<'tcx>),
990    (impl_m, impl_sig): (ty::AssocItem, ty::FnSig<'tcx>),
991    impl_trait_ref: ty::TraitRef<'tcx>,
992) -> ErrorGuaranteed {
993    let tcx = infcx.tcx;
994    let (impl_err_span, trait_err_span) =
995        extract_spans_for_error_reporting(infcx, terr, &cause, impl_m, trait_m);
996
997    let mut diag = {
    tcx.dcx().struct_span_err(impl_err_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("method `{0}` has an incompatible type for trait",
                            trait_m.name()))
                })).with_code(E0053)
}struct_span_code_err!(
998        tcx.dcx(),
999        impl_err_span,
1000        E0053,
1001        "method `{}` has an incompatible type for trait",
1002        trait_m.name()
1003    );
1004    match &terr {
1005        TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
1006            if trait_m.is_method() =>
1007        {
1008            let ty = trait_sig.inputs()[0];
1009            let sugg = get_self_string(ty, |ty| ty == impl_trait_ref.self_ty());
1010
1011            // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
1012            // span points only at the type `Box<Self`>, but we want to cover the whole
1013            // argument pattern and type.
1014            let (sig, body) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1015            let span = tcx
1016                .hir_body_param_idents(body)
1017                .zip(sig.decl.inputs.iter())
1018                .map(|(param_ident, ty)| {
1019                    if let Some(param_ident) = param_ident {
1020                        param_ident.span.to(ty.span)
1021                    } else {
1022                        ty.span
1023                    }
1024                })
1025                .next()
1026                .unwrap_or(impl_err_span);
1027
1028            diag.span_suggestion_verbose(
1029                span,
1030                "change the self-receiver type to match the trait",
1031                sugg,
1032                Applicability::MachineApplicable,
1033            );
1034        }
1035        TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
1036            if trait_sig.inputs().len() == *i {
1037                // Suggestion to change output type. We do not suggest in `async` functions
1038                // to avoid complex logic or incorrect output.
1039                if let ImplItemKind::Fn(sig, _) =
1040                    &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).kind
1041                    && !sig.header.asyncness.is_async()
1042                {
1043                    let msg = "change the output type to match the trait";
1044                    let ap = Applicability::MachineApplicable;
1045                    match sig.decl.output {
1046                        hir::FnRetTy::DefaultReturn(sp) => {
1047                            let sugg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" -> {0}", trait_sig.output()))
    })format!(" -> {}", trait_sig.output());
1048                            diag.span_suggestion_verbose(sp, msg, sugg, ap);
1049                        }
1050                        hir::FnRetTy::Return(hir_ty) => {
1051                            let sugg = trait_sig.output();
1052                            diag.span_suggestion_verbose(hir_ty.span, msg, sugg, ap);
1053                        }
1054                    };
1055                };
1056            } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
1057                diag.span_suggestion_verbose(
1058                    impl_err_span,
1059                    "change the parameter type to match the trait",
1060                    trait_ty,
1061                    Applicability::MachineApplicable,
1062                );
1063            }
1064        }
1065        _ => {}
1066    }
1067
1068    cause.span = impl_err_span;
1069    infcx.err_ctxt().note_type_err(
1070        &mut diag,
1071        &cause,
1072        trait_err_span.map(|sp| (sp, Cow::from("type in trait"), false)),
1073        Some(param_env.and(infer::ValuePairs::PolySigs(ExpectedFound {
1074            expected: ty::Binder::dummy(trait_sig),
1075            found: ty::Binder::dummy(impl_sig),
1076        }))),
1077        terr,
1078        false,
1079        None,
1080    );
1081
1082    diag.emit()
1083}
1084
1085fn check_region_bounds_on_impl_item<'tcx>(
1086    tcx: TyCtxt<'tcx>,
1087    impl_m: ty::AssocItem,
1088    trait_m: ty::AssocItem,
1089    delay: bool,
1090) -> Result<(), ErrorGuaranteed> {
1091    let impl_generics = tcx.generics_of(impl_m.def_id);
1092    let impl_params = impl_generics.own_counts().lifetimes;
1093
1094    let trait_generics = tcx.generics_of(trait_m.def_id);
1095    let trait_params = trait_generics.own_counts().lifetimes;
1096
1097    let Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span }) =
1098        check_number_of_early_bound_regions(
1099            tcx,
1100            impl_m.def_id.expect_local(),
1101            trait_m.def_id,
1102            impl_generics,
1103            impl_params,
1104            trait_generics,
1105            trait_params,
1106        )
1107    else {
1108        return Ok(());
1109    };
1110
1111    if !delay && let Some(guar) = check_region_late_boundedness(tcx, impl_m, trait_m) {
1112        return Err(guar);
1113    }
1114
1115    let reported = tcx
1116        .dcx()
1117        .create_err(LifetimesOrBoundsMismatchOnTrait {
1118            span,
1119            item_kind: impl_m.descr(),
1120            ident: impl_m.ident(tcx),
1121            generics_span,
1122            bounds_span,
1123            where_span,
1124        })
1125        .emit_unless_delay(delay);
1126
1127    Err(reported)
1128}
1129
1130pub(super) struct CheckNumberOfEarlyBoundRegionsError {
1131    pub(super) span: Span,
1132    pub(super) generics_span: Span,
1133    pub(super) bounds_span: Vec<Span>,
1134    pub(super) where_span: Option<Span>,
1135}
1136
1137pub(super) fn check_number_of_early_bound_regions<'tcx>(
1138    tcx: TyCtxt<'tcx>,
1139    impl_def_id: LocalDefId,
1140    trait_def_id: DefId,
1141    impl_generics: &Generics,
1142    impl_params: usize,
1143    trait_generics: &Generics,
1144    trait_params: usize,
1145) -> Result<(), CheckNumberOfEarlyBoundRegionsError> {
1146    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:1146",
                        "rustc_hir_analysis::check::compare_impl_item",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                        ::tracing_core::__macro_support::Option::Some(1146u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                        ::tracing_core::field::FieldSet::new(&["trait_generics",
                                        "impl_generics"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&trait_generics)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&impl_generics)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?trait_generics, ?impl_generics);
1147
1148    // Must have same number of early-bound lifetime parameters.
1149    // Unfortunately, if the user screws up the bounds, then this
1150    // will change classification between early and late. E.g.,
1151    // if in trait we have `<'a,'b:'a>`, and in impl we just have
1152    // `<'a,'b>`, then we have 2 early-bound lifetime parameters
1153    // in trait but 0 in the impl. But if we report "expected 2
1154    // but found 0" it's confusing, because it looks like there
1155    // are zero. Since I don't quite know how to phrase things at
1156    // the moment, give a kind of vague error message.
1157    if trait_params == impl_params {
1158        return Ok(());
1159    }
1160
1161    let span = tcx
1162        .hir_get_generics(impl_def_id)
1163        .expect("expected impl item to have generics or else we can't compare them")
1164        .span;
1165
1166    let mut generics_span = tcx.def_span(trait_def_id);
1167    let mut bounds_span = ::alloc::vec::Vec::new()vec![];
1168    let mut where_span = None;
1169
1170    if let Some(trait_node) = tcx.hir_get_if_local(trait_def_id)
1171        && let Some(trait_generics) = trait_node.generics()
1172    {
1173        generics_span = trait_generics.span;
1174        // FIXME: we could potentially look at the impl's bounds to not point at bounds that
1175        // *are* present in the impl.
1176        for p in trait_generics.predicates {
1177            match p.kind {
1178                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1179                    bounds,
1180                    ..
1181                })
1182                | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1183                    bounds,
1184                    ..
1185                }) => {
1186                    for b in *bounds {
1187                        if let hir::GenericBound::Outlives(lt) = b {
1188                            bounds_span.push(lt.ident.span);
1189                        }
1190                    }
1191                }
1192                _ => {}
1193            }
1194        }
1195        if let Some(impl_node) = tcx.hir_get_if_local(impl_def_id.into())
1196            && let Some(impl_generics) = impl_node.generics()
1197        {
1198            let mut impl_bounds = 0;
1199            for p in impl_generics.predicates {
1200                match p.kind {
1201                    hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1202                        bounds,
1203                        ..
1204                    })
1205                    | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1206                        bounds,
1207                        ..
1208                    }) => {
1209                        for b in *bounds {
1210                            if let hir::GenericBound::Outlives(_) = b {
1211                                impl_bounds += 1;
1212                            }
1213                        }
1214                    }
1215                    _ => {}
1216                }
1217            }
1218            if impl_bounds == bounds_span.len() {
1219                bounds_span = ::alloc::vec::Vec::new()vec![];
1220            } else if impl_generics.has_where_clause_predicates {
1221                where_span = Some(impl_generics.where_clause_span);
1222            }
1223        }
1224    }
1225
1226    Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span })
1227}
1228
1229#[allow(unused)]
1230enum LateEarlyMismatch<'tcx> {
1231    EarlyInImpl(DefId, DefId, ty::Region<'tcx>),
1232    LateInImpl(DefId, DefId, ty::Region<'tcx>),
1233}
1234
1235fn check_region_late_boundedness<'tcx>(
1236    tcx: TyCtxt<'tcx>,
1237    impl_m: ty::AssocItem,
1238    trait_m: ty::AssocItem,
1239) -> Option<ErrorGuaranteed> {
1240    if !impl_m.is_fn() {
1241        return None;
1242    }
1243
1244    let (infcx, param_env) = tcx
1245        .infer_ctxt()
1246        .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, impl_m.def_id));
1247
1248    let impl_m_args = infcx.fresh_args_for_item(DUMMY_SP, impl_m.def_id);
1249    let impl_m_sig = tcx.fn_sig(impl_m.def_id).instantiate(tcx, impl_m_args);
1250    let impl_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, impl_m_sig);
1251
1252    let trait_m_args = infcx.fresh_args_for_item(DUMMY_SP, trait_m.def_id);
1253    let trait_m_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_args);
1254    let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_m_sig);
1255
1256    let ocx = ObligationCtxt::new(&infcx);
1257
1258    // Equate the signatures so that we can infer whether a late-bound param was present where
1259    // an early-bound param was expected, since we replace the late-bound lifetimes with
1260    // `ReLateParam`, and early-bound lifetimes with infer vars, so the early-bound args will
1261    // resolve to `ReLateParam` if there is a mismatch.
1262    let Ok(()) = ocx.eq(
1263        &ObligationCause::dummy(),
1264        param_env,
1265        ty::Binder::dummy(trait_m_sig),
1266        ty::Binder::dummy(impl_m_sig),
1267    ) else {
1268        return None;
1269    };
1270
1271    let errors = ocx.try_evaluate_obligations();
1272    if !errors.is_empty() {
1273        return None;
1274    }
1275
1276    let mut mismatched = ::alloc::vec::Vec::new()vec![];
1277
1278    let impl_generics = tcx.generics_of(impl_m.def_id);
1279    for (id_arg, arg) in
1280        std::iter::zip(ty::GenericArgs::identity_for_item(tcx, impl_m.def_id), impl_m_args)
1281    {
1282        if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1283            && let ty::ReVar(vid) = r.kind()
1284            && let r = infcx
1285                .inner
1286                .borrow_mut()
1287                .unwrap_region_constraints()
1288                .opportunistic_resolve_var(tcx, vid)
1289            && let ty::ReLateParam(ty::LateParamRegion {
1290                kind: ty::LateParamRegionKind::Named(trait_param_def_id),
1291                ..
1292            }) = r.kind()
1293            && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1294        {
1295            mismatched.push(LateEarlyMismatch::EarlyInImpl(
1296                impl_generics.region_param(ebr, tcx).def_id,
1297                trait_param_def_id,
1298                id_arg.expect_region(),
1299            ));
1300        }
1301    }
1302
1303    let trait_generics = tcx.generics_of(trait_m.def_id);
1304    for (id_arg, arg) in
1305        std::iter::zip(ty::GenericArgs::identity_for_item(tcx, trait_m.def_id), trait_m_args)
1306    {
1307        if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1308            && let ty::ReVar(vid) = r.kind()
1309            && let r = infcx
1310                .inner
1311                .borrow_mut()
1312                .unwrap_region_constraints()
1313                .opportunistic_resolve_var(tcx, vid)
1314            && let ty::ReLateParam(ty::LateParamRegion {
1315                kind: ty::LateParamRegionKind::Named(impl_param_def_id),
1316                ..
1317            }) = r.kind()
1318            && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1319        {
1320            mismatched.push(LateEarlyMismatch::LateInImpl(
1321                impl_param_def_id,
1322                trait_generics.region_param(ebr, tcx).def_id,
1323                id_arg.expect_region(),
1324            ));
1325        }
1326    }
1327
1328    if mismatched.is_empty() {
1329        return None;
1330    }
1331
1332    let spans: Vec<_> = mismatched
1333        .iter()
1334        .map(|param| {
1335            let (LateEarlyMismatch::EarlyInImpl(impl_param_def_id, ..)
1336            | LateEarlyMismatch::LateInImpl(impl_param_def_id, ..)) = param;
1337            tcx.def_span(impl_param_def_id)
1338        })
1339        .collect();
1340
1341    let mut diag = tcx
1342        .dcx()
1343        .struct_span_err(spans, "lifetime parameters do not match the trait definition")
1344        .with_note("lifetime parameters differ in whether they are early- or late-bound")
1345        .with_code(E0195);
1346    for mismatch in mismatched {
1347        match mismatch {
1348            LateEarlyMismatch::EarlyInImpl(
1349                impl_param_def_id,
1350                trait_param_def_id,
1351                early_bound_region,
1352            ) => {
1353                let mut multispan = MultiSpan::from_spans(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [tcx.def_span(impl_param_def_id), tcx.def_span(trait_param_def_id)]))vec![
1354                    tcx.def_span(impl_param_def_id),
1355                    tcx.def_span(trait_param_def_id),
1356                ]);
1357                multispan
1358                    .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1359                multispan
1360                    .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1361                multispan.push_span_label(
1362                    tcx.def_span(impl_param_def_id),
1363                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is early-bound",
                tcx.item_name(impl_param_def_id)))
    })format!("`{}` is early-bound", tcx.item_name(impl_param_def_id)),
1364                );
1365                multispan.push_span_label(
1366                    tcx.def_span(trait_param_def_id),
1367                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is late-bound",
                tcx.item_name(trait_param_def_id)))
    })format!("`{}` is late-bound", tcx.item_name(trait_param_def_id)),
1368                );
1369                if let Some(span) =
1370                    find_region_in_predicates(tcx, impl_m.def_id, early_bound_region)
1371                {
1372                    multispan.push_span_label(
1373                        span,
1374                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
                tcx.item_name(impl_param_def_id)))
    })format!(
1375                            "this lifetime bound makes `{}` early-bound",
1376                            tcx.item_name(impl_param_def_id)
1377                        ),
1378                    );
1379                }
1380                diag.span_note(
1381                    multispan,
1382                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
                tcx.item_name(impl_param_def_id)))
    })format!(
1383                        "`{}` differs between the trait and impl",
1384                        tcx.item_name(impl_param_def_id)
1385                    ),
1386                );
1387            }
1388            LateEarlyMismatch::LateInImpl(
1389                impl_param_def_id,
1390                trait_param_def_id,
1391                early_bound_region,
1392            ) => {
1393                let mut multispan = MultiSpan::from_spans(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [tcx.def_span(impl_param_def_id), tcx.def_span(trait_param_def_id)]))vec![
1394                    tcx.def_span(impl_param_def_id),
1395                    tcx.def_span(trait_param_def_id),
1396                ]);
1397                multispan
1398                    .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1399                multispan
1400                    .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1401                multispan.push_span_label(
1402                    tcx.def_span(impl_param_def_id),
1403                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is late-bound",
                tcx.item_name(impl_param_def_id)))
    })format!("`{}` is late-bound", tcx.item_name(impl_param_def_id)),
1404                );
1405                multispan.push_span_label(
1406                    tcx.def_span(trait_param_def_id),
1407                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is early-bound",
                tcx.item_name(trait_param_def_id)))
    })format!("`{}` is early-bound", tcx.item_name(trait_param_def_id)),
1408                );
1409                if let Some(span) =
1410                    find_region_in_predicates(tcx, trait_m.def_id, early_bound_region)
1411                {
1412                    multispan.push_span_label(
1413                        span,
1414                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
                tcx.item_name(trait_param_def_id)))
    })format!(
1415                            "this lifetime bound makes `{}` early-bound",
1416                            tcx.item_name(trait_param_def_id)
1417                        ),
1418                    );
1419                }
1420                diag.span_note(
1421                    multispan,
1422                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
                tcx.item_name(impl_param_def_id)))
    })format!(
1423                        "`{}` differs between the trait and impl",
1424                        tcx.item_name(impl_param_def_id)
1425                    ),
1426                );
1427            }
1428        }
1429    }
1430
1431    Some(diag.emit())
1432}
1433
1434fn find_region_in_predicates<'tcx>(
1435    tcx: TyCtxt<'tcx>,
1436    def_id: DefId,
1437    early_bound_region: ty::Region<'tcx>,
1438) -> Option<Span> {
1439    for (pred, span) in tcx.explicit_predicates_of(def_id).instantiate_identity(tcx) {
1440        if pred.visit_with(&mut FindRegion(early_bound_region)).is_break() {
1441            return Some(span);
1442        }
1443    }
1444
1445    struct FindRegion<'tcx>(ty::Region<'tcx>);
1446    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindRegion<'tcx> {
1447        type Result = ControlFlow<()>;
1448        fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
1449            if r == self.0 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
1450        }
1451    }
1452
1453    None
1454}
1455
1456#[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("extract_spans_for_error_reporting",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1456u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["terr", "cause",
                                                    "impl_m", "trait_m"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&terr)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_m)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_m)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: (Span, Option<Span>) = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = infcx.tcx;
            let mut impl_args =
                {
                    let (sig, _) =
                        tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
                    sig.decl.inputs.iter().map(|t|
                                t.span).chain(iter::once(sig.decl.output.span()))
                };
            let trait_args =
                trait_m.def_id.as_local().map(|def_id|
                        {
                            let (sig, _) =
                                tcx.hir_expect_trait_item(def_id).expect_fn();
                            sig.decl.inputs.iter().map(|t|
                                        t.span).chain(iter::once(sig.decl.output.span()))
                        });
            match terr {
                TypeError::ArgumentMutability(i) |
                    TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
                    (impl_args.nth(i).unwrap(),
                        trait_args.and_then(|mut args| args.nth(i)))
                }
                _ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
            }
        }
    }
}#[instrument(level = "debug", skip(infcx))]
1457fn extract_spans_for_error_reporting<'tcx>(
1458    infcx: &infer::InferCtxt<'tcx>,
1459    terr: TypeError<'_>,
1460    cause: &ObligationCause<'tcx>,
1461    impl_m: ty::AssocItem,
1462    trait_m: ty::AssocItem,
1463) -> (Span, Option<Span>) {
1464    let tcx = infcx.tcx;
1465    let mut impl_args = {
1466        let (sig, _) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1467        sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1468    };
1469
1470    let trait_args = trait_m.def_id.as_local().map(|def_id| {
1471        let (sig, _) = tcx.hir_expect_trait_item(def_id).expect_fn();
1472        sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1473    });
1474
1475    match terr {
1476        TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1477            (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1478        }
1479        _ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
1480    }
1481}
1482
1483fn compare_self_type<'tcx>(
1484    tcx: TyCtxt<'tcx>,
1485    impl_m: ty::AssocItem,
1486    trait_m: ty::AssocItem,
1487    impl_trait_ref: ty::TraitRef<'tcx>,
1488    delay: bool,
1489) -> Result<(), ErrorGuaranteed> {
1490    // Try to give more informative error messages about self typing
1491    // mismatches. Note that any mismatch will also be detected
1492    // below, where we construct a canonical function type that
1493    // includes the self parameter as a normal parameter. It's just
1494    // that the error messages you get out of this code are a bit more
1495    // inscrutable, particularly for cases where one method has no
1496    // self.
1497
1498    let self_string = |method: ty::AssocItem| {
1499        let untransformed_self_ty = match method.container {
1500            ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1501                impl_trait_ref.self_ty()
1502            }
1503            ty::AssocContainer::Trait => tcx.types.self_param,
1504        };
1505        let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().input(0);
1506        let (infcx, param_env) = tcx
1507            .infer_ctxt()
1508            .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, method.def_id));
1509        let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1510        let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
1511        get_self_string(self_arg_ty, can_eq_self)
1512    };
1513
1514    match (trait_m.is_method(), impl_m.is_method()) {
1515        (false, false) | (true, true) => {}
1516
1517        (false, true) => {
1518            let self_descr = self_string(impl_m);
1519            let impl_m_span = tcx.def_span(impl_m.def_id);
1520            let mut err = {
    tcx.dcx().struct_span_err(impl_m_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("method `{0}` has a `{1}` declaration in the impl, but not in the trait",
                            trait_m.name(), self_descr))
                })).with_code(E0185)
}struct_span_code_err!(
1521                tcx.dcx(),
1522                impl_m_span,
1523                E0185,
1524                "method `{}` has a `{}` declaration in the impl, but not in the trait",
1525                trait_m.name(),
1526                self_descr
1527            );
1528            err.span_label(impl_m_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` used in impl", self_descr))
    })format!("`{self_descr}` used in impl"));
1529            if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1530                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("trait method declared without `{0}`",
                self_descr))
    })format!("trait method declared without `{self_descr}`"));
1531            } else {
1532                err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1533            }
1534            return Err(err.emit_unless_delay(delay));
1535        }
1536
1537        (true, false) => {
1538            let self_descr = self_string(trait_m);
1539            let impl_m_span = tcx.def_span(impl_m.def_id);
1540            let mut err = {
    tcx.dcx().struct_span_err(impl_m_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("method `{0}` has a `{1}` declaration in the trait, but not in the impl",
                            trait_m.name(), self_descr))
                })).with_code(E0186)
}struct_span_code_err!(
1541                tcx.dcx(),
1542                impl_m_span,
1543                E0186,
1544                "method `{}` has a `{}` declaration in the trait, but not in the impl",
1545                trait_m.name(),
1546                self_descr
1547            );
1548            err.span_label(impl_m_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}` in impl",
                self_descr))
    })format!("expected `{self_descr}` in impl"));
1549            if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1550                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` used in trait", self_descr))
    })format!("`{self_descr}` used in trait"));
1551            } else {
1552                err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1553            }
1554
1555            return Err(err.emit_unless_delay(delay));
1556        }
1557    }
1558
1559    Ok(())
1560}
1561
1562/// Checks that the number of generics on a given assoc item in a trait impl is the same
1563/// as the number of generics on the respective assoc item in the trait definition.
1564///
1565/// For example this code emits the errors in the following code:
1566/// ```rust,compile_fail
1567/// trait Trait {
1568///     fn foo();
1569///     type Assoc<T>;
1570/// }
1571///
1572/// impl Trait for () {
1573///     fn foo<T>() {}
1574///     //~^ error
1575///     type Assoc = u32;
1576///     //~^ error
1577/// }
1578/// ```
1579///
1580/// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
1581/// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
1582/// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
1583fn compare_number_of_generics<'tcx>(
1584    tcx: TyCtxt<'tcx>,
1585    impl_: ty::AssocItem,
1586    trait_: ty::AssocItem,
1587    delay: bool,
1588) -> Result<(), ErrorGuaranteed> {
1589    let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1590    let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1591
1592    // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
1593    // in `compare_generic_param_kinds` which will give a nicer error message than something like:
1594    // "expected 1 type parameter, found 0 type parameters"
1595    if (trait_own_counts.types + trait_own_counts.consts)
1596        == (impl_own_counts.types + impl_own_counts.consts)
1597    {
1598        return Ok(());
1599    }
1600
1601    // We never need to emit a separate error for RPITITs, since if an RPITIT
1602    // has mismatched type or const generic arguments, then the method that it's
1603    // inheriting the generics from will also have mismatched arguments, and
1604    // we'll report an error for that instead. Delay a bug for safety, though.
1605    if trait_.is_impl_trait_in_trait() {
1606        // FIXME: no tests trigger this. If you find example code that does
1607        // trigger this, please add it to the test suite.
1608        tcx.dcx()
1609            .bug("errors comparing numbers of generics of trait/impl functions were not emitted");
1610    }
1611
1612    let matchings = [
1613        ("type", trait_own_counts.types, impl_own_counts.types),
1614        ("const", trait_own_counts.consts, impl_own_counts.consts),
1615    ];
1616
1617    let item_kind = impl_.descr();
1618
1619    let mut err_occurred = None;
1620    for (kind, trait_count, impl_count) in matchings {
1621        if impl_count != trait_count {
1622            let arg_spans = |item: &ty::AssocItem, generics: &hir::Generics<'_>| {
1623                let mut spans = generics
1624                    .params
1625                    .iter()
1626                    .filter(|p| match p.kind {
1627                        hir::GenericParamKind::Lifetime {
1628                            kind: hir::LifetimeParamKind::Elided(_),
1629                        } => {
1630                            // A fn can have an arbitrary number of extra elided lifetimes for the
1631                            // same signature.
1632                            !item.is_fn()
1633                        }
1634                        _ => true,
1635                    })
1636                    .map(|p| p.span)
1637                    .collect::<Vec<Span>>();
1638                if spans.is_empty() {
1639                    spans = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [generics.span]))vec![generics.span]
1640                }
1641                spans
1642            };
1643            let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1644                let trait_item = tcx.hir_expect_trait_item(def_id);
1645                let arg_spans: Vec<Span> = arg_spans(&trait_, trait_item.generics);
1646                let impl_trait_spans: Vec<Span> = trait_item
1647                    .generics
1648                    .params
1649                    .iter()
1650                    .filter_map(|p| match p.kind {
1651                        GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1652                        _ => None,
1653                    })
1654                    .collect();
1655                (Some(arg_spans), impl_trait_spans)
1656            } else {
1657                let trait_span = tcx.hir_span_if_local(trait_.def_id);
1658                (trait_span.map(|s| ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [s]))vec![s]), ::alloc::vec::Vec::new()vec![])
1659            };
1660
1661            let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
1662            let impl_item_impl_trait_spans: Vec<Span> = impl_item
1663                .generics
1664                .params
1665                .iter()
1666                .filter_map(|p| match p.kind {
1667                    GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1668                    _ => None,
1669                })
1670                .collect();
1671            let spans = arg_spans(&impl_, impl_item.generics);
1672            let span = spans.first().copied();
1673
1674            let mut err = tcx.dcx().struct_span_err(
1675                spans,
1676                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}` has {2} {6} parameter{3} but its trait declaration has {4} {6} parameter{5}",
                item_kind, trait_.name(), impl_count,
                if impl_count == 1 { "" } else { "s" }, trait_count,
                if trait_count == 1 { "" } else { "s" }, kind))
    })format!(
1677                    "{} `{}` has {} {kind} parameter{} but its trait \
1678                     declaration has {} {kind} parameter{}",
1679                    item_kind,
1680                    trait_.name(),
1681                    impl_count,
1682                    pluralize!(impl_count),
1683                    trait_count,
1684                    pluralize!(trait_count),
1685                    kind = kind,
1686                ),
1687            );
1688            err.code(E0049);
1689
1690            let msg =
1691                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {1} {2} parameter{0}",
                if trait_count == 1 { "" } else { "s" }, trait_count, kind))
    })format!("expected {trait_count} {kind} parameter{}", pluralize!(trait_count),);
1692            if let Some(spans) = trait_spans {
1693                let mut spans = spans.iter();
1694                if let Some(span) = spans.next() {
1695                    err.span_label(*span, msg);
1696                }
1697                for span in spans {
1698                    err.span_label(*span, "");
1699                }
1700            } else {
1701                err.span_label(tcx.def_span(trait_.def_id), msg);
1702            }
1703
1704            if let Some(span) = span {
1705                err.span_label(
1706                    span,
1707                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("found {0} {1} parameter{2}",
                impl_count, kind, if impl_count == 1 { "" } else { "s" }))
    })format!("found {} {} parameter{}", impl_count, kind, pluralize!(impl_count),),
1708                );
1709            }
1710
1711            for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1712                err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1713            }
1714
1715            let reported = err.emit_unless_delay(delay);
1716            err_occurred = Some(reported);
1717        }
1718    }
1719
1720    if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1721}
1722
1723fn compare_number_of_method_arguments<'tcx>(
1724    tcx: TyCtxt<'tcx>,
1725    impl_m: ty::AssocItem,
1726    trait_m: ty::AssocItem,
1727    delay: bool,
1728) -> Result<(), ErrorGuaranteed> {
1729    let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1730    let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1731    let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
1732    let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1733
1734    if trait_number_args != impl_number_args {
1735        let trait_span = trait_m
1736            .def_id
1737            .as_local()
1738            .and_then(|def_id| {
1739                let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
1740                let pos = trait_number_args.saturating_sub(1);
1741                trait_m_sig.decl.inputs.get(pos).map(|arg| {
1742                    if pos == 0 {
1743                        arg.span
1744                    } else {
1745                        arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1746                    }
1747                })
1748            })
1749            .or_else(|| tcx.hir_span_if_local(trait_m.def_id));
1750
1751        let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1752        let pos = impl_number_args.saturating_sub(1);
1753        let impl_span = impl_m_sig
1754            .decl
1755            .inputs
1756            .get(pos)
1757            .map(|arg| {
1758                if pos == 0 {
1759                    arg.span
1760                } else {
1761                    arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1762                }
1763            })
1764            .unwrap_or_else(|| tcx.def_span(impl_m.def_id));
1765
1766        let mut err = {
    tcx.dcx().struct_span_err(impl_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("method `{0}` has {1} but the declaration in trait `{2}` has {3}",
                            trait_m.name(),
                            potentially_plural_count(impl_number_args, "parameter"),
                            tcx.def_path_str(trait_m.def_id), trait_number_args))
                })).with_code(E0050)
}struct_span_code_err!(
1767            tcx.dcx(),
1768            impl_span,
1769            E0050,
1770            "method `{}` has {} but the declaration in trait `{}` has {}",
1771            trait_m.name(),
1772            potentially_plural_count(impl_number_args, "parameter"),
1773            tcx.def_path_str(trait_m.def_id),
1774            trait_number_args
1775        );
1776
1777        if let Some(trait_span) = trait_span {
1778            err.span_label(
1779                trait_span,
1780                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("trait requires {0}",
                potentially_plural_count(trait_number_args, "parameter")))
    })format!(
1781                    "trait requires {}",
1782                    potentially_plural_count(trait_number_args, "parameter")
1783                ),
1784            );
1785        } else {
1786            err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1787        }
1788
1789        err.span_label(
1790            impl_span,
1791            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found {1}",
                potentially_plural_count(trait_number_args, "parameter"),
                impl_number_args))
    })format!(
1792                "expected {}, found {}",
1793                potentially_plural_count(trait_number_args, "parameter"),
1794                impl_number_args
1795            ),
1796        );
1797
1798        return Err(err.emit_unless_delay(delay));
1799    }
1800
1801    Ok(())
1802}
1803
1804fn compare_synthetic_generics<'tcx>(
1805    tcx: TyCtxt<'tcx>,
1806    impl_m: ty::AssocItem,
1807    trait_m: ty::AssocItem,
1808    delay: bool,
1809) -> Result<(), ErrorGuaranteed> {
1810    // FIXME(chrisvittal) Clean up this function, list of FIXME items:
1811    //     1. Better messages for the span labels
1812    //     2. Explanation as to what is going on
1813    // If we get here, we already have the same number of generics, so the zip will
1814    // be okay.
1815    let mut error_found = None;
1816    let impl_m_generics = tcx.generics_of(impl_m.def_id);
1817    let trait_m_generics = tcx.generics_of(trait_m.def_id);
1818    let impl_m_type_params =
1819        impl_m_generics.own_params.iter().filter_map(|param| match param.kind {
1820            GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1821            GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1822        });
1823    let trait_m_type_params =
1824        trait_m_generics.own_params.iter().filter_map(|param| match param.kind {
1825            GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1826            GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1827        });
1828    for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1829        iter::zip(impl_m_type_params, trait_m_type_params)
1830    {
1831        if impl_synthetic != trait_synthetic {
1832            let impl_def_id = impl_def_id.expect_local();
1833            let impl_span = tcx.def_span(impl_def_id);
1834            let trait_span = tcx.def_span(trait_def_id);
1835            let mut err = {
    tcx.dcx().struct_span_err(impl_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("method `{0}` has incompatible signature for trait",
                            trait_m.name()))
                })).with_code(E0643)
}struct_span_code_err!(
1836                tcx.dcx(),
1837                impl_span,
1838                E0643,
1839                "method `{}` has incompatible signature for trait",
1840                trait_m.name()
1841            );
1842            err.span_label(trait_span, "declaration in trait here");
1843            if impl_synthetic {
1844                // The case where the impl method uses `impl Trait` but the trait method uses
1845                // explicit generics
1846                err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1847                try {
1848                    // try taking the name from the trait impl
1849                    // FIXME: this is obviously suboptimal since the name can already be used
1850                    // as another generic argument
1851                    let new_name = tcx.opt_item_name(trait_def_id)?;
1852                    let trait_m = trait_m.def_id.as_local()?;
1853                    let trait_m = tcx.hir_expect_trait_item(trait_m);
1854
1855                    let impl_m = impl_m.def_id.as_local()?;
1856                    let impl_m = tcx.hir_expect_impl_item(impl_m);
1857
1858                    // in case there are no generics, take the spot between the function name
1859                    // and the opening paren of the argument list
1860                    let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1861                    // in case there are generics, just replace them
1862                    let generics_span = impl_m.generics.span.substitute_dummy(new_generics_span);
1863                    // replace with the generics from the trait
1864                    let new_generics =
1865                        tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1866
1867                    err.multipart_suggestion(
1868                        "try changing the `impl Trait` argument to a generic parameter",
1869                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(impl_span, new_name.to_string()), (generics_span, new_generics)]))vec![
1870                            // replace `impl Trait` with `T`
1871                            (impl_span, new_name.to_string()),
1872                            // replace impl method generics with trait method generics
1873                            // This isn't quite right, as users might have changed the names
1874                            // of the generics, but it works for the common case
1875                            (generics_span, new_generics),
1876                        ],
1877                        Applicability::MaybeIncorrect,
1878                    );
1879                };
1880            } else {
1881                // The case where the trait method uses `impl Trait`, but the impl method uses
1882                // explicit generics.
1883                err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1884                try {
1885                    let impl_m = impl_m.def_id.as_local()?;
1886                    let impl_m = tcx.hir_expect_impl_item(impl_m);
1887                    let (sig, _) = impl_m.expect_fn();
1888                    let input_tys = sig.decl.inputs;
1889
1890                    struct Visitor(hir::def_id::LocalDefId);
1891                    impl<'v> intravisit::Visitor<'v> for Visitor {
1892                        type Result = ControlFlow<Span>;
1893                        fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) -> Self::Result {
1894                            if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
1895                                && let Res::Def(DefKind::TyParam, def_id) = path.res
1896                                && def_id == self.0.to_def_id()
1897                            {
1898                                ControlFlow::Break(ty.span)
1899                            } else {
1900                                intravisit::walk_ty(self, ty)
1901                            }
1902                        }
1903                    }
1904
1905                    let span = input_tys
1906                        .iter()
1907                        .find_map(|ty| Visitor(impl_def_id).visit_ty_unambig(ty).break_value())?;
1908
1909                    let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
1910                    let bounds = bounds.first()?.span().to(bounds.last()?.span());
1911                    let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
1912
1913                    err.multipart_suggestion(
1914                        "try removing the generic parameter and using `impl Trait` instead",
1915                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(impl_m.generics.span, String::new()),
                (span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("impl {0}", bounds))
                        }))]))vec![
1916                            // delete generic parameters
1917                            (impl_m.generics.span, String::new()),
1918                            // replace param usage with `impl Trait`
1919                            (span, format!("impl {bounds}")),
1920                        ],
1921                        Applicability::MaybeIncorrect,
1922                    );
1923                };
1924            }
1925            error_found = Some(err.emit_unless_delay(delay));
1926        }
1927    }
1928    if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
1929}
1930
1931/// Checks that all parameters in the generics of a given assoc item in a trait impl have
1932/// the same kind as the respective generic parameter in the trait def.
1933///
1934/// For example all 4 errors in the following code are emitted here:
1935/// ```rust,ignore (pseudo-Rust)
1936/// trait Foo {
1937///     fn foo<const N: u8>();
1938///     type Bar<const N: u8>;
1939///     fn baz<const N: u32>();
1940///     type Blah<T>;
1941/// }
1942///
1943/// impl Foo for () {
1944///     fn foo<const N: u64>() {}
1945///     //~^ error
1946///     type Bar<const N: u64> = ();
1947///     //~^ error
1948///     fn baz<T>() {}
1949///     //~^ error
1950///     type Blah<const N: i64> = u32;
1951///     //~^ error
1952/// }
1953/// ```
1954///
1955/// This function does not handle lifetime parameters
1956fn compare_generic_param_kinds<'tcx>(
1957    tcx: TyCtxt<'tcx>,
1958    impl_item: ty::AssocItem,
1959    trait_item: ty::AssocItem,
1960    delay: bool,
1961) -> Result<(), ErrorGuaranteed> {
1962    match (&impl_item.tag(), &trait_item.tag()) {
    (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!(impl_item.tag(), trait_item.tag());
1963
1964    let ty_const_params_of = |def_id| {
1965        tcx.generics_of(def_id).own_params.iter().filter(|param| {
1966            #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. } =>
        true,
    _ => false,
}matches!(
1967                param.kind,
1968                GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1969            )
1970        })
1971    };
1972
1973    for (param_impl, param_trait) in
1974        iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1975    {
1976        use GenericParamDefKind::*;
1977        if match (&param_impl.kind, &param_trait.kind) {
1978            (Const { .. }, Const { .. })
1979                if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1980            {
1981                true
1982            }
1983            (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1984            // this is exhaustive so that anyone adding new generic param kinds knows
1985            // to make sure this error is reported for them.
1986            (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1987            (Lifetime { .. }, _) | (_, Lifetime { .. }) => {
1988                ::rustc_middle::util::bug::bug_fmt(format_args!("lifetime params are expected to be filtered by `ty_const_params_of`"))bug!("lifetime params are expected to be filtered by `ty_const_params_of`")
1989            }
1990        } {
1991            let param_impl_span = tcx.def_span(param_impl.def_id);
1992            let param_trait_span = tcx.def_span(param_trait.def_id);
1993
1994            let mut err = {
    tcx.dcx().struct_span_err(param_impl_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} `{1}` has an incompatible generic parameter for trait `{2}`",
                            impl_item.descr(), trait_item.name(),
                            &tcx.def_path_str(tcx.parent(trait_item.def_id))))
                })).with_code(E0053)
}struct_span_code_err!(
1995                tcx.dcx(),
1996                param_impl_span,
1997                E0053,
1998                "{} `{}` has an incompatible generic parameter for trait `{}`",
1999                impl_item.descr(),
2000                trait_item.name(),
2001                &tcx.def_path_str(tcx.parent(trait_item.def_id))
2002            );
2003
2004            let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
2005                Const { .. } => {
2006                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} const parameter of type `{1}`",
                prefix, tcx.type_of(param.def_id).instantiate_identity()))
    })format!(
2007                        "{} const parameter of type `{}`",
2008                        prefix,
2009                        tcx.type_of(param.def_id).instantiate_identity()
2010                    )
2011                }
2012                Type { .. } => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} type parameter", prefix))
    })format!("{prefix} type parameter"),
2013                Lifetime { .. } => ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(param.def_id),
    format_args!("lifetime params are expected to be filtered by `ty_const_params_of`"))span_bug!(
2014                    tcx.def_span(param.def_id),
2015                    "lifetime params are expected to be filtered by `ty_const_params_of`"
2016                ),
2017            };
2018
2019            let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
2020            err.span_label(trait_header_span, "");
2021            err.span_label(param_trait_span, make_param_message("expected", param_trait));
2022
2023            let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
2024            err.span_label(impl_header_span, "");
2025            err.span_label(param_impl_span, make_param_message("found", param_impl));
2026
2027            let reported = err.emit_unless_delay(delay);
2028            return Err(reported);
2029        }
2030    }
2031
2032    Ok(())
2033}
2034
2035fn compare_impl_const<'tcx>(
2036    tcx: TyCtxt<'tcx>,
2037    impl_const_item: ty::AssocItem,
2038    trait_const_item: ty::AssocItem,
2039    impl_trait_ref: ty::TraitRef<'tcx>,
2040) -> Result<(), ErrorGuaranteed> {
2041    compare_type_const(tcx, impl_const_item, trait_const_item)?;
2042    compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
2043    compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
2044    check_region_bounds_on_impl_item(tcx, impl_const_item, trait_const_item, false)?;
2045    compare_const_predicate_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
2046}
2047
2048fn compare_type_const<'tcx>(
2049    tcx: TyCtxt<'tcx>,
2050    impl_const_item: ty::AssocItem,
2051    trait_const_item: ty::AssocItem,
2052) -> Result<(), ErrorGuaranteed> {
2053    let impl_is_type_const = tcx.is_type_const(impl_const_item.def_id);
2054    let trait_type_const_span = tcx.type_const_span(trait_const_item.def_id);
2055
2056    if let Some(trait_type_const_span) = trait_type_const_span
2057        && !impl_is_type_const
2058    {
2059        return Err(tcx
2060            .dcx()
2061            .struct_span_err(
2062                tcx.def_span(impl_const_item.def_id),
2063                "implementation of a `type const` must also be marked as `type const`",
2064            )
2065            .with_span_note(
2066                MultiSpan::from_spans(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [tcx.def_span(trait_const_item.def_id), trait_type_const_span]))vec![
2067                    tcx.def_span(trait_const_item.def_id),
2068                    trait_type_const_span,
2069                ]),
2070                "trait declaration of const is marked as `type const`",
2071            )
2072            .emit());
2073    }
2074    Ok(())
2075}
2076
2077/// The equivalent of [compare_method_predicate_entailment], but for associated constants
2078/// instead of associated functions.
2079// FIXME(generic_const_items): If possible extract the common parts of `compare_{type,const}_predicate_entailment`.
2080#[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("compare_const_predicate_entailment",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2080u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["impl_ct",
                                                    "trait_ct", "impl_trait_ref"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ct)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ct)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let impl_ct_def_id = impl_ct.def_id.expect_local();
            let impl_ct_span = tcx.def_span(impl_ct_def_id);
            let trait_to_impl_args =
                GenericArgs::identity_for_item(tcx,
                        impl_ct.def_id).rebase_onto(tcx, impl_ct.container_id(tcx),
                    impl_trait_ref.args);
            let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
            let trait_ty =
                tcx.type_of(trait_ct.def_id).instantiate(tcx,
                    trait_to_impl_args);
            let code =
                ObligationCauseCode::CompareImplItem {
                    impl_item_def_id: impl_ct_def_id,
                    trait_item_def_id: trait_ct.def_id,
                    kind: impl_ct.kind,
                };
            let mut cause =
                ObligationCause::new(impl_ct_span, impl_ct_def_id,
                    code.clone());
            let impl_ct_predicates = tcx.predicates_of(impl_ct.def_id);
            let trait_ct_predicates = tcx.predicates_of(trait_ct.def_id);
            let impl_predicates =
                tcx.predicates_of(impl_ct_predicates.parent.unwrap());
            let mut hybrid_preds =
                impl_predicates.instantiate_identity(tcx).predicates;
            hybrid_preds.extend(trait_ct_predicates.instantiate_own(tcx,
                        trait_to_impl_args).map(|(predicate, _)| predicate));
            let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
            let param_env =
                traits::normalize_param_env_or_error(tcx, param_env,
                    ObligationCause::misc(impl_ct_span, impl_ct_def_id));
            let infcx =
                tcx.infer_ctxt().build(TypingMode::non_body_analysis());
            let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
            let impl_ct_own_bounds =
                impl_ct_predicates.instantiate_own_identity();
            for (predicate, span) in impl_ct_own_bounds {
                let cause = ObligationCause::misc(span, impl_ct_def_id);
                let predicate = ocx.normalize(&cause, param_env, predicate);
                let cause =
                    ObligationCause::new(span, impl_ct_def_id, code.clone());
                ocx.register_obligation(traits::Obligation::new(tcx, cause,
                        param_env, predicate));
            }
            let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2147",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2147u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["impl_ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&impl_ty) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2150",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2150u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["trait_ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&trait_ty)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
            if let Err(terr) = err {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2155",
                                        "rustc_hir_analysis::check::compare_impl_item",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                        ::tracing_core::__macro_support::Option::Some(2155u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                        ::tracing_core::field::FieldSet::new(&["impl_ty",
                                                        "trait_ty"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&impl_ty) as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&trait_ty)
                                                            as &dyn Value))])
                            });
                    } else { ; }
                };
                let (ty, _) =
                    tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
                cause.span = ty.span;
                let mut diag =
                    {
                        tcx.dcx().struct_span_err(cause.span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("implemented const `{0}` has an incompatible type for trait",
                                                trait_ct.name()))
                                    })).with_code(E0326)
                    };
                let trait_c_span =
                    trait_ct.def_id.as_local().map(|trait_ct_def_id|
                            {
                                let (ty, _) =
                                    tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
                                ty.span
                            });
                infcx.err_ctxt().note_type_err(&mut diag, &cause,
                    trait_c_span.map(|span|
                            (span, Cow::from("type in trait"), false)),
                    Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
                                    expected: trait_ty.into(),
                                    found: impl_ty.into(),
                                }))), terr, false, None);
                return Err(diag.emit());
            };
            let errors = ocx.evaluate_obligations_error_on_ambiguity();
            if !errors.is_empty() {
                return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
            }
            ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env,
                [])
        }
    }
}#[instrument(level = "debug", skip(tcx))]
2081fn compare_const_predicate_entailment<'tcx>(
2082    tcx: TyCtxt<'tcx>,
2083    impl_ct: ty::AssocItem,
2084    trait_ct: ty::AssocItem,
2085    impl_trait_ref: ty::TraitRef<'tcx>,
2086) -> Result<(), ErrorGuaranteed> {
2087    let impl_ct_def_id = impl_ct.def_id.expect_local();
2088    let impl_ct_span = tcx.def_span(impl_ct_def_id);
2089
2090    // The below is for the most part highly similar to the procedure
2091    // for methods above. It is simpler in many respects, especially
2092    // because we shouldn't really have to deal with lifetimes or
2093    // predicates. In fact some of this should probably be put into
2094    // shared functions because of DRY violations...
2095    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id).rebase_onto(
2096        tcx,
2097        impl_ct.container_id(tcx),
2098        impl_trait_ref.args,
2099    );
2100
2101    // Create a parameter environment that represents the implementation's
2102    // associated const.
2103    let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
2104
2105    let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
2106    let code = ObligationCauseCode::CompareImplItem {
2107        impl_item_def_id: impl_ct_def_id,
2108        trait_item_def_id: trait_ct.def_id,
2109        kind: impl_ct.kind,
2110    };
2111    let mut cause = ObligationCause::new(impl_ct_span, impl_ct_def_id, code.clone());
2112
2113    let impl_ct_predicates = tcx.predicates_of(impl_ct.def_id);
2114    let trait_ct_predicates = tcx.predicates_of(trait_ct.def_id);
2115
2116    // The predicates declared by the impl definition, the trait and the
2117    // associated const in the trait are assumed.
2118    let impl_predicates = tcx.predicates_of(impl_ct_predicates.parent.unwrap());
2119    let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2120    hybrid_preds.extend(
2121        trait_ct_predicates
2122            .instantiate_own(tcx, trait_to_impl_args)
2123            .map(|(predicate, _)| predicate),
2124    );
2125
2126    let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
2127    let param_env = traits::normalize_param_env_or_error(
2128        tcx,
2129        param_env,
2130        ObligationCause::misc(impl_ct_span, impl_ct_def_id),
2131    );
2132
2133    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2134    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2135
2136    let impl_ct_own_bounds = impl_ct_predicates.instantiate_own_identity();
2137    for (predicate, span) in impl_ct_own_bounds {
2138        let cause = ObligationCause::misc(span, impl_ct_def_id);
2139        let predicate = ocx.normalize(&cause, param_env, predicate);
2140
2141        let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
2142        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2143    }
2144
2145    // There is no "body" here, so just pass dummy id.
2146    let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
2147    debug!(?impl_ty);
2148
2149    let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
2150    debug!(?trait_ty);
2151
2152    let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
2153
2154    if let Err(terr) = err {
2155        debug!(?impl_ty, ?trait_ty);
2156
2157        // Locate the Span containing just the type of the offending impl
2158        let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
2159        cause.span = ty.span;
2160
2161        let mut diag = struct_span_code_err!(
2162            tcx.dcx(),
2163            cause.span,
2164            E0326,
2165            "implemented const `{}` has an incompatible type for trait",
2166            trait_ct.name()
2167        );
2168
2169        let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
2170            // Add a label to the Span containing just the type of the const
2171            let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
2172            ty.span
2173        });
2174
2175        infcx.err_ctxt().note_type_err(
2176            &mut diag,
2177            &cause,
2178            trait_c_span.map(|span| (span, Cow::from("type in trait"), false)),
2179            Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2180                expected: trait_ty.into(),
2181                found: impl_ty.into(),
2182            }))),
2183            terr,
2184            false,
2185            None,
2186        );
2187        return Err(diag.emit());
2188    };
2189
2190    // Check that all obligations are satisfied by the implementation's
2191    // version.
2192    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2193    if !errors.is_empty() {
2194        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2195    }
2196
2197    ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env, [])
2198}
2199
2200#[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("compare_impl_ty",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2200u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["impl_ty",
                                                    "trait_ty", "impl_trait_ref"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
            compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
            check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
            compare_type_predicate_entailment(tcx, impl_ty, trait_ty,
                    impl_trait_ref)?;
            check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
        }
    }
}#[instrument(level = "debug", skip(tcx))]
2201fn compare_impl_ty<'tcx>(
2202    tcx: TyCtxt<'tcx>,
2203    impl_ty: ty::AssocItem,
2204    trait_ty: ty::AssocItem,
2205    impl_trait_ref: ty::TraitRef<'tcx>,
2206) -> Result<(), ErrorGuaranteed> {
2207    compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
2208    compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
2209    check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
2210    compare_type_predicate_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
2211    check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
2212}
2213
2214/// The equivalent of [compare_method_predicate_entailment], but for associated types
2215/// instead of associated functions.
2216#[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("compare_type_predicate_entailment",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2216u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["impl_ty",
                                                    "trait_ty", "impl_trait_ref"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let impl_def_id = impl_ty.container_id(tcx);
            let trait_to_impl_args =
                GenericArgs::identity_for_item(tcx,
                        impl_ty.def_id).rebase_onto(tcx, impl_def_id,
                    impl_trait_ref.args);
            let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
            let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
            let impl_ty_own_bounds =
                impl_ty_predicates.instantiate_own_identity();
            if impl_ty_own_bounds.len() == 0 { return Ok(()); }
            let impl_ty_def_id = impl_ty.def_id.expect_local();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2244",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2244u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["trait_to_impl_args"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&trait_to_impl_args)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let impl_predicates =
                tcx.predicates_of(impl_ty_predicates.parent.unwrap());
            let mut hybrid_preds =
                impl_predicates.instantiate_identity(tcx).predicates;
            hybrid_preds.extend(trait_ty_predicates.instantiate_own(tcx,
                        trait_to_impl_args).map(|(predicate, _)| predicate));
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2255",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2255u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["hybrid_preds"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&hybrid_preds)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let impl_ty_span = tcx.def_span(impl_ty_def_id);
            let normalize_cause =
                ObligationCause::misc(impl_ty_span, impl_ty_def_id);
            let is_conditionally_const =
                tcx.is_conditionally_const(impl_ty.def_id);
            if is_conditionally_const {
                hybrid_preds.extend(tcx.const_conditions(impl_ty_predicates.parent.unwrap()).instantiate_identity(tcx).into_iter().chain(tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx,
                                trait_to_impl_args)).map(|(trait_ref, _)|
                            {
                                trait_ref.to_host_effect_clause(tcx,
                                    ty::BoundConstness::Maybe)
                            }));
            }
            let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
            let param_env =
                traits::normalize_param_env_or_error(tcx, param_env,
                    normalize_cause);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2279",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2279u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["caller_bounds"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&param_env.caller_bounds())
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let infcx =
                tcx.infer_ctxt().build(TypingMode::non_body_analysis());
            let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
            for (predicate, span) in impl_ty_own_bounds {
                let cause = ObligationCause::misc(span, impl_ty_def_id);
                let predicate = ocx.normalize(&cause, param_env, predicate);
                let cause =
                    ObligationCause::new(span, impl_ty_def_id,
                        ObligationCauseCode::CompareImplItem {
                            impl_item_def_id: impl_ty.def_id.expect_local(),
                            trait_item_def_id: trait_ty.def_id,
                            kind: impl_ty.kind,
                        });
                ocx.register_obligation(traits::Obligation::new(tcx, cause,
                        param_env, predicate));
            }
            if is_conditionally_const {
                let impl_ty_own_const_conditions =
                    tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
                for (const_condition, span) in impl_ty_own_const_conditions {
                    let normalize_cause =
                        traits::ObligationCause::misc(span, impl_ty_def_id);
                    let const_condition =
                        ocx.normalize(&normalize_cause, param_env, const_condition);
                    let cause =
                        ObligationCause::new(span, impl_ty_def_id,
                            ObligationCauseCode::CompareImplItem {
                                impl_item_def_id: impl_ty_def_id,
                                trait_item_def_id: trait_ty.def_id,
                                kind: impl_ty.kind,
                            });
                    ocx.register_obligation(traits::Obligation::new(tcx, cause,
                            param_env,
                            const_condition.to_host_effect_clause(tcx,
                                ty::BoundConstness::Maybe)));
                }
            }
            let errors = ocx.evaluate_obligations_error_on_ambiguity();
            if !errors.is_empty() {
                let reported =
                    infcx.err_ctxt().report_fulfillment_errors(errors);
                return Err(reported);
            }
            ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env,
                [])
        }
    }
}#[instrument(level = "debug", skip(tcx))]
2217fn compare_type_predicate_entailment<'tcx>(
2218    tcx: TyCtxt<'tcx>,
2219    impl_ty: ty::AssocItem,
2220    trait_ty: ty::AssocItem,
2221    impl_trait_ref: ty::TraitRef<'tcx>,
2222) -> Result<(), ErrorGuaranteed> {
2223    let impl_def_id = impl_ty.container_id(tcx);
2224    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
2225        tcx,
2226        impl_def_id,
2227        impl_trait_ref.args,
2228    );
2229
2230    let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
2231    let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
2232
2233    let impl_ty_own_bounds = impl_ty_predicates.instantiate_own_identity();
2234    // If there are no bounds, then there are no const conditions, so no need to check that here.
2235    if impl_ty_own_bounds.len() == 0 {
2236        // Nothing to check.
2237        return Ok(());
2238    }
2239
2240    // This `DefId` should be used for the `body_id` field on each
2241    // `ObligationCause` (and the `FnCtxt`). This is what
2242    // `regionck_item` expects.
2243    let impl_ty_def_id = impl_ty.def_id.expect_local();
2244    debug!(?trait_to_impl_args);
2245
2246    // The predicates declared by the impl definition, the trait and the
2247    // associated type in the trait are assumed.
2248    let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
2249    let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2250    hybrid_preds.extend(
2251        trait_ty_predicates
2252            .instantiate_own(tcx, trait_to_impl_args)
2253            .map(|(predicate, _)| predicate),
2254    );
2255    debug!(?hybrid_preds);
2256
2257    let impl_ty_span = tcx.def_span(impl_ty_def_id);
2258    let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
2259
2260    let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
2261    if is_conditionally_const {
2262        // Augment the hybrid param-env with the const conditions
2263        // of the impl header and the trait assoc type.
2264        hybrid_preds.extend(
2265            tcx.const_conditions(impl_ty_predicates.parent.unwrap())
2266                .instantiate_identity(tcx)
2267                .into_iter()
2268                .chain(
2269                    tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
2270                )
2271                .map(|(trait_ref, _)| {
2272                    trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
2273                }),
2274        );
2275    }
2276
2277    let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
2278    let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
2279    debug!(caller_bounds=?param_env.caller_bounds());
2280
2281    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2282    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2283
2284    for (predicate, span) in impl_ty_own_bounds {
2285        let cause = ObligationCause::misc(span, impl_ty_def_id);
2286        let predicate = ocx.normalize(&cause, param_env, predicate);
2287
2288        let cause = ObligationCause::new(
2289            span,
2290            impl_ty_def_id,
2291            ObligationCauseCode::CompareImplItem {
2292                impl_item_def_id: impl_ty.def_id.expect_local(),
2293                trait_item_def_id: trait_ty.def_id,
2294                kind: impl_ty.kind,
2295            },
2296        );
2297        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2298    }
2299
2300    if is_conditionally_const {
2301        // Validate the const conditions of the impl associated type.
2302        let impl_ty_own_const_conditions =
2303            tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2304        for (const_condition, span) in impl_ty_own_const_conditions {
2305            let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2306            let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2307
2308            let cause = ObligationCause::new(
2309                span,
2310                impl_ty_def_id,
2311                ObligationCauseCode::CompareImplItem {
2312                    impl_item_def_id: impl_ty_def_id,
2313                    trait_item_def_id: trait_ty.def_id,
2314                    kind: impl_ty.kind,
2315                },
2316            );
2317            ocx.register_obligation(traits::Obligation::new(
2318                tcx,
2319                cause,
2320                param_env,
2321                const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2322            ));
2323        }
2324    }
2325
2326    // Check that all obligations are satisfied by the implementation's
2327    // version.
2328    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2329    if !errors.is_empty() {
2330        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2331        return Err(reported);
2332    }
2333
2334    // Finally, resolve all regions. This catches wily misuses of
2335    // lifetime parameters.
2336    ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2337}
2338
2339/// Validate that `ProjectionCandidate`s created for this associated type will
2340/// be valid.
2341///
2342/// Usually given
2343///
2344/// trait X { type Y: Copy } impl X for T { type Y = S; }
2345///
2346/// We are able to normalize `<T as X>::Y` to `S`, and so when we check the
2347/// impl is well-formed we have to prove `S: Copy`.
2348///
2349/// For default associated types the normalization is not possible (the value
2350/// from the impl could be overridden). We also can't normalize generic
2351/// associated types (yet) because they contain bound parameters.
2352#[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("check_type_bounds",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2352u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["trait_ty",
                                                    "impl_ty", "impl_trait_ref"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            tcx.ensure_ok().coherent_trait(impl_trait_ref.def_id)?;
            let param_env = tcx.param_env(impl_ty.def_id);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2364",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2364u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["param_env"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&param_env)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let container_id = impl_ty.container_id(tcx);
            let impl_ty_def_id = impl_ty.def_id.expect_local();
            let impl_ty_args =
                GenericArgs::identity_for_item(tcx, impl_ty.def_id);
            let rebased_args =
                impl_ty_args.rebase_onto(tcx, container_id,
                    impl_trait_ref.args);
            let infcx =
                tcx.infer_ctxt().build(TypingMode::non_body_analysis());
            let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
            let impl_ty_span =
                if impl_ty.is_impl_trait_in_trait() {
                    tcx.def_span(impl_ty_def_id)
                } else {
                    match tcx.hir_node_by_def_id(impl_ty_def_id) {
                        hir::Node::TraitItem(hir::TraitItem {
                            kind: hir::TraitItemKind::Type(_, Some(ty)), .. }) =>
                            ty.span,
                        hir::Node::ImplItem(hir::ImplItem {
                            kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
                        item =>
                            ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(impl_ty_def_id),
                                format_args!("cannot call `check_type_bounds` on item: {0:?}",
                                    item)),
                    }
                };
            let assumed_wf_types =
                ocx.assumed_wf_types_and_report_errors(param_env,
                        impl_ty_def_id)?;
            let normalize_cause =
                ObligationCause::new(impl_ty_span, impl_ty_def_id,
                    ObligationCauseCode::CheckAssociatedTypeBounds {
                        impl_item_def_id: impl_ty.def_id.expect_local(),
                        trait_item_def_id: trait_ty.def_id,
                    });
            let mk_cause =
                |span: Span|
                    {
                        let code =
                            ObligationCauseCode::WhereClause(trait_ty.def_id, span);
                        ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
                    };
            let mut obligations: Vec<_> =
                util::elaborate(tcx,
                        tcx.explicit_item_bounds(trait_ty.def_id).iter_instantiated_copied(tcx,
                                rebased_args).map(|(concrete_ty_bound, span)|
                                {
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2411",
                                                            "rustc_hir_analysis::check::compare_impl_item",
                                                            ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(2411u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                                            ::tracing_core::field::FieldSet::new(&["concrete_ty_bound"],
                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                        ::tracing::__macro_support::Option::Some(&debug(&concrete_ty_bound)
                                                                                as &dyn Value))])
                                                });
                                        } else { ; }
                                    };
                                    traits::Obligation::new(tcx, mk_cause(span), param_env,
                                        concrete_ty_bound)
                                })).collect();
            if tcx.is_conditionally_const(impl_ty_def_id) {
                obligations.extend(util::elaborate(tcx,
                        tcx.explicit_implied_const_bounds(trait_ty.def_id).iter_instantiated_copied(tcx,
                                rebased_args).map(|(c, span)|
                                {
                                    traits::Obligation::new(tcx, mk_cause(span), param_env,
                                        c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe))
                                })));
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2434",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2434u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["item_bounds"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&obligations)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let normalize_param_env =
                param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
            for obligation in &mut obligations {
                match ocx.deeply_normalize(&normalize_cause,
                        normalize_param_env, obligation.predicate) {
                    Ok(pred) => obligation.predicate = pred,
                    Err(e) => {
                        return Err(infcx.err_ctxt().report_fulfillment_errors(e));
                    }
                }
            }
            ocx.register_obligations(obligations);
            let errors = ocx.evaluate_obligations_error_on_ambiguity();
            if !errors.is_empty() {
                let reported =
                    infcx.err_ctxt().report_fulfillment_errors(errors);
                return Err(reported);
            }
            ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env,
                assumed_wf_types)
        }
    }
}#[instrument(level = "debug", skip(tcx))]
2353pub(super) fn check_type_bounds<'tcx>(
2354    tcx: TyCtxt<'tcx>,
2355    trait_ty: ty::AssocItem,
2356    impl_ty: ty::AssocItem,
2357    impl_trait_ref: ty::TraitRef<'tcx>,
2358) -> Result<(), ErrorGuaranteed> {
2359    // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
2360    // other `Foo` impls are incoherent.
2361    tcx.ensure_ok().coherent_trait(impl_trait_ref.def_id)?;
2362
2363    let param_env = tcx.param_env(impl_ty.def_id);
2364    debug!(?param_env);
2365
2366    let container_id = impl_ty.container_id(tcx);
2367    let impl_ty_def_id = impl_ty.def_id.expect_local();
2368    let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2369    let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2370
2371    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2372    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2373
2374    // A synthetic impl Trait for RPITIT desugaring or assoc type for effects desugaring has no HIR,
2375    // which we currently use to get the span for an impl's associated type. Instead, for these,
2376    // use the def_span for the synthesized  associated type.
2377    let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2378        tcx.def_span(impl_ty_def_id)
2379    } else {
2380        match tcx.hir_node_by_def_id(impl_ty_def_id) {
2381            hir::Node::TraitItem(hir::TraitItem {
2382                kind: hir::TraitItemKind::Type(_, Some(ty)),
2383                ..
2384            }) => ty.span,
2385            hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2386            item => span_bug!(
2387                tcx.def_span(impl_ty_def_id),
2388                "cannot call `check_type_bounds` on item: {item:?}",
2389            ),
2390        }
2391    };
2392    let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2393
2394    let normalize_cause = ObligationCause::new(
2395        impl_ty_span,
2396        impl_ty_def_id,
2397        ObligationCauseCode::CheckAssociatedTypeBounds {
2398            impl_item_def_id: impl_ty.def_id.expect_local(),
2399            trait_item_def_id: trait_ty.def_id,
2400        },
2401    );
2402    let mk_cause = |span: Span| {
2403        let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2404        ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2405    };
2406
2407    let mut obligations: Vec<_> = util::elaborate(
2408        tcx,
2409        tcx.explicit_item_bounds(trait_ty.def_id).iter_instantiated_copied(tcx, rebased_args).map(
2410            |(concrete_ty_bound, span)| {
2411                debug!(?concrete_ty_bound);
2412                traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2413            },
2414        ),
2415    )
2416    .collect();
2417
2418    // Only in a const implementation do we need to check that the `[const]` item bounds hold.
2419    if tcx.is_conditionally_const(impl_ty_def_id) {
2420        obligations.extend(util::elaborate(
2421            tcx,
2422            tcx.explicit_implied_const_bounds(trait_ty.def_id)
2423                .iter_instantiated_copied(tcx, rebased_args)
2424                .map(|(c, span)| {
2425                    traits::Obligation::new(
2426                        tcx,
2427                        mk_cause(span),
2428                        param_env,
2429                        c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2430                    )
2431                }),
2432        ));
2433    }
2434    debug!(item_bounds=?obligations);
2435
2436    // Normalize predicates with the assumption that the GAT may always normalize
2437    // to its definition type. This should be the param-env we use to *prove* the
2438    // predicate too, but we don't do that because of performance issues.
2439    // See <https://github.com/rust-lang/rust/pull/117542#issue-1976337685>.
2440    let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2441    for obligation in &mut obligations {
2442        match ocx.deeply_normalize(&normalize_cause, normalize_param_env, obligation.predicate) {
2443            Ok(pred) => obligation.predicate = pred,
2444            Err(e) => {
2445                return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2446            }
2447        }
2448    }
2449
2450    // Check that all obligations are satisfied by the implementation's
2451    // version.
2452    ocx.register_obligations(obligations);
2453    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2454    if !errors.is_empty() {
2455        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2456        return Err(reported);
2457    }
2458
2459    // Finally, resolve all regions. This catches wily misuses of
2460    // lifetime parameters.
2461    ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2462}
2463
2464/// Install projection predicates that allow GATs to project to their own
2465/// definition types. This is not allowed in general in cases of default
2466/// associated types in trait definitions, or when specialization is involved,
2467/// but is needed when checking these definition types actually satisfy the
2468/// trait bounds of the GAT.
2469///
2470/// # How it works
2471///
2472/// ```ignore (example)
2473/// impl<A, B> Foo<u32> for (A, B) {
2474///     type Bar<C> = Wrapper<A, B, C>
2475/// }
2476/// ```
2477///
2478/// - `impl_trait_ref` would be `<(A, B) as Foo<u32>>`
2479/// - `normalize_impl_ty_args` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
2480/// - `normalize_impl_ty` would be `Wrapper<A, B, ^0.0>`
2481/// - `rebased_args` would be `[(A, B), u32, ^0.0]`, combining the args from
2482///    the *trait* with the generic associated type parameters (as bound vars).
2483///
2484/// A note regarding the use of bound vars here:
2485/// Imagine as an example
2486/// ```
2487/// trait Family {
2488///     type Member<C: Eq>;
2489/// }
2490///
2491/// impl Family for VecFamily {
2492///     type Member<C: Eq> = i32;
2493/// }
2494/// ```
2495/// Here, we would generate
2496/// ```ignore (pseudo-rust)
2497/// forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
2498/// ```
2499///
2500/// when we really would like to generate
2501/// ```ignore (pseudo-rust)
2502/// forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
2503/// ```
2504///
2505/// But, this is probably fine, because although the first clause can be used with types `C` that
2506/// do not implement `Eq`, for it to cause some kind of problem, there would have to be a
2507/// `VecFamily::Member<X>` for some type `X` where `!(X: Eq)`, that appears in the value of type
2508/// `Member<C: Eq> = ....` That type would fail a well-formedness check that we ought to be doing
2509/// elsewhere, which would check that any `<T as Family>::Member<X>` meets the bounds declared in
2510/// the trait (notably, that `X: Eq` and `T: Family`).
2511fn param_env_with_gat_bounds<'tcx>(
2512    tcx: TyCtxt<'tcx>,
2513    impl_ty: ty::AssocItem,
2514    impl_trait_ref: ty::TraitRef<'tcx>,
2515) -> ty::ParamEnv<'tcx> {
2516    let param_env = tcx.param_env(impl_ty.def_id);
2517    let container_id = impl_ty.container_id(tcx);
2518    let mut predicates = param_env.caller_bounds().to_vec();
2519
2520    // for RPITITs, we should install predicates that allow us to project all
2521    // of the RPITITs associated with the same body. This is because checking
2522    // the item bounds of RPITITs often involves nested RPITITs having to prove
2523    // bounds about themselves.
2524    let impl_tys_to_install = match impl_ty.kind {
2525        ty::AssocKind::Type {
2526            data:
2527                ty::AssocTypeData::Rpitit(
2528                    ty::ImplTraitInTraitData::Impl { fn_def_id }
2529                    | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2530                ),
2531        } => tcx
2532            .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2533            .iter()
2534            .map(|def_id| tcx.associated_item(*def_id))
2535            .collect(),
2536        _ => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [impl_ty]))vec![impl_ty],
2537    };
2538
2539    for impl_ty in impl_tys_to_install {
2540        let trait_ty = match impl_ty.container {
2541            ty::AssocContainer::InherentImpl => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
2542            ty::AssocContainer::Trait => impl_ty,
2543            ty::AssocContainer::TraitImpl(Err(_)) => continue,
2544            ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
2545                tcx.associated_item(trait_item_def_id)
2546            }
2547        };
2548
2549        let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind<'tcx>; 8]> =
2550            smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2551        // Extend the impl's identity args with late-bound GAT vars
2552        let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2553            .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2554                GenericParamDefKind::Type { .. } => {
2555                    let kind = ty::BoundTyKind::Param(param.def_id);
2556                    let bound_var = ty::BoundVariableKind::Ty(kind);
2557                    bound_vars.push(bound_var);
2558                    Ty::new_bound(
2559                        tcx,
2560                        ty::INNERMOST,
2561                        ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2562                    )
2563                    .into()
2564                }
2565                GenericParamDefKind::Lifetime => {
2566                    let kind = ty::BoundRegionKind::Named(param.def_id);
2567                    let bound_var = ty::BoundVariableKind::Region(kind);
2568                    bound_vars.push(bound_var);
2569                    ty::Region::new_bound(
2570                        tcx,
2571                        ty::INNERMOST,
2572                        ty::BoundRegion {
2573                            var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2574                            kind,
2575                        },
2576                    )
2577                    .into()
2578                }
2579                GenericParamDefKind::Const { .. } => {
2580                    let bound_var = ty::BoundVariableKind::Const;
2581                    bound_vars.push(bound_var);
2582                    ty::Const::new_bound(
2583                        tcx,
2584                        ty::INNERMOST,
2585                        ty::BoundConst::new(ty::BoundVar::from_usize(bound_vars.len() - 1)),
2586                    )
2587                    .into()
2588                }
2589            });
2590        // When checking something like
2591        //
2592        // trait X { type Y: PartialEq<<Self as X>::Y> }
2593        // impl X for T { default type Y = S; }
2594        //
2595        // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
2596        // we want <T as X>::Y to normalize to S. This is valid because we are
2597        // checking the default value specifically here. Add this equality to the
2598        // ParamEnv for normalization specifically.
2599        let normalize_impl_ty =
2600            tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args);
2601        let rebased_args =
2602            normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2603        let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2604
2605        match normalize_impl_ty.kind() {
2606            ty::Alias(ty::Projection, proj)
2607                if proj.def_id == trait_ty.def_id && proj.args == rebased_args =>
2608            {
2609                // Don't include this predicate if the projected type is
2610                // exactly the same as the projection. This can occur in
2611                // (somewhat dubious) code like this:
2612                //
2613                // impl<T> X for T where T: X { type Y = <T as X>::Y; }
2614            }
2615            _ => predicates.push(
2616                ty::Binder::bind_with_vars(
2617                    ty::ProjectionPredicate {
2618                        projection_term: ty::AliasTerm::new_from_args(
2619                            tcx,
2620                            trait_ty.def_id,
2621                            rebased_args,
2622                        ),
2623                        term: normalize_impl_ty.into(),
2624                    },
2625                    bound_vars,
2626                )
2627                .upcast(tcx),
2628            ),
2629        };
2630    }
2631
2632    ty::ParamEnv::new(tcx.mk_clauses(&predicates))
2633}
2634
2635/// Manually check here that `async fn foo()` wasn't matched against `fn foo()`,
2636/// and extract a better error if so.
2637fn try_report_async_mismatch<'tcx>(
2638    tcx: TyCtxt<'tcx>,
2639    infcx: &InferCtxt<'tcx>,
2640    errors: &[FulfillmentError<'tcx>],
2641    trait_m: ty::AssocItem,
2642    impl_m: ty::AssocItem,
2643    impl_sig: ty::FnSig<'tcx>,
2644) -> Result<(), ErrorGuaranteed> {
2645    if !tcx.asyncness(trait_m.def_id).is_async() {
2646        return Ok(());
2647    }
2648
2649    let ty::Alias(ty::Projection, ty::AliasTy { def_id: async_future_def_id, .. }) =
2650        *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2651    else {
2652        ::rustc_middle::util::bug::bug_fmt(format_args!("expected `async fn` to return an RPITIT"));bug!("expected `async fn` to return an RPITIT");
2653    };
2654
2655    for error in errors {
2656        if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2657            && def_id == async_future_def_id
2658            && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2659            && let Some(proj) = proj.no_bound_vars()
2660            && infcx.can_eq(
2661                error.root_obligation.param_env,
2662                proj.term.expect_type(),
2663                impl_sig.output(),
2664            )
2665        {
2666            // FIXME: We should suggest making the fn `async`, but extracting
2667            // the right span is a bit difficult.
2668            return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2669                span: tcx.def_span(impl_m.def_id),
2670                method_name: tcx.item_ident(impl_m.def_id),
2671                trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
2672            }));
2673        }
2674    }
2675
2676    Ok(())
2677}