Skip to main content

rustc_hir_analysis/check/
compare_impl_item.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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 hybrid_preds =
                hybrid_preds.into_iter().map(Unnormalized::skip_norm_wip);
            let param_env =
                ty::ParamEnv::new(tcx.mk_clauses_from_iter(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:2256",
                                    "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(2256u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_ty");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
                                                        as &dyn ::tracing::field::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:2259",
                                    "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(2259u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_ty");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
                                                        as &dyn ::tracing::field::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:2264",
                                        "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(2264u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                        ::tracing_core::field::FieldSet::new(&[{
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("impl_ty")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("impl_ty");
                                                            NAME.as_str()
                                                        },
                                                        {
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("trait_ty")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("trait_ty");
                                                            NAME.as_str()
                                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
                                                            as &dyn ::tracing::field::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))]
2189fn compare_const_predicate_entailment<'tcx>(
2190    tcx: TyCtxt<'tcx>,
2191    impl_ct: ty::AssocItem,
2192    trait_ct: ty::AssocItem,
2193    impl_trait_ref: ty::TraitRef<'tcx>,
2194) -> Result<(), ErrorGuaranteed> {
2195    let impl_ct_def_id = impl_ct.def_id.expect_local();
2196    let impl_ct_span = tcx.def_span(impl_ct_def_id);
2197
2198    // The below is for the most part highly similar to the procedure
2199    // for methods above. It is simpler in many respects, especially
2200    // because we shouldn't really have to deal with lifetimes or
2201    // predicates. In fact some of this should probably be put into
2202    // shared functions because of DRY violations...
2203    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id).rebase_onto(
2204        tcx,
2205        impl_ct.container_id(tcx),
2206        impl_trait_ref.args,
2207    );
2208
2209    // Create a parameter environment that represents the implementation's
2210    // associated const.
2211    let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
2212
2213    let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
2214    let code = ObligationCauseCode::CompareImplItem {
2215        impl_item_def_id: impl_ct_def_id,
2216        trait_item_def_id: trait_ct.def_id,
2217        kind: impl_ct.kind,
2218    };
2219    let mut cause = ObligationCause::new(impl_ct_span, impl_ct_def_id, code.clone());
2220
2221    let impl_ct_predicates = tcx.predicates_of(impl_ct.def_id);
2222    let trait_ct_predicates = tcx.predicates_of(trait_ct.def_id);
2223
2224    // The predicates declared by the impl definition, the trait and the
2225    // associated const in the trait are assumed.
2226    let impl_predicates = tcx.predicates_of(impl_ct_predicates.parent.unwrap());
2227    let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2228    hybrid_preds.extend(
2229        trait_ct_predicates
2230            .instantiate_own(tcx, trait_to_impl_args)
2231            .map(|(predicate, _)| predicate),
2232    );
2233    let hybrid_preds = hybrid_preds.into_iter().map(Unnormalized::skip_norm_wip);
2234
2235    let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
2236    let param_env = traits::normalize_param_env_or_error(
2237        tcx,
2238        param_env,
2239        ObligationCause::misc(impl_ct_span, impl_ct_def_id),
2240    );
2241
2242    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2243    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2244
2245    let impl_ct_own_bounds = impl_ct_predicates.instantiate_own_identity();
2246    for (predicate, span) in impl_ct_own_bounds {
2247        let cause = ObligationCause::misc(span, impl_ct_def_id);
2248        let predicate = ocx.normalize(&cause, param_env, predicate);
2249
2250        let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
2251        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2252    }
2253
2254    // There is no "body" here, so just pass dummy id.
2255    let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
2256    debug!(?impl_ty);
2257
2258    let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
2259    debug!(?trait_ty);
2260
2261    let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
2262
2263    if let Err(terr) = err {
2264        debug!(?impl_ty, ?trait_ty);
2265
2266        // Locate the Span containing just the type of the offending impl
2267        let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
2268        cause.span = ty.span;
2269
2270        let mut diag = struct_span_code_err!(
2271            tcx.dcx(),
2272            cause.span,
2273            E0326,
2274            "implemented const `{}` has an incompatible type for trait",
2275            trait_ct.name()
2276        );
2277
2278        let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
2279            // Add a label to the Span containing just the type of the const
2280            let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
2281            ty.span
2282        });
2283
2284        infcx.err_ctxt().note_type_err(
2285            &mut diag,
2286            &cause,
2287            trait_c_span.map(|span| (span, Cow::from("type in trait"), false)),
2288            Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2289                expected: trait_ty.into(),
2290                found: impl_ty.into(),
2291            }))),
2292            terr,
2293            false,
2294            None,
2295        );
2296        return Err(diag.emit());
2297    };
2298
2299    // Check that all obligations are satisfied by the implementation's
2300    // version.
2301    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2302    if !errors.is_empty() {
2303        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2304    }
2305
2306    ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env, [])
2307}
2308
2309#[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(2309u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_trait_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_trait_ref");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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))]
2310fn compare_impl_ty<'tcx>(
2311    tcx: TyCtxt<'tcx>,
2312    impl_ty: ty::AssocItem,
2313    trait_ty: ty::AssocItem,
2314    impl_trait_ref: ty::TraitRef<'tcx>,
2315) -> Result<(), ErrorGuaranteed> {
2316    compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
2317    compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
2318    check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
2319    compare_type_predicate_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
2320    check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
2321}
2322
2323/// The equivalent of [compare_method_predicate_entailment], but for associated types
2324/// instead of associated functions.
2325#[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(2325u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_trait_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_trait_ref");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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:2353",
                                    "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(2353u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_to_impl_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_to_impl_args");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_to_impl_args)
                                                        as &dyn ::tracing::field::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: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(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hybrid_preds")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hybrid_preds");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hybrid_preds)
                                                        as &dyn ::tracing::field::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 hybrid_preds =
                hybrid_preds.into_iter().map(Unnormalized::skip_norm_wip);
            let param_env =
                ty::ParamEnv::new(tcx.mk_clauses_from_iter(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:2389",
                                    "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(2389u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("caller_bounds")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("caller_bounds");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_env.caller_bounds())
                                                        as &dyn ::tracing::field::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))]
2326fn compare_type_predicate_entailment<'tcx>(
2327    tcx: TyCtxt<'tcx>,
2328    impl_ty: ty::AssocItem,
2329    trait_ty: ty::AssocItem,
2330    impl_trait_ref: ty::TraitRef<'tcx>,
2331) -> Result<(), ErrorGuaranteed> {
2332    let impl_def_id = impl_ty.container_id(tcx);
2333    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
2334        tcx,
2335        impl_def_id,
2336        impl_trait_ref.args,
2337    );
2338
2339    let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
2340    let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
2341
2342    let impl_ty_own_bounds = impl_ty_predicates.instantiate_own_identity();
2343    // If there are no bounds, then there are no const conditions, so no need to check that here.
2344    if impl_ty_own_bounds.len() == 0 {
2345        // Nothing to check.
2346        return Ok(());
2347    }
2348
2349    // This `DefId` should be used for the `body_def_id` field on each
2350    // `ObligationCause` (and the `FnCtxt`). This is what
2351    // `regionck_item` expects.
2352    let impl_ty_def_id = impl_ty.def_id.expect_local();
2353    debug!(?trait_to_impl_args);
2354
2355    // The predicates declared by the impl definition, the trait and the
2356    // associated type in the trait are assumed.
2357    let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
2358    let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2359    hybrid_preds.extend(
2360        trait_ty_predicates
2361            .instantiate_own(tcx, trait_to_impl_args)
2362            .map(|(predicate, _)| predicate),
2363    );
2364    debug!(?hybrid_preds);
2365
2366    let impl_ty_span = tcx.def_span(impl_ty_def_id);
2367    let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
2368
2369    let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
2370    if is_conditionally_const {
2371        // Augment the hybrid param-env with the const conditions
2372        // of the impl header and the trait assoc type.
2373        hybrid_preds.extend(
2374            tcx.const_conditions(impl_ty_predicates.parent.unwrap())
2375                .instantiate_identity(tcx)
2376                .into_iter()
2377                .chain(
2378                    tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
2379                )
2380                .map(|(trait_ref, _)| {
2381                    trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
2382                }),
2383        );
2384    }
2385
2386    let hybrid_preds = hybrid_preds.into_iter().map(Unnormalized::skip_norm_wip);
2387    let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
2388    let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
2389    debug!(caller_bounds=?param_env.caller_bounds());
2390
2391    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2392    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2393
2394    for (predicate, span) in impl_ty_own_bounds {
2395        let cause = ObligationCause::misc(span, impl_ty_def_id);
2396        let predicate = ocx.normalize(&cause, param_env, predicate);
2397
2398        let cause = ObligationCause::new(
2399            span,
2400            impl_ty_def_id,
2401            ObligationCauseCode::CompareImplItem {
2402                impl_item_def_id: impl_ty.def_id.expect_local(),
2403                trait_item_def_id: trait_ty.def_id,
2404                kind: impl_ty.kind,
2405            },
2406        );
2407        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2408    }
2409
2410    if is_conditionally_const {
2411        // Validate the const conditions of the impl associated type.
2412        let impl_ty_own_const_conditions =
2413            tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2414        for (const_condition, span) in impl_ty_own_const_conditions {
2415            let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2416            let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2417
2418            let cause = ObligationCause::new(
2419                span,
2420                impl_ty_def_id,
2421                ObligationCauseCode::CompareImplItem {
2422                    impl_item_def_id: impl_ty_def_id,
2423                    trait_item_def_id: trait_ty.def_id,
2424                    kind: impl_ty.kind,
2425                },
2426            );
2427            ocx.register_obligation(traits::Obligation::new(
2428                tcx,
2429                cause,
2430                param_env,
2431                const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2432            ));
2433        }
2434    }
2435
2436    // Check that all obligations are satisfied by the implementation's
2437    // version.
2438    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2439    if !errors.is_empty() {
2440        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2441        return Err(reported);
2442    }
2443
2444    // Finally, resolve all regions. This catches wily misuses of
2445    // lifetime parameters.
2446    ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2447}
2448
2449/// Validate that `ProjectionCandidate`s created for this associated type will
2450/// be valid.
2451///
2452/// Usually given
2453///
2454/// trait X { type Y: Copy } impl X for T { type Y = S; }
2455///
2456/// We are able to normalize `<T as X>::Y` to `S`, and so when we check the
2457/// impl is well-formed we have to prove `S: Copy`.
2458///
2459/// For default associated types the normalization is not possible (the value
2460/// from the impl could be overridden). We also can't normalize generic
2461/// associated types (yet) because they contain bound parameters.
2462#[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(2462u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_trait_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_trait_ref");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            tcx.ensure_result().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:2474",
                                    "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(2474u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("param_env")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("param_env");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_env)
                                                        as &dyn ::tracing::field::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(Unnormalized::skip_norm_wip).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:2523",
                                                            "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(2523u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                                            ::tracing_core::field::FieldSet::new(&[{
                                                                                const NAME:
                                                                                    ::tracing::__macro_support::FieldName<{
                                                                                        ::tracing::__macro_support::FieldName::len("concrete_ty_bound")
                                                                                    }> =
                                                                                    ::tracing::__macro_support::FieldName::new("concrete_ty_bound");
                                                                                NAME.as_str()
                                                                            }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&concrete_ty_bound)
                                                                                as &dyn ::tracing::field::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(Unnormalized::skip_norm_wip).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:2546",
                                    "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(2546u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item_bounds")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item_bounds");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligations)
                                                        as &dyn ::tracing::field::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,
                        Unnormalized::new_wip(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))]
2463pub(super) fn check_type_bounds<'tcx>(
2464    tcx: TyCtxt<'tcx>,
2465    trait_ty: ty::AssocItem,
2466    impl_ty: ty::AssocItem,
2467    impl_trait_ref: ty::TraitRef<'tcx>,
2468) -> Result<(), ErrorGuaranteed> {
2469    // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
2470    // other `Foo` impls are incoherent.
2471    tcx.ensure_result().coherent_trait(impl_trait_ref.def_id)?;
2472
2473    let param_env = tcx.param_env(impl_ty.def_id);
2474    debug!(?param_env);
2475
2476    let container_id = impl_ty.container_id(tcx);
2477    let impl_ty_def_id = impl_ty.def_id.expect_local();
2478    let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2479    let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2480
2481    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2482    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2483
2484    // A synthetic impl Trait for RPITIT desugaring or assoc type for effects desugaring has no HIR,
2485    // which we currently use to get the span for an impl's associated type. Instead, for these,
2486    // use the def_span for the synthesized  associated type.
2487    let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2488        tcx.def_span(impl_ty_def_id)
2489    } else {
2490        match tcx.hir_node_by_def_id(impl_ty_def_id) {
2491            hir::Node::TraitItem(hir::TraitItem {
2492                kind: hir::TraitItemKind::Type(_, Some(ty)),
2493                ..
2494            }) => ty.span,
2495            hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2496            item => span_bug!(
2497                tcx.def_span(impl_ty_def_id),
2498                "cannot call `check_type_bounds` on item: {item:?}",
2499            ),
2500        }
2501    };
2502    let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2503
2504    let normalize_cause = ObligationCause::new(
2505        impl_ty_span,
2506        impl_ty_def_id,
2507        ObligationCauseCode::CheckAssociatedTypeBounds {
2508            impl_item_def_id: impl_ty.def_id.expect_local(),
2509            trait_item_def_id: trait_ty.def_id,
2510        },
2511    );
2512    let mk_cause = |span: Span| {
2513        let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2514        ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2515    };
2516
2517    let mut obligations: Vec<_> = util::elaborate(
2518        tcx,
2519        tcx.explicit_item_bounds(trait_ty.def_id)
2520            .iter_instantiated_copied(tcx, rebased_args)
2521            .map(Unnormalized::skip_norm_wip)
2522            .map(|(concrete_ty_bound, span)| {
2523                debug!(?concrete_ty_bound);
2524                traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2525            }),
2526    )
2527    .collect();
2528
2529    // Only in a const implementation do we need to check that the `[const]` item bounds hold.
2530    if tcx.is_conditionally_const(impl_ty_def_id) {
2531        obligations.extend(util::elaborate(
2532            tcx,
2533            tcx.explicit_implied_const_bounds(trait_ty.def_id)
2534                .iter_instantiated_copied(tcx, rebased_args)
2535                .map(Unnormalized::skip_norm_wip)
2536                .map(|(c, span)| {
2537                    traits::Obligation::new(
2538                        tcx,
2539                        mk_cause(span),
2540                        param_env,
2541                        c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2542                    )
2543                }),
2544        ));
2545    }
2546    debug!(item_bounds=?obligations);
2547
2548    // Normalize predicates with the assumption that the GAT may always normalize
2549    // to its definition type. This should be the param-env we use to *prove* the
2550    // predicate too, but we don't do that because of performance issues.
2551    // See <https://github.com/rust-lang/rust/pull/117542#issue-1976337685>.
2552    let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2553    for obligation in &mut obligations {
2554        match ocx.deeply_normalize(
2555            &normalize_cause,
2556            normalize_param_env,
2557            Unnormalized::new_wip(obligation.predicate),
2558        ) {
2559            Ok(pred) => obligation.predicate = pred,
2560            Err(e) => {
2561                return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2562            }
2563        }
2564    }
2565
2566    // Check that all obligations are satisfied by the implementation's
2567    // version.
2568    ocx.register_obligations(obligations);
2569    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2570    if !errors.is_empty() {
2571        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2572        return Err(reported);
2573    }
2574
2575    // Finally, resolve all regions. This catches wily misuses of
2576    // lifetime parameters.
2577    ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2578}
2579
2580/// Install projection predicates that allow GATs to project to their own
2581/// definition types. This is not allowed in general in cases of default
2582/// associated types in trait definitions, or when specialization is involved,
2583/// but is needed when checking these definition types actually satisfy the
2584/// trait bounds of the GAT.
2585///
2586/// # How it works
2587///
2588/// ```ignore (example)
2589/// impl<A, B> Foo<u32> for (A, B) {
2590///     type Bar<C> = Wrapper<A, B, C>
2591/// }
2592/// ```
2593///
2594/// - `impl_trait_ref` would be `<(A, B) as Foo<u32>>`
2595/// - `normalize_impl_ty_args` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
2596/// - `normalize_impl_ty` would be `Wrapper<A, B, ^0.0>`
2597/// - `rebased_args` would be `[(A, B), u32, ^0.0]`, combining the args from
2598///    the *trait* with the generic associated type parameters (as bound vars).
2599///
2600/// A note regarding the use of bound vars here:
2601/// Imagine as an example
2602/// ```
2603/// trait Family {
2604///     type Member<C: Eq>;
2605/// }
2606///
2607/// impl Family for VecFamily {
2608///     type Member<C: Eq> = i32;
2609/// }
2610/// ```
2611/// Here, we would generate
2612/// ```ignore (pseudo-rust)
2613/// forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
2614/// ```
2615///
2616/// when we really would like to generate
2617/// ```ignore (pseudo-rust)
2618/// forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
2619/// ```
2620///
2621/// But, this is probably fine, because although the first clause can be used with types `C` that
2622/// do not implement `Eq`, for it to cause some kind of problem, there would have to be a
2623/// `VecFamily::Member<X>` for some type `X` where `!(X: Eq)`, that appears in the value of type
2624/// `Member<C: Eq> = ....` That type would fail a well-formedness check that we ought to be doing
2625/// elsewhere, which would check that any `<T as Family>::Member<X>` meets the bounds declared in
2626/// the trait (notably, that `X: Eq` and `T: Family`).
2627fn param_env_with_gat_bounds<'tcx>(
2628    tcx: TyCtxt<'tcx>,
2629    impl_ty: ty::AssocItem,
2630    impl_trait_ref: ty::TraitRef<'tcx>,
2631) -> ty::ParamEnv<'tcx> {
2632    let param_env = tcx.param_env(impl_ty.def_id);
2633    let container_id = impl_ty.container_id(tcx);
2634    let mut clauses = param_env.caller_bounds().to_vec();
2635
2636    // for RPITITs, we should install predicates that allow us to project all
2637    // of the RPITITs associated with the same body. This is because checking
2638    // the item bounds of RPITITs often involves nested RPITITs having to prove
2639    // bounds about themselves.
2640    let impl_tys_to_install = match impl_ty.kind {
2641        ty::AssocKind::Type {
2642            data:
2643                ty::AssocTypeData::Rpitit(
2644                    ty::ImplTraitInTraitData::Impl { fn_def_id }
2645                    | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2646                ),
2647        } => tcx
2648            .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2649            .iter()
2650            .map(|def_id| tcx.associated_item(*def_id))
2651            .collect(),
2652        _ => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [impl_ty]))vec![impl_ty],
2653    };
2654
2655    for impl_ty in impl_tys_to_install {
2656        let trait_ty = match impl_ty.container {
2657            ty::AssocContainer::InherentImpl => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
2658            ty::AssocContainer::Trait => impl_ty,
2659            ty::AssocContainer::TraitImpl(Err(_)) => continue,
2660            ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
2661                tcx.associated_item(trait_item_def_id)
2662            }
2663        };
2664
2665        let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind<'tcx>; 8]> =
2666            smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2667        // Extend the impl's identity args with late-bound GAT vars
2668        let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2669            .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2670                GenericParamDefKind::Type { .. } => {
2671                    let kind = ty::BoundTyKind::Param(param.def_id);
2672                    let bound_var = ty::BoundVariableKind::Ty(kind);
2673                    bound_vars.push(bound_var);
2674                    Ty::new_bound(
2675                        tcx,
2676                        ty::INNERMOST,
2677                        ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2678                    )
2679                    .into()
2680                }
2681                GenericParamDefKind::Lifetime => {
2682                    let kind = ty::BoundRegionKind::Named(param.def_id);
2683                    let bound_var = ty::BoundVariableKind::Region(kind);
2684                    bound_vars.push(bound_var);
2685                    ty::Region::new_bound(
2686                        tcx,
2687                        ty::INNERMOST,
2688                        ty::BoundRegion {
2689                            var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2690                            kind,
2691                        },
2692                    )
2693                    .into()
2694                }
2695                GenericParamDefKind::Const { .. } => {
2696                    let bound_var = ty::BoundVariableKind::Const;
2697                    bound_vars.push(bound_var);
2698                    ty::Const::new_bound(
2699                        tcx,
2700                        ty::INNERMOST,
2701                        ty::BoundConst::new(ty::BoundVar::from_usize(bound_vars.len() - 1)),
2702                    )
2703                    .into()
2704                }
2705            });
2706        // When checking something like
2707        //
2708        // trait X { type Y: PartialEq<<Self as X>::Y> }
2709        // impl X for T { default type Y = S; }
2710        //
2711        // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
2712        // we want <T as X>::Y to normalize to S. This is valid because we are
2713        // checking the default value specifically here. Add this equality to the
2714        // ParamEnv for normalization specifically.
2715        let normalize_impl_ty =
2716            tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args).skip_norm_wip();
2717        let rebased_args =
2718            normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2719        let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2720
2721        match normalize_impl_ty.kind() {
2722            &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
2723                if def_id == trait_ty.def_id && args == rebased_args =>
2724            {
2725                // Don't include this predicate if the projected type is
2726                // exactly the same as the projection. This can occur in
2727                // (somewhat dubious) code like this:
2728                //
2729                // impl<T> X for T where T: X { type Y = <T as X>::Y; }
2730            }
2731            _ => clauses.push(
2732                ty::Binder::bind_with_vars(
2733                    ty::ProjectionPredicate {
2734                        projection_term: ty::AliasTerm::new_from_def_id(
2735                            tcx,
2736                            trait_ty.def_id,
2737                            rebased_args,
2738                        ),
2739                        term: normalize_impl_ty.into(),
2740                    },
2741                    bound_vars,
2742                )
2743                .upcast(tcx),
2744            ),
2745        };
2746    }
2747
2748    ty::ParamEnv::new(tcx.mk_clauses(&clauses))
2749}
2750
2751/// Manually check here that `async fn foo()` wasn't matched against `fn foo()`,
2752/// and extract a better error if so.
2753fn try_report_async_mismatch<'tcx>(
2754    tcx: TyCtxt<'tcx>,
2755    infcx: &InferCtxt<'tcx>,
2756    errors: &[FulfillmentError<'tcx>],
2757    trait_m: ty::AssocItem,
2758    impl_m: ty::AssocItem,
2759    impl_sig: ty::FnSig<'tcx>,
2760) -> Result<(), ErrorGuaranteed> {
2761    if !tcx.asyncness(trait_m.def_id).is_async() {
2762        return Ok(());
2763    }
2764
2765    let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id: async_future_def_id }, .. }) =
2766        *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2767    else {
2768        ::rustc_middle::util::bug::bug_fmt(format_args!("expected `async fn` to return an RPITIT"));bug!("expected `async fn` to return an RPITIT");
2769    };
2770
2771    for error in errors {
2772        if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2773            && def_id == async_future_def_id
2774            && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2775            && let Some(proj) = proj.no_bound_vars()
2776            && infcx.can_eq(
2777                error.root_obligation.param_env,
2778                proj.term.expect_type(),
2779                impl_sig.output(),
2780            )
2781        {
2782            // FIXME: We should suggest making the fn `async`, but extracting
2783            // the right span is a bit difficult.
2784            return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2785                span: tcx.def_span(impl_m.def_id),
2786                method_name: tcx.item_ident(impl_m.def_id),
2787                trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
2788            }));
2789        }
2790    }
2791
2792    Ok(())
2793}