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, Ty, TyCtxt,
18    TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypeVisitor,
19    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_clause_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_clause_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 clauses contained
169/// in the `trait_m` generics to the placeholder form.
170///
171/// Finally we register each of these clauses 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_clause_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_clauses = tcx.clauses_of(impl_m.def_id);
            let trait_m_clauses = tcx.clauses_of(trait_m.def_id);
            let impl_clauses = tcx.clauses_of(impl_m_clauses.parent.unwrap());
            let mut hybrid_clauses =
                impl_clauses.instantiate_identity(tcx).clauses;
            hybrid_clauses.extend(trait_m_clauses.instantiate_own(tcx,
                        trait_to_impl_args).map(|(clause, _)| clause));
            let is_conditionally_const =
                tcx.is_conditionally_const(impl_m.def_id);
            if is_conditionally_const {
                hybrid_clauses.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_clauses =
                hybrid_clauses.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_clauses));
            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:256",
                                    "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(256u32),
                                    ::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_clauses.instantiate_own_identity();
            for (clause, span) in impl_m_own_bounds {
                let normalize_cause =
                    traits::ObligationCause::misc(span, impl_m_def_id);
                let clause =
                    ocx.normalize(&normalize_cause, param_env, clause);
                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, clause));
            }
            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:332",
                                    "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(332u32),
                                    ::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:345",
                                    "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(345u32),
                                    ::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:357",
                                        "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(357u32),
                                        ::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_clause_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_clauses = tcx.clauses_of(impl_m.def_id);
207    let trait_m_clauses = tcx.clauses_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 clauses 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_clauses = tcx.clauses_of(impl_m_clauses.parent.unwrap());
217    let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
218    hybrid_clauses
219        .extend(trait_m_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(clause, _)| clause));
220
221    let is_conditionally_const = tcx.is_conditionally_const(impl_m.def_id);
222    if is_conditionally_const {
223        // Augment the hybrid param-env with the const conditions
224        // of the impl header and the trait method.
225        hybrid_clauses.extend(
226            tcx.const_conditions(impl_def_id)
227                .instantiate_identity(tcx)
228                .into_iter()
229                .chain(
230                    tcx.const_conditions(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args),
231                )
232                .map(|(trait_ref, _)| {
233                    trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
234                }),
235        );
236    }
237
238    let hybrid_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
239    let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
240    let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_clauses));
241    // NOTE(-Zhigher-ranked-assumptions): The `hybrid_preds`
242    // should be well-formed. However, using them may result in
243    // region errors as we currently don't track placeholder
244    // assumptions.
245    //
246    // We eagerly normalize the where-clauses here while ignoring
247    // region constraints. This means we can then use where-bounds
248    // whose normalization results in placeholder errors further
249    // down without getting any errors.
250    //
251    // This should be sound to do so as the only region errors here
252    // should be due to missing implied bounds.
253    //
254    // cc trait-system-refactor-initiative/issues/166.
255    let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
256    debug!(caller_bounds=?param_env.caller_bounds());
257
258    let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
259    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
260
261    // Create obligations for each clause declared by the impl
262    // definition in the context of the hybrid param-env. This makes
263    // sure that the impl's method's where clauses are not more
264    // restrictive than the trait's method (and the impl itself).
265    let impl_m_own_bounds = impl_m_clauses.instantiate_own_identity();
266    for (clause, span) in impl_m_own_bounds {
267        let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
268        let clause = ocx.normalize(&normalize_cause, param_env, clause);
269
270        let cause = ObligationCause::new(
271            span,
272            impl_m_def_id,
273            ObligationCauseCode::CompareImplItem {
274                impl_item_def_id: impl_m_def_id,
275                trait_item_def_id: trait_m.def_id,
276                kind: impl_m.kind,
277            },
278        );
279        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
280    }
281
282    // If we're within a const implementation, we need to make sure that the method
283    // does not assume stronger `[const]` bounds than the trait definition.
284    //
285    // This registers the `[const]` bounds of the impl method, which we will prove
286    // using the hybrid param-env that we earlier augmented with the const conditions
287    // from the impl header and trait method declaration.
288    if is_conditionally_const {
289        for (const_condition, span) in
290            tcx.const_conditions(impl_m.def_id).instantiate_own_identity()
291        {
292            let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
293            let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
294
295            let cause = ObligationCause::new(
296                span,
297                impl_m_def_id,
298                ObligationCauseCode::CompareImplItem {
299                    impl_item_def_id: impl_m_def_id,
300                    trait_item_def_id: trait_m.def_id,
301                    kind: impl_m.kind,
302                },
303            );
304            ocx.register_obligation(traits::Obligation::new(
305                tcx,
306                cause,
307                param_env,
308                const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
309            ));
310        }
311    }
312
313    // We now need to check that the signature of the impl method is
314    // compatible with that of the trait method. We do this by
315    // checking that `impl_fty <: trait_fty`.
316    //
317    // FIXME: We manually instantiate the trait method here as we need
318    // to manually compute its implied bounds. Otherwise this could just
319    // be `ocx.sub(impl_sig, trait_sig)`.
320
321    let mut wf_tys = FxIndexSet::default();
322
323    let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars(
324        impl_m_span,
325        BoundRegionConversionTime::HigherRankedType,
326        tcx.fn_sig(impl_m.def_id).instantiate_identity().skip_norm_wip(),
327    );
328
329    let norm_cause = ObligationCause::misc(impl_m_span, impl_m_def_id);
330    let impl_sig =
331        ocx.normalize(&norm_cause, param_env, Unnormalized::new_wip(unnormalized_impl_sig));
332    debug!(?impl_sig);
333
334    let trait_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args).skip_norm_wip();
335    let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
336
337    // Next, add all inputs and output as well-formed tys. Importantly,
338    // we have to do this before normalization, since the normalized ty may
339    // not contain the input parameters. See issue #87748.
340    wf_tys.extend(trait_sig.inputs_and_output.iter());
341    let trait_sig = ocx.normalize(&norm_cause, param_env, Unnormalized::new_wip(trait_sig));
342    // We also have to add the normalized trait signature
343    // as we don't normalize during implied bounds computation.
344    wf_tys.extend(trait_sig.inputs_and_output.iter());
345    debug!(?trait_sig);
346
347    // FIXME: We'd want to keep more accurate spans than "the method signature" when
348    // processing the comparison between the trait and impl fn, but we sadly lose them
349    // and point at the whole signature when a trait bound or specific input or output
350    // type would be more appropriate. In other places we have a `Vec<Span>`
351    // corresponding to their `Vec<Predicate>`, but we don't have that here.
352    // Fixing this would improve the output of test `issue-83765.rs`.
353    // There's the same issue in compare_eii code.
354    let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
355
356    if let Err(terr) = result {
357        debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
358
359        let emitted = report_trait_method_mismatch(
360            infcx,
361            cause,
362            param_env,
363            terr,
364            (trait_m, trait_sig),
365            (impl_m, impl_sig),
366            impl_trait_ref,
367        );
368        return Err(emitted);
369    }
370
371    if !(impl_sig, trait_sig).references_error() {
372        for ty in unnormalized_impl_sig.inputs_and_output {
373            ocx.register_obligation(traits::Obligation::new(
374                infcx.tcx,
375                cause.clone(),
376                param_env,
377                ty::ClauseKind::WellFormed(ty.into()),
378            ));
379        }
380    }
381
382    // Check that all obligations are satisfied by the implementation's
383    // version.
384    let errors = ocx.evaluate_obligations_error_on_ambiguity();
385    if !errors.is_empty() {
386        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
387        return Err(reported);
388    }
389
390    // Finally, resolve all regions. This catches wily misuses of
391    // lifetime parameters.
392    let errors = infcx.resolve_regions(impl_m_def_id, param_env, wf_tys);
393    if !errors.is_empty() {
394        return Err(infcx
395            .tainted_by_errors()
396            .unwrap_or_else(|| infcx.err_ctxt().report_region_errors(impl_m_def_id, &errors)));
397    }
398
399    Ok(())
400}
401
402struct RemapLateParam<'tcx> {
403    tcx: TyCtxt<'tcx>,
404    mapping: FxIndexMap<ty::LateParamRegionKind, ty::LateParamRegionKind>,
405}
406
407impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateParam<'tcx> {
408    fn cx(&self) -> TyCtxt<'tcx> {
409        self.tcx
410    }
411
412    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
413        if let ty::ReLateParam(fr) = r.kind() {
414            ty::Region::new_late_param(
415                self.tcx,
416                fr.scope,
417                self.mapping.get(&fr.kind).copied().unwrap_or(fr.kind),
418            )
419        } else {
420            r
421        }
422    }
423}
424
425/// Given a method def-id in an impl, compare the method signature of the impl
426/// against the trait that it's implementing. In doing so, infer the hidden types
427/// that this method's signature provides to satisfy each return-position `impl Trait`
428/// in the trait signature.
429///
430/// The method is also responsible for making sure that the hidden types for each
431/// RPITIT actually satisfy the bounds of the `impl Trait`, i.e. that if we infer
432/// `impl Trait = Foo`, that `Foo: Trait` holds.
433///
434/// For example, given the sample code:
435///
436/// ```
437/// use std::ops::Deref;
438///
439/// trait Foo {
440///     fn bar() -> impl Deref<Target = impl Sized>;
441///     //          ^- RPITIT #1        ^- RPITIT #2
442/// }
443///
444/// impl Foo for () {
445///     fn bar() -> Box<String> { Box::new(String::new()) }
446/// }
447/// ```
448///
449/// The hidden types for the RPITITs in `bar` would be inferred to:
450///     * `impl Deref` (RPITIT #1) = `Box<String>`
451///     * `impl Sized` (RPITIT #2) = `String`
452///
453/// The relationship between these two types is straightforward in this case, but
454/// may be more tenuously connected via other `impl`s and normalization rules for
455/// cases of more complicated nested RPITITs.
456x;#[instrument(skip(tcx), level = "debug", ret)]
457pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
458    tcx: TyCtxt<'tcx>,
459    impl_m_def_id: LocalDefId,
460) -> Result<&'tcx DefIdMap<ty::EarlyBinder<'tcx, Ty<'tcx>>>, ErrorGuaranteed> {
461    let impl_m = tcx.associated_item(impl_m_def_id.to_def_id());
462    let trait_m = tcx.associated_item(impl_m.expect_trait_impl()?);
463    let impl_trait_ref = tcx
464        .impl_trait_ref(tcx.parent(impl_m_def_id.to_def_id()))
465        .instantiate_identity()
466        .skip_norm_wip();
467    // First, check a few of the same things as `compare_impl_method`,
468    // just so we don't ICE during instantiation later.
469    check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?;
470
471    let impl_m_hir_id = tcx.local_def_id_to_hir_id(impl_m_def_id);
472    let return_span = tcx.hir_fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
473    let cause = ObligationCause::new(
474        return_span,
475        impl_m_def_id,
476        ObligationCauseCode::CompareImplItem {
477            impl_item_def_id: impl_m_def_id,
478            trait_item_def_id: trait_m.def_id,
479            kind: impl_m.kind,
480        },
481    );
482
483    // Create mapping from trait to impl (i.e. impl trait header + impl method identity args).
484    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
485        tcx,
486        impl_m.container_id(tcx),
487        impl_trait_ref.args,
488    );
489
490    let hybrid_clauses = tcx
491        .clauses_of(impl_m.container_id(tcx))
492        .instantiate_identity(tcx)
493        .into_iter()
494        .chain(tcx.clauses_of(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args))
495        .map(|(clause, _)| clause.skip_norm_wip());
496    let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_clauses));
497    let param_env = traits::normalize_param_env_or_error(
498        tcx,
499        param_env,
500        ObligationCause::misc(tcx.def_span(impl_m_def_id), impl_m_def_id),
501    );
502
503    let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
504    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
505
506    // Check that the where clauses of the impl are satisfied by the hybrid param env.
507    // You might ask -- what does this have to do with RPITIT inference? Nothing.
508    // We check these because if the where clauses of the signatures do not match
509    // up, then we don't want to give spurious other errors that point at the RPITITs.
510    // They're not necessary to check, though, because we already check them in
511    // `compare_method_clause_entailment`.
512    let impl_m_own_bounds = tcx.clauses_of(impl_m_def_id).instantiate_own_identity();
513    for (clause, span) in impl_m_own_bounds {
514        let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
515        let clause = ocx.normalize(&normalize_cause, param_env, clause);
516
517        let cause = ObligationCause::new(
518            span,
519            impl_m_def_id,
520            ObligationCauseCode::CompareImplItem {
521                impl_item_def_id: impl_m_def_id,
522                trait_item_def_id: trait_m.def_id,
523                kind: impl_m.kind,
524            },
525        );
526        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
527    }
528
529    // Normalize the impl signature with fresh variables for lifetime inference.
530    let misc_cause = ObligationCause::misc(return_span, impl_m_def_id);
531    let impl_sig = ocx.normalize(
532        &misc_cause,
533        param_env,
534        Unnormalized::new_wip(infcx.instantiate_binder_with_fresh_vars(
535            return_span,
536            BoundRegionConversionTime::HigherRankedType,
537            tcx.fn_sig(impl_m.def_id).instantiate_identity().skip_norm_wip(),
538        )),
539    );
540    impl_sig.error_reported()?;
541    let impl_return_ty = impl_sig.output();
542
543    // Normalize the trait signature with liberated bound vars, passing it through
544    // the ImplTraitInTraitCollector, which gathers all of the RPITITs and replaces
545    // them with inference variables.
546    // We will use these inference variables to collect the hidden types of RPITITs.
547    let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_def_id);
548    let unnormalized_trait_sig = tcx
549        .liberate_late_bound_regions(
550            impl_m.def_id,
551            tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args).skip_norm_wip(),
552        )
553        .fold_with(&mut collector);
554
555    let trait_sig =
556        ocx.normalize(&misc_cause, param_env, Unnormalized::new_wip(unnormalized_trait_sig));
557    trait_sig.error_reported()?;
558    let trait_return_ty = trait_sig.output();
559
560    // RPITITs are allowed to use the implied predicates of the method that
561    // defines them. This is because we want code like:
562    // ```
563    // trait Foo {
564    //     fn test<'a, T>(_: &'a T) -> impl Sized;
565    // }
566    // impl Foo for () {
567    //     fn test<'a, T>(x: &'a T) -> &'a T { x }
568    // }
569    // ```
570    // .. to compile. However, since we use both the normalized and unnormalized
571    // inputs and outputs from the instantiated trait signature, we will end up
572    // seeing the hidden type of an RPIT in the signature itself. Naively, this
573    // means that we will use the hidden type to imply the hidden type's own
574    // well-formedness.
575    //
576    // To avoid this, we replace the infer vars used for hidden type inference
577    // with placeholders, which imply nothing about outlives bounds, and then
578    // prove below that the hidden types are well formed.
579    let universe = infcx.create_next_universe();
580    let mut idx = ty::BoundVar::ZERO;
581    let mapping: FxIndexMap<_, _> = collector
582        .types
583        .iter()
584        .map(|(_, &(ty, _))| {
585            assert!(
586                infcx.resolve_vars_if_possible(ty) == ty && ty.is_ty_var(),
587                "{ty:?} should not have been constrained via normalization",
588                ty = infcx.resolve_vars_if_possible(ty)
589            );
590            idx += 1;
591            (
592                ty,
593                Ty::new_placeholder(
594                    tcx,
595                    ty::PlaceholderType::new(
596                        universe,
597                        ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
598                    ),
599                ),
600            )
601        })
602        .collect();
603    let mut type_mapper = BottomUpFolder {
604        tcx,
605        ty_op: |ty| *mapping.get(&ty).unwrap_or(&ty),
606        lt_op: |lt| lt,
607        ct_op: |ct| ct,
608    };
609    let wf_tys = FxIndexSet::from_iter(
610        unnormalized_trait_sig
611            .inputs_and_output
612            .iter()
613            .chain(trait_sig.inputs_and_output.iter())
614            .map(|ty| ty.fold_with(&mut type_mapper)),
615    );
616
617    match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
618        Ok(()) => {}
619        Err(terr) => {
620            let mut diag = struct_span_code_err!(
621                tcx.dcx(),
622                cause.span,
623                E0053,
624                "method `{}` has an incompatible return type for trait",
625                trait_m.name()
626            );
627            infcx.err_ctxt().note_type_err(
628                &mut diag,
629                &cause,
630                tcx.hir_get_if_local(impl_m.def_id)
631                    .and_then(|node| node.fn_decl())
632                    .map(|decl| (decl.output.span(), Cow::from("return type in trait"), false)),
633                Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
634                    expected: trait_return_ty.into(),
635                    found: impl_return_ty.into(),
636                }))),
637                terr,
638                false,
639                None,
640            );
641            return Err(diag.emit());
642        }
643    }
644
645    debug!(?trait_sig, ?impl_sig, "equating function signatures");
646
647    // Unify the whole function signature. We need to do this to fully infer
648    // the lifetimes of the return type, but do this after unifying just the
649    // return types, since we want to avoid duplicating errors from
650    // `compare_method_clause_entailment`.
651    match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
652        Ok(()) => {}
653        Err(terr) => {
654            // This function gets called during `compare_method_clause_entailment` when normalizing a
655            // signature that contains RPITIT. When the method signatures don't match, we have to
656            // emit an error now because `compare_method_clause_entailment` will not report the error
657            // when normalization fails.
658            let emitted = report_trait_method_mismatch(
659                infcx,
660                cause,
661                param_env,
662                terr,
663                (trait_m, trait_sig),
664                (impl_m, impl_sig),
665                impl_trait_ref,
666            );
667            return Err(emitted);
668        }
669    }
670
671    if !unnormalized_trait_sig.output().references_error() && collector.types.is_empty() {
672        tcx.dcx().delayed_bug(
673            "expect >0 RPITITs in call to `collect_return_position_impl_trait_in_trait_tys`",
674        );
675    }
676
677    // FIXME: This has the same issue as #108544, but since this isn't breaking
678    // existing code, I'm not particularly inclined to do the same hack as above
679    // where we process wf obligations manually. This can be fixed in a forward-
680    // compatible way later.
681    let collected_types = collector.types;
682    for (_, &(ty, _)) in &collected_types {
683        ocx.register_obligation(traits::Obligation::new(
684            tcx,
685            misc_cause.clone(),
686            param_env,
687            ty::ClauseKind::WellFormed(ty.into()),
688        ));
689    }
690
691    // Check that all obligations are satisfied by the implementation's
692    // RPITs.
693    let errors = ocx.evaluate_obligations_error_on_ambiguity();
694    if !errors.is_empty() {
695        if let Err(guar) = try_report_async_mismatch(tcx, infcx, &errors, trait_m, impl_m, impl_sig)
696        {
697            return Err(guar);
698        }
699
700        let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
701        return Err(guar);
702    }
703
704    // Finally, resolve all regions. This catches wily misuses of
705    // lifetime parameters.
706    ocx.resolve_regions_and_report_errors(impl_m_def_id, param_env, wf_tys)?;
707
708    let mut remapped_types = DefIdMap::default();
709    for (def_id, (ty, args)) in collected_types {
710        match infcx.fully_resolve(ty) {
711            Ok(ty) => {
712                // `ty` contains free regions that we created earlier while liberating the
713                // trait fn signature. However, projection normalization expects `ty` to
714                // contains `def_id`'s early-bound regions.
715                let id_args = GenericArgs::identity_for_item(tcx, def_id);
716                debug!(?id_args, ?args);
717                let map: FxIndexMap<_, _> = std::iter::zip(args, id_args)
718                    .skip(tcx.generics_of(trait_m.def_id).count())
719                    .filter_map(|(a, b)| Some((a.as_region()?, b.as_region()?)))
720                    .collect();
721                debug!(?map);
722
723                // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound
724                // region args that are synthesized during AST lowering. These are args
725                // that are appended to the parent args (trait and trait method). However,
726                // we're trying to infer the uninstantiated type value of the RPITIT inside
727                // the *impl*, so we can later use the impl's method args to normalize
728                // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`).
729                //
730                // Due to the design of RPITITs, during AST lowering, we have no idea that
731                // an impl method corresponds to a trait method with RPITITs in it. Therefore,
732                // we don't have a list of early-bound region args for the RPITIT in the impl.
733                // Since early region parameters are index-based, we can't just rebase these
734                // (trait method) early-bound region args onto the impl, and there's no
735                // guarantee that the indices from the trait args and impl args line up.
736                // So to fix this, we subtract the number of trait args and add the number of
737                // impl args to *renumber* these early-bound regions to their corresponding
738                // indices in the impl's generic parameters list.
739                //
740                // Also, we only need to account for a difference in trait and impl args,
741                // since we previously enforce that the trait method and impl method have the
742                // same generics.
743                let num_trait_args = impl_trait_ref.args.len();
744                let num_impl_args = tcx.generics_of(impl_m.container_id(tcx)).own_params.len();
745                let ty = match ty.try_fold_with(&mut RemapHiddenTyRegions {
746                    tcx,
747                    map,
748                    num_trait_args,
749                    num_impl_args,
750                    def_id,
751                    impl_m_def_id: impl_m.def_id,
752                    ty,
753                    return_span,
754                }) {
755                    Ok(ty) => ty,
756                    Err(guar) => Ty::new_error(tcx, guar),
757                };
758                remapped_types.insert(def_id, ty::EarlyBinder::bind(tcx, ty));
759            }
760            Err(err) => {
761                // This code path is not reached in any tests, but may be
762                // reachable. If this is triggered, it should be converted to
763                // `span_delayed_bug` and the triggering case turned into a
764                // test.
765                tcx.dcx()
766                    .span_bug(return_span, format!("could not fully resolve: {ty} => {err:?}"));
767            }
768        }
769    }
770
771    // We may not collect all RPITITs that we see in the HIR for a trait signature
772    // because an RPITIT was located within a missing item. Like if we have a sig
773    // returning `-> Missing<impl Sized>`, that gets converted to `-> {type error}`,
774    // and when walking through the signature we end up never collecting the def id
775    // of the `impl Sized`. Insert that here, so we don't ICE later.
776    for assoc_item in tcx.associated_types_for_impl_traits_in_associated_fn(trait_m.def_id) {
777        if !remapped_types.contains_key(assoc_item) {
778            remapped_types.insert(
779                *assoc_item,
780                ty::EarlyBinder::bind(
781                    tcx,
782                    Ty::new_error_with_message(
783                        tcx,
784                        return_span,
785                        "missing synthetic item for RPITIT",
786                    ),
787                ),
788            );
789        }
790    }
791
792    Ok(&*tcx.arena.alloc(remapped_types))
793}
794
795struct ImplTraitInTraitCollector<'a, 'tcx, E> {
796    ocx: &'a ObligationCtxt<'a, 'tcx, E>,
797    types: FxIndexMap<DefId, (Ty<'tcx>, ty::GenericArgsRef<'tcx>)>,
798    span: Span,
799    param_env: ty::ParamEnv<'tcx>,
800    impl_m_id: LocalDefId,
801}
802
803impl<'a, 'tcx, E> ImplTraitInTraitCollector<'a, 'tcx, E>
804where
805    E: 'tcx,
806{
807    fn new(
808        ocx: &'a ObligationCtxt<'a, 'tcx, E>,
809        span: Span,
810        param_env: ty::ParamEnv<'tcx>,
811        impl_m_id: LocalDefId,
812    ) -> Self {
813        ImplTraitInTraitCollector { ocx, types: FxIndexMap::default(), span, param_env, impl_m_id }
814    }
815}
816
817impl<'tcx, E> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx, E>
818where
819    E: 'tcx,
820{
821    fn cx(&self) -> TyCtxt<'tcx> {
822        self.ocx.infcx.tcx
823    }
824
825    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
826        if let &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args: proj_args, .. }) =
827            ty.kind()
828            && self.cx().is_impl_trait_in_trait(def_id)
829        {
830            if let Some((ty, _)) = self.types.get(&def_id) {
831                return *ty;
832            }
833            //FIXME(RPITIT): Deny nested RPITIT in args too
834            if proj_args.has_escaping_bound_vars() {
835                ::rustc_middle::util::bug::bug_fmt(format_args!("FIXME(RPITIT): error here"));bug!("FIXME(RPITIT): error here");
836            }
837            // Replace with infer var
838            let infer_ty = self.ocx.infcx.next_ty_var(self.span);
839            self.types.insert(def_id, (infer_ty, proj_args));
840            // Recurse into bounds
841            for (pred, pred_span) in self
842                .cx()
843                .explicit_item_bounds(def_id)
844                .iter_instantiated_copied(self.cx(), proj_args)
845                .map(Unnormalized::skip_norm_wip)
846            {
847                let pred = pred.fold_with(self);
848                let pred = self.ocx.normalize(
849                    &ObligationCause::misc(self.span, self.impl_m_id),
850                    self.param_env,
851                    Unnormalized::new_wip(pred),
852                );
853
854                self.ocx.register_obligation(traits::Obligation::new(
855                    self.cx(),
856                    ObligationCause::new(
857                        self.span,
858                        self.impl_m_id,
859                        ObligationCauseCode::WhereClause(def_id, pred_span),
860                    ),
861                    self.param_env,
862                    pred,
863                ));
864            }
865            infer_ty
866        } else {
867            ty.super_fold_with(self)
868        }
869    }
870}
871
872struct RemapHiddenTyRegions<'tcx> {
873    tcx: TyCtxt<'tcx>,
874    /// Map from early/late params of the impl to identity regions of the RPITIT (GAT)
875    /// in the trait.
876    map: FxIndexMap<ty::Region<'tcx>, ty::Region<'tcx>>,
877    num_trait_args: usize,
878    num_impl_args: usize,
879    /// Def id of the RPITIT (GAT) in the *trait*.
880    def_id: DefId,
881    /// Def id of the impl method which owns the opaque hidden type we're remapping.
882    impl_m_def_id: DefId,
883    /// The hidden type we're remapping. Useful for diagnostics.
884    ty: Ty<'tcx>,
885    /// Span of the return type. Useful for diagnostics.
886    return_span: Span,
887}
888
889impl<'tcx> ty::FallibleTypeFolder<TyCtxt<'tcx>> for RemapHiddenTyRegions<'tcx> {
890    type Error = ErrorGuaranteed;
891
892    fn cx(&self) -> TyCtxt<'tcx> {
893        self.tcx
894    }
895
896    fn try_fold_region(
897        &mut self,
898        region: ty::Region<'tcx>,
899    ) -> Result<ty::Region<'tcx>, Self::Error> {
900        match region.kind() {
901            // Never remap bound regions or `'static`
902            ty::ReBound(..) | ty::ReStatic | ty::ReError(_) => return Ok(region),
903            // We always remap liberated late-bound regions from the function.
904            ty::ReLateParam(_) => {}
905            // Remap early-bound regions as long as they don't come from the `impl` itself,
906            // in which case we don't really need to renumber them.
907            ty::ReEarlyParam(ebr) => {
908                if ebr.index as usize >= self.num_impl_args {
909                    // Remap
910                } else {
911                    return Ok(region);
912                }
913            }
914            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!(
915                "should not have leaked vars or placeholders into hidden type of RPITIT"
916            ),
917        }
918
919        let e = if let Some(id_region) = self.map.get(&region) {
920            if let ty::ReEarlyParam(e) = id_region.kind() {
921                e
922            } else {
923                ::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!(
924                    "expected to map region {region} to early-bound identity region, but got {id_region}"
925                );
926            }
927        } else {
928            let guar = match region.opt_param_def_id(self.tcx, self.impl_m_def_id) {
929                Some(def_id) => {
930                    let return_span = if let &ty::Alias(
931                        _,
932                        ty::AliasTy { kind: ty::Opaque { def_id: opaque_ty_def_id }, .. },
933                    ) = self.ty.kind()
934                    {
935                        self.tcx.def_span(opaque_ty_def_id)
936                    } else {
937                        self.return_span
938                    };
939                    self.tcx
940                        .dcx()
941                        .struct_span_err(
942                            return_span,
943                            "return type captures more lifetimes than trait definition",
944                        )
945                        .with_span_label(self.tcx.def_span(def_id), "this lifetime was captured")
946                        .with_span_note(
947                            self.tcx.def_span(self.def_id),
948                            "hidden type must only reference lifetimes captured by this impl trait",
949                        )
950                        .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))
951                        .emit()
952                }
953                None => {
954                    // This code path is not reached in any tests, but may be
955                    // reachable. If this is triggered, it should be converted
956                    // to `delayed_bug` and the triggering case turned into a
957                    // test.
958                    self.tcx.dcx().bug("should've been able to remap region");
959                }
960            };
961            return Err(guar);
962        };
963
964        Ok(ty::Region::new_early_param(
965            self.tcx,
966            ty::EarlyParamRegion {
967                name: e.name,
968                index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32,
969            },
970        ))
971    }
972}
973
974/// Gets the string for an explicit self declaration, e.g. "self", "&self",
975/// etc.
976fn get_self_string<'tcx, P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> String
977where
978    P: Fn(Ty<'tcx>) -> bool,
979{
980    if is_self_ty(self_arg_ty) {
981        "self".to_owned()
982    } else if let ty::Ref(_, ty, mutbl) = self_arg_ty.kind()
983        && is_self_ty(*ty)
984    {
985        match mutbl {
986            hir::Mutability::Not => "&self".to_owned(),
987            hir::Mutability::Mut => "&mut self".to_owned(),
988        }
989    } else {
990        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("self: {0}", self_arg_ty))
    })format!("self: {self_arg_ty}")
991    }
992}
993
994fn report_trait_method_mismatch<'tcx>(
995    infcx: &InferCtxt<'tcx>,
996    mut cause: ObligationCause<'tcx>,
997    param_env: ty::ParamEnv<'tcx>,
998    terr: TypeError<'tcx>,
999    (trait_m, trait_sig): (ty::AssocItem, ty::FnSig<'tcx>),
1000    (impl_m, impl_sig): (ty::AssocItem, ty::FnSig<'tcx>),
1001    impl_trait_ref: ty::TraitRef<'tcx>,
1002) -> ErrorGuaranteed {
1003    let tcx = infcx.tcx;
1004    let (impl_err_span, trait_err_span) =
1005        extract_spans_for_error_reporting(infcx, terr, &cause, impl_m, trait_m);
1006
1007    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!(
1008        tcx.dcx(),
1009        impl_err_span,
1010        E0053,
1011        "method `{}` has an incompatible type for trait",
1012        trait_m.name()
1013    );
1014    match &terr {
1015        TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
1016            if trait_m.is_method() =>
1017        {
1018            let ty = trait_sig.inputs()[0];
1019            let sugg = get_self_string(ty, |ty| ty == impl_trait_ref.self_ty());
1020
1021            // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
1022            // span points only at the type `Box<Self`>, but we want to cover the whole
1023            // argument pattern and type.
1024            let (sig, body) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1025            let span = tcx
1026                .hir_body_param_idents(body)
1027                .zip(sig.decl.inputs.iter())
1028                .map(|(param_ident, ty)| {
1029                    if let Some(param_ident) = param_ident {
1030                        param_ident.span.to(ty.span)
1031                    } else {
1032                        ty.span
1033                    }
1034                })
1035                .next()
1036                .unwrap_or(impl_err_span);
1037
1038            diag.span_suggestion_verbose(
1039                span,
1040                "change the self-receiver type to match the trait",
1041                sugg,
1042                Applicability::MachineApplicable,
1043            );
1044        }
1045        TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
1046            if trait_sig.inputs().len() == *i {
1047                // Suggestion to change output type. We do not suggest in `async` functions
1048                // to avoid complex logic or incorrect output.
1049                if let ImplItemKind::Fn(sig, _) =
1050                    &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).kind
1051                    && !sig.header.asyncness.is_async()
1052                {
1053                    let msg = "change the output type to match the trait";
1054                    let ap = Applicability::MachineApplicable;
1055                    match sig.decl.output {
1056                        hir::FnRetTy::DefaultReturn(sp) => {
1057                            let sugg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" -> {0}", trait_sig.output()))
    })format!(" -> {}", trait_sig.output());
1058                            diag.span_suggestion_verbose(sp, msg, sugg, ap);
1059                        }
1060                        hir::FnRetTy::Return(hir_ty) => {
1061                            let sugg = trait_sig.output();
1062                            diag.span_suggestion_verbose(hir_ty.span, msg, sugg, ap);
1063                        }
1064                    };
1065                };
1066            } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
1067                diag.span_suggestion_verbose(
1068                    impl_err_span,
1069                    "change the parameter type to match the trait",
1070                    trait_ty,
1071                    Applicability::MachineApplicable,
1072                );
1073            }
1074        }
1075        _ => {}
1076    }
1077
1078    cause.span = impl_err_span;
1079    infcx.err_ctxt().note_type_err(
1080        &mut diag,
1081        &cause,
1082        trait_err_span.map(|sp| (sp, Cow::from("type in trait"), false)),
1083        Some(param_env.and(infer::ValuePairs::PolySigs(ExpectedFound {
1084            expected: ty::Binder::dummy(trait_sig),
1085            found: ty::Binder::dummy(impl_sig),
1086        }))),
1087        terr,
1088        false,
1089        None,
1090    );
1091
1092    diag.emit()
1093}
1094
1095fn check_region_bounds_on_impl_item<'tcx>(
1096    tcx: TyCtxt<'tcx>,
1097    impl_m: ty::AssocItem,
1098    trait_m: ty::AssocItem,
1099    delay: bool,
1100) -> Result<(), ErrorGuaranteed> {
1101    let impl_generics = tcx.generics_of(impl_m.def_id);
1102    let impl_params = impl_generics.own_counts().lifetimes;
1103
1104    let trait_generics = tcx.generics_of(trait_m.def_id);
1105    let trait_params = trait_generics.own_counts().lifetimes;
1106
1107    let Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span }) =
1108        check_number_of_early_bound_regions(
1109            tcx,
1110            impl_m.def_id.expect_local(),
1111            trait_m.def_id,
1112            impl_generics,
1113            impl_params,
1114            trait_generics,
1115            trait_params,
1116        )
1117    else {
1118        return Ok(());
1119    };
1120
1121    if !delay && let Some(guar) = check_region_late_boundedness(tcx, impl_m, trait_m) {
1122        return Err(guar);
1123    }
1124
1125    let reported = tcx
1126        .dcx()
1127        .create_err(LifetimesOrBoundsMismatchOnTrait {
1128            span,
1129            item_kind: impl_m.descr(),
1130            ident: impl_m.ident(tcx),
1131            generics_span,
1132            bounds_span,
1133            where_span,
1134        })
1135        .emit_unless_delay(delay);
1136
1137    Err(reported)
1138}
1139
1140pub(super) struct CheckNumberOfEarlyBoundRegionsError {
1141    pub(super) span: Span,
1142    pub(super) generics_span: Span,
1143    pub(super) bounds_span: Vec<Span>,
1144    pub(super) where_span: Option<Span>,
1145}
1146
1147pub(super) fn check_number_of_early_bound_regions<'tcx>(
1148    tcx: TyCtxt<'tcx>,
1149    impl_def_id: LocalDefId,
1150    trait_def_id: DefId,
1151    impl_generics: &Generics,
1152    impl_params: usize,
1153    trait_generics: &Generics,
1154    trait_params: usize,
1155) -> Result<(), CheckNumberOfEarlyBoundRegionsError> {
1156    {
    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:1156",
                        "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(1156u32),
                        ::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);
1157
1158    // Must have same number of early-bound lifetime parameters.
1159    // Unfortunately, if the user screws up the bounds, then this
1160    // will change classification between early and late. E.g.,
1161    // if in trait we have `<'a,'b:'a>`, and in impl we just have
1162    // `<'a,'b>`, then we have 2 early-bound lifetime parameters
1163    // in trait but 0 in the impl. But if we report "expected 2
1164    // but found 0" it's confusing, because it looks like there
1165    // are zero. Since I don't quite know how to phrase things at
1166    // the moment, give a kind of vague error message.
1167    if trait_params == impl_params {
1168        return Ok(());
1169    }
1170
1171    let span = tcx
1172        .hir_get_generics(impl_def_id)
1173        .expect("expected impl item to have generics or else we can't compare them")
1174        .span;
1175
1176    let mut generics_span = tcx.def_span(trait_def_id);
1177    let mut bounds_span = ::alloc::vec::Vec::new()vec![];
1178    let mut where_span = None;
1179
1180    if let Some(trait_node) = tcx.hir_get_if_local(trait_def_id)
1181        && let Some(trait_generics) = trait_node.generics()
1182    {
1183        generics_span = trait_generics.span;
1184        // FIXME: we could potentially look at the impl's bounds to not point at bounds that
1185        // *are* present in the impl.
1186        for p in trait_generics.predicates {
1187            match p.kind {
1188                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1189                    bounds,
1190                    ..
1191                })
1192                | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1193                    bounds,
1194                    ..
1195                }) => {
1196                    for b in *bounds {
1197                        if let hir::GenericBound::Outlives(lt) = b {
1198                            bounds_span.push(lt.ident.span);
1199                        }
1200                    }
1201                }
1202            }
1203        }
1204        if let Some(impl_node) = tcx.hir_get_if_local(impl_def_id.into())
1205            && let Some(impl_generics) = impl_node.generics()
1206        {
1207            let mut impl_bounds = 0;
1208            for p in impl_generics.predicates {
1209                match p.kind {
1210                    hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1211                        bounds,
1212                        ..
1213                    })
1214                    | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1215                        bounds,
1216                        ..
1217                    }) => {
1218                        for b in *bounds {
1219                            if let hir::GenericBound::Outlives(_) = b {
1220                                impl_bounds += 1;
1221                            }
1222                        }
1223                    }
1224                }
1225            }
1226            if impl_bounds == bounds_span.len() {
1227                bounds_span = ::alloc::vec::Vec::new()vec![];
1228            } else if impl_generics.has_where_clause_predicates {
1229                where_span = Some(impl_generics.where_clause_span);
1230            }
1231        }
1232    }
1233
1234    Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span })
1235}
1236
1237#[allow(unused)]
1238enum LateEarlyMismatch<'tcx> {
1239    EarlyInImpl(DefId, DefId, ty::Region<'tcx>),
1240    LateInImpl(DefId, DefId, ty::Region<'tcx>),
1241}
1242
1243fn check_region_late_boundedness<'tcx>(
1244    tcx: TyCtxt<'tcx>,
1245    impl_m: ty::AssocItem,
1246    trait_m: ty::AssocItem,
1247) -> Option<ErrorGuaranteed> {
1248    if !impl_m.is_fn() {
1249        return None;
1250    }
1251
1252    let (infcx, param_env) = tcx
1253        .infer_ctxt()
1254        .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, impl_m.def_id));
1255
1256    let impl_m_args = infcx.fresh_args_for_item(DUMMY_SP, impl_m.def_id);
1257    let impl_m_sig = tcx.fn_sig(impl_m.def_id).instantiate(tcx, impl_m_args).skip_norm_wip();
1258    let impl_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, impl_m_sig);
1259
1260    let trait_m_args = infcx.fresh_args_for_item(DUMMY_SP, trait_m.def_id);
1261    let trait_m_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_args).skip_norm_wip();
1262    let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_m_sig);
1263
1264    let ocx = ObligationCtxt::new(&infcx);
1265
1266    // Equate the signatures so that we can infer whether a late-bound param was present where
1267    // an early-bound param was expected, since we replace the late-bound lifetimes with
1268    // `ReLateParam`, and early-bound lifetimes with infer vars, so the early-bound args will
1269    // resolve to `ReLateParam` if there is a mismatch.
1270    let Ok(()) = ocx.eq(
1271        &ObligationCause::dummy(),
1272        param_env,
1273        ty::Binder::dummy(trait_m_sig),
1274        ty::Binder::dummy(impl_m_sig),
1275    ) else {
1276        return None;
1277    };
1278
1279    let errors = ocx.try_evaluate_obligations();
1280    if !errors.is_empty() {
1281        return None;
1282    }
1283
1284    let mut mismatched = ::alloc::vec::Vec::new()vec![];
1285
1286    let impl_generics = tcx.generics_of(impl_m.def_id);
1287    for (id_arg, arg) in
1288        std::iter::zip(ty::GenericArgs::identity_for_item(tcx, impl_m.def_id), impl_m_args)
1289    {
1290        if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1291            && let ty::ReVar(vid) = r.kind()
1292            && let r = infcx
1293                .inner
1294                .borrow_mut()
1295                .unwrap_region_constraints()
1296                .opportunistic_resolve_var(tcx, vid)
1297            && let ty::ReLateParam(ty::LateParamRegion {
1298                kind: ty::LateParamRegionKind::Named(trait_param_def_id),
1299                ..
1300            }) = r.kind()
1301            && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1302        {
1303            mismatched.push(LateEarlyMismatch::EarlyInImpl(
1304                impl_generics.region_param(ebr, tcx).def_id,
1305                trait_param_def_id,
1306                id_arg.expect_region(),
1307            ));
1308        }
1309    }
1310
1311    let trait_generics = tcx.generics_of(trait_m.def_id);
1312    for (id_arg, arg) in
1313        std::iter::zip(ty::GenericArgs::identity_for_item(tcx, trait_m.def_id), trait_m_args)
1314    {
1315        if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1316            && let ty::ReVar(vid) = r.kind()
1317            && let r = infcx
1318                .inner
1319                .borrow_mut()
1320                .unwrap_region_constraints()
1321                .opportunistic_resolve_var(tcx, vid)
1322            && let ty::ReLateParam(ty::LateParamRegion {
1323                kind: ty::LateParamRegionKind::Named(impl_param_def_id),
1324                ..
1325            }) = r.kind()
1326            && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1327        {
1328            mismatched.push(LateEarlyMismatch::LateInImpl(
1329                impl_param_def_id,
1330                trait_generics.region_param(ebr, tcx).def_id,
1331                id_arg.expect_region(),
1332            ));
1333        }
1334    }
1335
1336    if mismatched.is_empty() {
1337        return None;
1338    }
1339
1340    let spans: Vec<_> = mismatched
1341        .iter()
1342        .map(|param| {
1343            let (LateEarlyMismatch::EarlyInImpl(impl_param_def_id, ..)
1344            | LateEarlyMismatch::LateInImpl(impl_param_def_id, ..)) = *param;
1345            tcx.def_span(impl_param_def_id)
1346        })
1347        .collect();
1348
1349    let mut diag = tcx
1350        .dcx()
1351        .struct_span_err(spans, "lifetime parameters do not match the trait definition")
1352        .with_note("lifetime parameters differ in whether they are early- or late-bound")
1353        .with_code(E0195);
1354    for mismatch in mismatched {
1355        match mismatch {
1356            LateEarlyMismatch::EarlyInImpl(
1357                impl_param_def_id,
1358                trait_param_def_id,
1359                early_bound_region,
1360            ) => {
1361                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![
1362                    tcx.def_span(impl_param_def_id),
1363                    tcx.def_span(trait_param_def_id),
1364                ]);
1365                multispan
1366                    .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1367                multispan
1368                    .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1369                multispan.push_span_label(
1370                    tcx.def_span(impl_param_def_id),
1371                    ::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)),
1372                );
1373                multispan.push_span_label(
1374                    tcx.def_span(trait_param_def_id),
1375                    ::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)),
1376                );
1377                if let Some(span) = find_region_in_clauses(tcx, impl_m.def_id, early_bound_region) {
1378                    multispan.push_span_label(
1379                        span,
1380                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
                tcx.item_name(impl_param_def_id)))
    })format!(
1381                            "this lifetime bound makes `{}` early-bound",
1382                            tcx.item_name(impl_param_def_id)
1383                        ),
1384                    );
1385                }
1386                diag.span_note(
1387                    multispan,
1388                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
                tcx.item_name(impl_param_def_id)))
    })format!(
1389                        "`{}` differs between the trait and impl",
1390                        tcx.item_name(impl_param_def_id)
1391                    ),
1392                );
1393            }
1394            LateEarlyMismatch::LateInImpl(
1395                impl_param_def_id,
1396                trait_param_def_id,
1397                early_bound_region,
1398            ) => {
1399                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![
1400                    tcx.def_span(impl_param_def_id),
1401                    tcx.def_span(trait_param_def_id),
1402                ]);
1403                multispan
1404                    .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1405                multispan
1406                    .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1407                multispan.push_span_label(
1408                    tcx.def_span(impl_param_def_id),
1409                    ::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)),
1410                );
1411                multispan.push_span_label(
1412                    tcx.def_span(trait_param_def_id),
1413                    ::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)),
1414                );
1415                if let Some(span) = find_region_in_clauses(tcx, trait_m.def_id, early_bound_region)
1416                {
1417                    multispan.push_span_label(
1418                        span,
1419                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
                tcx.item_name(trait_param_def_id)))
    })format!(
1420                            "this lifetime bound makes `{}` early-bound",
1421                            tcx.item_name(trait_param_def_id)
1422                        ),
1423                    );
1424                }
1425                diag.span_note(
1426                    multispan,
1427                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
                tcx.item_name(impl_param_def_id)))
    })format!(
1428                        "`{}` differs between the trait and impl",
1429                        tcx.item_name(impl_param_def_id)
1430                    ),
1431                );
1432            }
1433        }
1434    }
1435
1436    Some(diag.emit())
1437}
1438
1439fn find_region_in_clauses<'tcx>(
1440    tcx: TyCtxt<'tcx>,
1441    def_id: DefId,
1442    early_bound_region: ty::Region<'tcx>,
1443) -> Option<Span> {
1444    for (clause, span) in tcx.explicit_clauses_of(def_id).instantiate_identity(tcx) {
1445        if clause.skip_norm_wip().visit_with(&mut FindRegion(early_bound_region)).is_break() {
1446            return Some(span);
1447        }
1448    }
1449
1450    struct FindRegion<'tcx>(ty::Region<'tcx>);
1451    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindRegion<'tcx> {
1452        type Result = ControlFlow<()>;
1453        fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
1454            if r == self.0 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
1455        }
1456    }
1457
1458    None
1459}
1460
1461#[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(1461u32),
                                    ::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))]
1462fn extract_spans_for_error_reporting<'tcx>(
1463    infcx: &infer::InferCtxt<'tcx>,
1464    terr: TypeError<'_>,
1465    cause: &ObligationCause<'tcx>,
1466    impl_m: ty::AssocItem,
1467    trait_m: ty::AssocItem,
1468) -> (Span, Option<Span>) {
1469    let tcx = infcx.tcx;
1470    let mut impl_args = {
1471        let (sig, _) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1472        sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1473    };
1474
1475    let trait_args = trait_m.def_id.as_local().map(|def_id| {
1476        let (sig, _) = tcx.hir_expect_trait_item(def_id).expect_fn();
1477        sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1478    });
1479
1480    match terr {
1481        TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1482            (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1483        }
1484        _ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
1485    }
1486}
1487
1488fn compare_self_type<'tcx>(
1489    tcx: TyCtxt<'tcx>,
1490    impl_m: ty::AssocItem,
1491    trait_m: ty::AssocItem,
1492    impl_trait_ref: ty::TraitRef<'tcx>,
1493    delay: bool,
1494) -> Result<(), ErrorGuaranteed> {
1495    // Try to give more informative error messages about self typing
1496    // mismatches. Note that any mismatch will also be detected
1497    // below, where we construct a canonical function type that
1498    // includes the self parameter as a normal parameter. It's just
1499    // that the error messages you get out of this code are a bit more
1500    // inscrutable, particularly for cases where one method has no
1501    // self.
1502
1503    let self_string = |method: ty::AssocItem| {
1504        let untransformed_self_ty = match method.container {
1505            ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1506                impl_trait_ref.self_ty()
1507            }
1508            ty::AssocContainer::Trait => tcx.types.self_param,
1509        };
1510        let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip().input(0);
1511        let (infcx, param_env) = tcx
1512            .infer_ctxt()
1513            .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, method.def_id));
1514        let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1515        let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
1516        get_self_string(self_arg_ty, can_eq_self)
1517    };
1518
1519    match (trait_m.is_method(), impl_m.is_method()) {
1520        (false, false) | (true, true) => {}
1521
1522        (false, true) => {
1523            let self_descr = self_string(impl_m);
1524            let impl_m_span = tcx.def_span(impl_m.def_id);
1525            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!(
1526                tcx.dcx(),
1527                impl_m_span,
1528                E0185,
1529                "method `{}` has a `{}` declaration in the impl, but not in the trait",
1530                trait_m.name(),
1531                self_descr
1532            );
1533            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"));
1534            if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1535                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}`"));
1536            } else {
1537                err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1538            }
1539            return Err(err.emit_unless_delay(delay));
1540        }
1541
1542        (true, false) => {
1543            let self_descr = self_string(trait_m);
1544            let impl_m_span = tcx.def_span(impl_m.def_id);
1545            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!(
1546                tcx.dcx(),
1547                impl_m_span,
1548                E0186,
1549                "method `{}` has a `{}` declaration in the trait, but not in the impl",
1550                trait_m.name(),
1551                self_descr
1552            );
1553            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"));
1554            if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1555                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"));
1556            } else {
1557                err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1558            }
1559
1560            return Err(err.emit_unless_delay(delay));
1561        }
1562    }
1563
1564    Ok(())
1565}
1566
1567/// Checks that the number of generics on a given assoc item in a trait impl is the same
1568/// as the number of generics on the respective assoc item in the trait definition.
1569///
1570/// For example this code emits the errors in the following code:
1571/// ```rust,compile_fail
1572/// trait Trait {
1573///     fn foo();
1574///     type Assoc<T>;
1575/// }
1576///
1577/// impl Trait for () {
1578///     fn foo<T>() {}
1579///     //~^ error
1580///     type Assoc = u32;
1581///     //~^ error
1582/// }
1583/// ```
1584///
1585/// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
1586/// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
1587/// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
1588fn compare_number_of_generics<'tcx>(
1589    tcx: TyCtxt<'tcx>,
1590    impl_: ty::AssocItem,
1591    trait_: ty::AssocItem,
1592    delay: bool,
1593) -> Result<(), ErrorGuaranteed> {
1594    let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1595    let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1596
1597    // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
1598    // in `compare_generic_param_kinds` which will give a nicer error message than something like:
1599    // "expected 1 type parameter, found 0 type parameters"
1600    if (trait_own_counts.types + trait_own_counts.consts)
1601        == (impl_own_counts.types + impl_own_counts.consts)
1602    {
1603        return Ok(());
1604    }
1605
1606    // We never need to emit a separate error for RPITITs, since if an RPITIT
1607    // has mismatched type or const generic arguments, then the method that it's
1608    // inheriting the generics from will also have mismatched arguments, and
1609    // we'll report an error for that instead. Delay a bug for safety, though.
1610    if trait_.is_impl_trait_in_trait() {
1611        // FIXME: no tests trigger this. If you find example code that does
1612        // trigger this, please add it to the test suite.
1613        tcx.dcx()
1614            .bug("errors comparing numbers of generics of trait/impl functions were not emitted");
1615    }
1616
1617    let matchings = [
1618        ("type", trait_own_counts.types, impl_own_counts.types),
1619        ("const", trait_own_counts.consts, impl_own_counts.consts),
1620    ];
1621
1622    let item_kind = impl_.descr();
1623
1624    let mut err_occurred = None;
1625    for (kind, trait_count, impl_count) in matchings {
1626        if impl_count != trait_count {
1627            let arg_spans = |item: &ty::AssocItem, generics: &hir::Generics<'_>| {
1628                let mut spans = generics
1629                    .params
1630                    .iter()
1631                    .filter(|p| match p.kind {
1632                        hir::GenericParamKind::Lifetime {
1633                            kind: hir::LifetimeParamKind::Elided(_),
1634                        } => {
1635                            // A fn can have an arbitrary number of extra elided lifetimes for the
1636                            // same signature.
1637                            !item.is_fn()
1638                        }
1639                        _ => true,
1640                    })
1641                    .map(|p| p.span)
1642                    .collect::<Vec<Span>>();
1643                if spans.is_empty() {
1644                    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]
1645                }
1646                spans
1647            };
1648            let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1649                let trait_item = tcx.hir_expect_trait_item(def_id);
1650                let arg_spans: Vec<Span> = arg_spans(&trait_, trait_item.generics);
1651                let impl_trait_spans: Vec<Span> = trait_item
1652                    .generics
1653                    .params
1654                    .iter()
1655                    .filter_map(|p| match p.kind {
1656                        GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1657                        _ => None,
1658                    })
1659                    .collect();
1660                (Some(arg_spans), impl_trait_spans)
1661            } else {
1662                let trait_span = tcx.hir_span_if_local(trait_.def_id);
1663                (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![])
1664            };
1665
1666            let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
1667            let impl_item_impl_trait_spans: Vec<Span> = impl_item
1668                .generics
1669                .params
1670                .iter()
1671                .filter_map(|p| match p.kind {
1672                    GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1673                    _ => None,
1674                })
1675                .collect();
1676            let spans = arg_spans(&impl_, impl_item.generics);
1677            let span = spans.first().copied();
1678
1679            let mut err = tcx.dcx().struct_span_err(
1680                spans,
1681                ::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!(
1682                    "{} `{}` has {} {kind} parameter{} but its trait \
1683                     declaration has {} {kind} parameter{}",
1684                    item_kind,
1685                    trait_.name(),
1686                    impl_count,
1687                    pluralize!(impl_count),
1688                    trait_count,
1689                    pluralize!(trait_count),
1690                    kind = kind,
1691                ),
1692            );
1693            err.code(E0049);
1694
1695            let msg =
1696                ::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),);
1697            if let Some(spans) = trait_spans {
1698                let mut spans = spans.iter();
1699                if let Some(span) = spans.next() {
1700                    err.span_label(*span, msg);
1701                }
1702                for span in spans {
1703                    err.span_label(*span, "");
1704                }
1705            } else {
1706                err.span_label(tcx.def_span(trait_.def_id), msg);
1707            }
1708
1709            if let Some(span) = span {
1710                err.span_label(
1711                    span,
1712                    ::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),),
1713                );
1714            }
1715
1716            for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1717                err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1718            }
1719
1720            let reported = err.emit_unless_delay(delay);
1721            err_occurred = Some(reported);
1722        }
1723    }
1724
1725    if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1726}
1727
1728fn compare_number_of_method_arguments<'tcx>(
1729    tcx: TyCtxt<'tcx>,
1730    impl_m: ty::AssocItem,
1731    trait_m: ty::AssocItem,
1732    delay: bool,
1733) -> Result<(), ErrorGuaranteed> {
1734    let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1735    let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1736    let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
1737    let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1738
1739    if trait_number_args != impl_number_args {
1740        let trait_span = trait_m
1741            .def_id
1742            .as_local()
1743            .and_then(|def_id| {
1744                let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
1745                let pos = trait_number_args.saturating_sub(1);
1746                trait_m_sig.decl.inputs.get(pos).map(|arg| {
1747                    if pos == 0 {
1748                        arg.span
1749                    } else {
1750                        arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1751                    }
1752                })
1753            })
1754            .or_else(|| tcx.hir_span_if_local(trait_m.def_id));
1755
1756        let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1757        let pos = impl_number_args.saturating_sub(1);
1758        let impl_span = impl_m_sig
1759            .decl
1760            .inputs
1761            .get(pos)
1762            .map(|arg| {
1763                if pos == 0 {
1764                    arg.span
1765                } else {
1766                    arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1767                }
1768            })
1769            .unwrap_or_else(|| tcx.def_span(impl_m.def_id));
1770
1771        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!(
1772            tcx.dcx(),
1773            impl_span,
1774            E0050,
1775            "method `{}` has {} but the declaration in trait `{}` has {}",
1776            trait_m.name(),
1777            potentially_plural_count(impl_number_args, "parameter"),
1778            tcx.def_path_str(trait_m.def_id),
1779            trait_number_args
1780        );
1781
1782        if let Some(trait_span) = trait_span {
1783            err.span_label(
1784                trait_span,
1785                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("trait requires {0}",
                potentially_plural_count(trait_number_args, "parameter")))
    })format!(
1786                    "trait requires {}",
1787                    potentially_plural_count(trait_number_args, "parameter")
1788                ),
1789            );
1790        } else {
1791            err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1792        }
1793
1794        err.span_label(
1795            impl_span,
1796            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found {1}",
                potentially_plural_count(trait_number_args, "parameter"),
                impl_number_args))
    })format!(
1797                "expected {}, found {}",
1798                potentially_plural_count(trait_number_args, "parameter"),
1799                impl_number_args
1800            ),
1801        );
1802
1803        // Only emit verbose suggestions when the trait span isn’t local (e.g., cross-crate).
1804        if !trait_m.def_id.is_local() {
1805            let trait_sig = tcx.fn_sig(trait_m.def_id);
1806            let trait_arg_idents = tcx.fn_arg_idents(trait_m.def_id);
1807            let sm = tcx.sess.source_map();
1808            // Find the span of the space between the parentheses in a method.
1809            // fn foo(...) {}
1810            //        ^^^
1811            let impl_inputs_span = if let (Some(first), Some(last)) =
1812                (impl_m_sig.decl.inputs.first(), impl_m_sig.decl.inputs.last())
1813            {
1814                // We have inputs; construct the span from those.
1815                // fn foo( a: i32, b: u32 ) {}
1816                //        ^^^^^^^^^^^^^^^^
1817                let arg_idents = tcx.fn_arg_idents(impl_m.def_id);
1818                let first_lo = arg_idents
1819                    .get(0)
1820                    .and_then(|id| id.map(|id| id.span.lo()))
1821                    .unwrap_or(first.span.lo());
1822                Some(impl_m_sig.span.with_lo(first_lo).with_hi(last.span.hi()))
1823            } else {
1824                // We have no inputs; construct the span to the left of the last parenthesis
1825                // fn foo( ) {}
1826                //        ^
1827                // FIXME: Keep spans for function parentheses around to make this more robust.
1828                sm.span_to_snippet(impl_m_sig.span).ok().and_then(|s| {
1829                    let right_paren = s.as_bytes().iter().rposition(|&b| b == b')')?;
1830                    let pos = impl_m_sig.span.lo() + BytePos(right_paren as u32);
1831                    Some(impl_m_sig.span.with_lo(pos).with_hi(pos))
1832                })
1833            };
1834            let suggestion = match trait_number_args.cmp(&impl_number_args) {
1835                Ordering::Greater => {
1836                    // Span is right before the end parenthesis:
1837                    // fn foo(a: i32 ) {}
1838                    //              ^
1839                    let trait_inputs = trait_sig.skip_binder().inputs().skip_binder();
1840                    let missing = trait_inputs
1841                        .iter()
1842                        .enumerate()
1843                        .skip(impl_number_args)
1844                        .map(|(idx, ty)| {
1845                            let name = trait_arg_idents
1846                                .get(idx)
1847                                .and_then(|ident| *ident)
1848                                .map(|ident| ident.to_string())
1849                                .unwrap_or_else(|| "_".to_string());
1850                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", name, ty))
    })format!("{name}: {ty}")
1851                        })
1852                        .collect::<Vec<_>>();
1853
1854                    if missing.is_empty() {
1855                        None
1856                    } else {
1857                        impl_inputs_span.map(|s| {
1858                            let span = s.shrink_to_hi();
1859                            let prefix = if impl_number_args == 0 { "" } else { ", " };
1860                            let replacement = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}{0}", missing.join(", "),
                prefix))
    })format!("{prefix}{}", missing.join(", "));
1861                            (
1862                                span,
1863                                ::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!(
1864                                    "add the missing parameter{} from the trait",
1865                                    pluralize!(trait_number_args - impl_number_args)
1866                                ),
1867                                replacement,
1868                            )
1869                        })
1870                    }
1871                }
1872                Ordering::Less => impl_inputs_span.and_then(|full| {
1873                    // Span of the arguments that there are too many of:
1874                    // fn foo(a: i32, b: u32) {}
1875                    //              ^^^^^^^^
1876                    let lo = if trait_number_args == 0 {
1877                        full.lo()
1878                    } else {
1879                        impl_m_sig
1880                            .decl
1881                            .inputs
1882                            .get(trait_number_args - 1)
1883                            .map(|arg| arg.span.hi())?
1884                    };
1885                    let span = full.with_lo(lo);
1886                    Some((
1887                        span,
1888                        ::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!(
1889                            "remove the extra parameter{} to match the trait",
1890                            pluralize!(impl_number_args - trait_number_args)
1891                        ),
1892                        String::new(),
1893                    ))
1894                }),
1895                Ordering::Equal => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1896            };
1897            if let Some((span, msg, replacement)) = suggestion {
1898                err.span_suggestion_verbose(span, msg, replacement, Applicability::MaybeIncorrect);
1899            }
1900        }
1901
1902        return Err(err.emit_unless_delay(delay));
1903    }
1904
1905    Ok(())
1906}
1907
1908fn compare_synthetic_generics<'tcx>(
1909    tcx: TyCtxt<'tcx>,
1910    impl_m: ty::AssocItem,
1911    trait_m: ty::AssocItem,
1912    delay: bool,
1913) -> Result<(), ErrorGuaranteed> {
1914    // FIXME(chrisvittal) Clean up this function, list of FIXME items:
1915    //     1. Better messages for the span labels
1916    //     2. Explanation as to what is going on
1917    // If we get here, we already have the same number of generics, so the zip will
1918    // be okay.
1919    let mut error_found = None;
1920    let impl_m_generics = tcx.generics_of(impl_m.def_id);
1921    let trait_m_generics = tcx.generics_of(trait_m.def_id);
1922    let impl_m_type_params =
1923        impl_m_generics.own_params.iter().filter_map(|param| match param.kind {
1924            GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1925            GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1926        });
1927    let trait_m_type_params =
1928        trait_m_generics.own_params.iter().filter_map(|param| match param.kind {
1929            GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1930            GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1931        });
1932    for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1933        iter::zip(impl_m_type_params, trait_m_type_params)
1934    {
1935        if impl_synthetic != trait_synthetic {
1936            let impl_def_id = impl_def_id.expect_local();
1937            let impl_span = tcx.def_span(impl_def_id);
1938            let trait_span = tcx.def_span(trait_def_id);
1939            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!(
1940                tcx.dcx(),
1941                impl_span,
1942                E0643,
1943                "method `{}` has incompatible signature for trait",
1944                trait_m.name()
1945            );
1946            err.span_label(trait_span, "declaration in trait here");
1947            if impl_synthetic {
1948                // The case where the impl method uses `impl Trait` but the trait method uses
1949                // explicit generics
1950                err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1951                try {
1952                    // try taking the name from the trait impl
1953                    // FIXME: this is obviously suboptimal since the name can already be used
1954                    // as another generic argument
1955                    let new_name = tcx.opt_item_name(trait_def_id)?;
1956                    let trait_m = trait_m.def_id.as_local()?;
1957                    let trait_m = tcx.hir_expect_trait_item(trait_m);
1958
1959                    let impl_m = impl_m.def_id.as_local()?;
1960                    let impl_m = tcx.hir_expect_impl_item(impl_m);
1961
1962                    // in case there are no generics, take the spot between the function name
1963                    // and the opening paren of the argument list
1964                    let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1965                    // in case there are generics, just replace them
1966                    let generics_span = impl_m.generics.span.substitute_dummy(new_generics_span);
1967                    // replace with the generics from the trait
1968                    let new_generics =
1969                        tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1970
1971                    err.multipart_suggestion(
1972                        "try changing the `impl Trait` argument to a generic parameter",
1973                        ::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![
1974                            // replace `impl Trait` with `T`
1975                            (impl_span, new_name.to_string()),
1976                            // replace impl method generics with trait method generics
1977                            // This isn't quite right, as users might have changed the names
1978                            // of the generics, but it works for the common case
1979                            (generics_span, new_generics),
1980                        ],
1981                        Applicability::MaybeIncorrect,
1982                    );
1983                };
1984            } else {
1985                // The case where the trait method uses `impl Trait`, but the impl method uses
1986                // explicit generics.
1987                err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1988                try {
1989                    let impl_m = impl_m.def_id.as_local()?;
1990                    let impl_m = tcx.hir_expect_impl_item(impl_m);
1991                    let (sig, _) = impl_m.expect_fn();
1992                    let input_tys = sig.decl.inputs;
1993
1994                    struct Visitor(hir::def_id::LocalDefId);
1995                    impl<'v> intravisit::Visitor<'v> for Visitor {
1996                        type Result = ControlFlow<Span>;
1997                        fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) -> Self::Result {
1998                            if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
1999                                && let Res::Def(DefKind::TyParam, def_id) = path.res
2000                                && def_id == self.0.to_def_id()
2001                            {
2002                                ControlFlow::Break(ty.span)
2003                            } else {
2004                                intravisit::walk_ty(self, ty)
2005                            }
2006                        }
2007                    }
2008
2009                    let span = input_tys
2010                        .iter()
2011                        .find_map(|ty| Visitor(impl_def_id).visit_ty_unambig(ty).break_value())?;
2012
2013                    let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
2014                    let bounds = bounds.first()?.span().to(bounds.last()?.span());
2015                    let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
2016
2017                    err.multipart_suggestion(
2018                        "try removing the generic parameter and using `impl Trait` instead",
2019                        ::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![
2020                            // delete generic parameters
2021                            (impl_m.generics.span, String::new()),
2022                            // replace param usage with `impl Trait`
2023                            (span, format!("impl {bounds}")),
2024                        ],
2025                        Applicability::MaybeIncorrect,
2026                    );
2027                };
2028            }
2029            error_found = Some(err.emit_unless_delay(delay));
2030        }
2031    }
2032    if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
2033}
2034
2035/// Checks that all parameters in the generics of a given assoc item in a trait impl have
2036/// the same kind as the respective generic parameter in the trait def.
2037///
2038/// For example all 4 errors in the following code are emitted here:
2039/// ```rust,ignore (pseudo-Rust)
2040/// trait Foo {
2041///     fn foo<const N: u8>();
2042///     type Bar<const N: u8>;
2043///     fn baz<const N: u32>();
2044///     type Blah<T>;
2045/// }
2046///
2047/// impl Foo for () {
2048///     fn foo<const N: u64>() {}
2049///     //~^ error
2050///     type Bar<const N: u64> = ();
2051///     //~^ error
2052///     fn baz<T>() {}
2053///     //~^ error
2054///     type Blah<const N: i64> = u32;
2055///     //~^ error
2056/// }
2057/// ```
2058///
2059/// This function does not handle lifetime parameters
2060fn compare_generic_param_kinds<'tcx>(
2061    tcx: TyCtxt<'tcx>,
2062    impl_item: ty::AssocItem,
2063    trait_item: ty::AssocItem,
2064    delay: bool,
2065) -> Result<(), ErrorGuaranteed> {
2066    {
    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());
2067
2068    let ty_const_params_of = |def_id| {
2069        tcx.generics_of(def_id).own_params.iter().filter(|param| {
2070            #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. } =>
        true,
    _ => false,
}matches!(
2071                param.kind,
2072                GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
2073            )
2074        })
2075    };
2076
2077    for (param_impl, param_trait) in
2078        iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
2079    {
2080        use GenericParamDefKind::*;
2081        if match (&param_impl.kind, &param_trait.kind) {
2082            (Const { .. }, Const { .. })
2083                if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
2084            {
2085                true
2086            }
2087            (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
2088            // this is exhaustive so that anyone adding new generic param kinds knows
2089            // to make sure this error is reported for them.
2090            (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
2091            (Lifetime { .. }, _) | (_, Lifetime { .. }) => {
2092                ::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`")
2093            }
2094        } {
2095            let param_impl_span = tcx.def_span(param_impl.def_id);
2096            let param_trait_span = tcx.def_span(param_trait.def_id);
2097
2098            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!(
2099                tcx.dcx(),
2100                param_impl_span,
2101                E0053,
2102                "{} `{}` has an incompatible generic parameter for trait `{}`",
2103                impl_item.descr(),
2104                trait_item.name(),
2105                &tcx.def_path_str(tcx.parent(trait_item.def_id))
2106            );
2107
2108            let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
2109                Const { .. } => {
2110                    ::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!(
2111                        "{} const parameter of type `{}`",
2112                        prefix,
2113                        tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip()
2114                    )
2115                }
2116                Type { .. } => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} type parameter", prefix))
    })format!("{prefix} type parameter"),
2117                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!(
2118                    tcx.def_span(param.def_id),
2119                    "lifetime params are expected to be filtered by `ty_const_params_of`"
2120                ),
2121            };
2122
2123            let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
2124            err.span_label(trait_header_span, "");
2125            err.span_label(param_trait_span, make_param_message("expected", param_trait));
2126
2127            let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
2128            err.span_label(impl_header_span, "");
2129            err.span_label(param_impl_span, make_param_message("found", param_impl));
2130
2131            let reported = err.emit_unless_delay(delay);
2132            return Err(reported);
2133        }
2134    }
2135
2136    Ok(())
2137}
2138
2139fn compare_impl_const<'tcx>(
2140    tcx: TyCtxt<'tcx>,
2141    impl_const_item: ty::AssocItem,
2142    trait_const_item: ty::AssocItem,
2143    impl_trait_ref: ty::TraitRef<'tcx>,
2144) -> Result<(), ErrorGuaranteed> {
2145    compare_type_const(tcx, impl_const_item, trait_const_item)?;
2146    compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
2147    compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
2148    check_region_bounds_on_impl_item(tcx, impl_const_item, trait_const_item, false)?;
2149    compare_const_clause_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
2150}
2151
2152fn compare_type_const<'tcx>(
2153    tcx: TyCtxt<'tcx>,
2154    impl_const_item: ty::AssocItem,
2155    trait_const_item: ty::AssocItem,
2156) -> Result<(), ErrorGuaranteed> {
2157    let impl_is_type_const = tcx.is_type_const(impl_const_item.def_id);
2158    let trait_type_const_span = tcx.type_const_span(trait_const_item.def_id);
2159
2160    if let Some(trait_type_const_span) = trait_type_const_span
2161        && !impl_is_type_const
2162    {
2163        return Err(tcx
2164            .dcx()
2165            .struct_span_err(
2166                tcx.def_span(impl_const_item.def_id),
2167                "implementation of a `type const` must also be marked as `type const`",
2168            )
2169            .with_span_note(
2170                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![
2171                    tcx.def_span(trait_const_item.def_id),
2172                    trait_type_const_span,
2173                ]),
2174                "trait declaration of const is marked as `type const`",
2175            )
2176            .emit());
2177    }
2178    Ok(())
2179}
2180
2181/// The equivalent of [compare_method_clause_entailment], but for associated constants
2182/// instead of associated functions.
2183// FIXME(generic_const_items): If possible extract the common parts of
2184// `compare_{type,const}_clause_entailment`.
2185#[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_clause_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(2185u32),
                                    ::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_clauses = tcx.clauses_of(impl_ct.def_id);
            let trait_ct_clauses = tcx.clauses_of(trait_ct.def_id);
            let impl_clauses =
                tcx.clauses_of(impl_ct_clauses.parent.unwrap());
            let mut hybrid_clauses =
                impl_clauses.instantiate_identity(tcx).clauses;
            hybrid_clauses.extend(trait_ct_clauses.instantiate_own(tcx,
                        trait_to_impl_args).map(|(clause, _)| clause));
            let hybrid_clauses =
                hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
            let param_env =
                ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_clauses));
            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_clauses.instantiate_own_identity();
            for (clause, span) in impl_ct_own_bounds {
                let cause = ObligationCause::misc(span, impl_ct_def_id);
                let clause = ocx.normalize(&cause, param_env, clause);
                let cause =
                    ObligationCause::new(span, impl_ct_def_id, code.clone());
                ocx.register_obligation(traits::Obligation::new(tcx, cause,
                        param_env, clause));
            }
            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:2251",
                                    "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(2251u32),
                                    ::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:2254",
                                    "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(2254u32),
                                    ::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: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("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))]
2186fn compare_const_clause_entailment<'tcx>(
2187    tcx: TyCtxt<'tcx>,
2188    impl_ct: ty::AssocItem,
2189    trait_ct: ty::AssocItem,
2190    impl_trait_ref: ty::TraitRef<'tcx>,
2191) -> Result<(), ErrorGuaranteed> {
2192    let impl_ct_def_id = impl_ct.def_id.expect_local();
2193    let impl_ct_span = tcx.def_span(impl_ct_def_id);
2194
2195    // The below is for the most part highly similar to the procedure
2196    // for methods above. It is simpler in many respects, especially
2197    // because we shouldn't really have to deal with lifetimes or
2198    // predicates. In fact some of this should probably be put into
2199    // shared functions because of DRY violations...
2200    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id).rebase_onto(
2201        tcx,
2202        impl_ct.container_id(tcx),
2203        impl_trait_ref.args,
2204    );
2205
2206    // Create a parameter environment that represents the implementation's
2207    // associated const.
2208    let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
2209
2210    let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
2211    let code = ObligationCauseCode::CompareImplItem {
2212        impl_item_def_id: impl_ct_def_id,
2213        trait_item_def_id: trait_ct.def_id,
2214        kind: impl_ct.kind,
2215    };
2216    let mut cause = ObligationCause::new(impl_ct_span, impl_ct_def_id, code.clone());
2217
2218    let impl_ct_clauses = tcx.clauses_of(impl_ct.def_id);
2219    let trait_ct_clauses = tcx.clauses_of(trait_ct.def_id);
2220
2221    // The clauses declared by the impl definition, the trait and the
2222    // associated const in the trait are assumed.
2223    let impl_clauses = tcx.clauses_of(impl_ct_clauses.parent.unwrap());
2224    let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
2225    hybrid_clauses.extend(
2226        trait_ct_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(clause, _)| clause),
2227    );
2228    let hybrid_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
2229
2230    let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_clauses));
2231    let param_env = traits::normalize_param_env_or_error(
2232        tcx,
2233        param_env,
2234        ObligationCause::misc(impl_ct_span, impl_ct_def_id),
2235    );
2236
2237    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2238    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2239
2240    let impl_ct_own_bounds = impl_ct_clauses.instantiate_own_identity();
2241    for (clause, span) in impl_ct_own_bounds {
2242        let cause = ObligationCause::misc(span, impl_ct_def_id);
2243        let clause = ocx.normalize(&cause, param_env, clause);
2244
2245        let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
2246        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
2247    }
2248
2249    // There is no "body" here, so just pass dummy id.
2250    let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
2251    debug!(?impl_ty);
2252
2253    let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
2254    debug!(?trait_ty);
2255
2256    let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
2257
2258    if let Err(terr) = err {
2259        debug!(?impl_ty, ?trait_ty);
2260
2261        // Locate the Span containing just the type of the offending impl
2262        let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
2263        cause.span = ty.span;
2264
2265        let mut diag = struct_span_code_err!(
2266            tcx.dcx(),
2267            cause.span,
2268            E0326,
2269            "implemented const `{}` has an incompatible type for trait",
2270            trait_ct.name()
2271        );
2272
2273        let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
2274            // Add a label to the Span containing just the type of the const
2275            let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
2276            ty.span
2277        });
2278
2279        infcx.err_ctxt().note_type_err(
2280            &mut diag,
2281            &cause,
2282            trait_c_span.map(|span| (span, Cow::from("type in trait"), false)),
2283            Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2284                expected: trait_ty.into(),
2285                found: impl_ty.into(),
2286            }))),
2287            terr,
2288            false,
2289            None,
2290        );
2291        return Err(diag.emit());
2292    };
2293
2294    // Check that all obligations are satisfied by the implementation's
2295    // version.
2296    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2297    if !errors.is_empty() {
2298        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2299    }
2300
2301    ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env, [])
2302}
2303
2304#[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(2304u32),
                                    ::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_clause_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))]
2305fn compare_impl_ty<'tcx>(
2306    tcx: TyCtxt<'tcx>,
2307    impl_ty: ty::AssocItem,
2308    trait_ty: ty::AssocItem,
2309    impl_trait_ref: ty::TraitRef<'tcx>,
2310) -> Result<(), ErrorGuaranteed> {
2311    compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
2312    compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
2313    check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
2314    compare_type_clause_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
2315    check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
2316}
2317
2318/// The equivalent of [compare_method_clause_entailment], but for associated types
2319/// instead of associated functions.
2320#[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_clause_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(2320u32),
                                    ::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_clauses = tcx.clauses_of(impl_ty.def_id);
            let trait_ty_clauses = tcx.clauses_of(trait_ty.def_id);
            let impl_ty_own_bounds =
                impl_ty_clauses.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:2348",
                                    "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(2348u32),
                                    ::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_clauses =
                tcx.clauses_of(impl_ty_clauses.parent.unwrap());
            let mut hybrid_clauses =
                impl_clauses.instantiate_identity(tcx).clauses;
            hybrid_clauses.extend(trait_ty_clauses.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:2357",
                                    "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(2357u32),
                                    ::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_clauses")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hybrid_clauses");
                                                        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_clauses)
                                                        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_clauses.extend(tcx.const_conditions(impl_ty_clauses.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_clauses =
                hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
            let param_env =
                ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_clauses));
            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:2382",
                                    "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(2382u32),
                                    ::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 (clause, span) in impl_ty_own_bounds {
                let cause = ObligationCause::misc(span, impl_ty_def_id);
                let clause = ocx.normalize(&cause, param_env, clause);
                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, clause));
            }
            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))]
2321fn compare_type_clause_entailment<'tcx>(
2322    tcx: TyCtxt<'tcx>,
2323    impl_ty: ty::AssocItem,
2324    trait_ty: ty::AssocItem,
2325    impl_trait_ref: ty::TraitRef<'tcx>,
2326) -> Result<(), ErrorGuaranteed> {
2327    let impl_def_id = impl_ty.container_id(tcx);
2328    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
2329        tcx,
2330        impl_def_id,
2331        impl_trait_ref.args,
2332    );
2333
2334    let impl_ty_clauses = tcx.clauses_of(impl_ty.def_id);
2335    let trait_ty_clauses = tcx.clauses_of(trait_ty.def_id);
2336
2337    let impl_ty_own_bounds = impl_ty_clauses.instantiate_own_identity();
2338    // If there are no bounds, then there are no const conditions, so no need to check that here.
2339    if impl_ty_own_bounds.len() == 0 {
2340        // Nothing to check.
2341        return Ok(());
2342    }
2343
2344    // This `DefId` should be used for the `body_def_id` field on each
2345    // `ObligationCause` (and the `FnCtxt`). This is what
2346    // `regionck_item` expects.
2347    let impl_ty_def_id = impl_ty.def_id.expect_local();
2348    debug!(?trait_to_impl_args);
2349
2350    // The clauses declared by the impl definition, the trait and the
2351    // associated type in the trait are assumed.
2352    let impl_clauses = tcx.clauses_of(impl_ty_clauses.parent.unwrap());
2353    let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
2354    hybrid_clauses.extend(
2355        trait_ty_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(predicate, _)| predicate),
2356    );
2357    debug!(?hybrid_clauses);
2358
2359    let impl_ty_span = tcx.def_span(impl_ty_def_id);
2360    let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
2361
2362    let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
2363    if is_conditionally_const {
2364        // Augment the hybrid param-env with the const conditions
2365        // of the impl header and the trait assoc type.
2366        hybrid_clauses.extend(
2367            tcx.const_conditions(impl_ty_clauses.parent.unwrap())
2368                .instantiate_identity(tcx)
2369                .into_iter()
2370                .chain(
2371                    tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
2372                )
2373                .map(|(trait_ref, _)| {
2374                    trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
2375                }),
2376        );
2377    }
2378
2379    let hybrid_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
2380    let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_clauses));
2381    let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
2382    debug!(caller_bounds=?param_env.caller_bounds());
2383
2384    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2385    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2386
2387    for (clause, span) in impl_ty_own_bounds {
2388        let cause = ObligationCause::misc(span, impl_ty_def_id);
2389        let clause = ocx.normalize(&cause, param_env, clause);
2390
2391        let cause = ObligationCause::new(
2392            span,
2393            impl_ty_def_id,
2394            ObligationCauseCode::CompareImplItem {
2395                impl_item_def_id: impl_ty.def_id.expect_local(),
2396                trait_item_def_id: trait_ty.def_id,
2397                kind: impl_ty.kind,
2398            },
2399        );
2400        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
2401    }
2402
2403    if is_conditionally_const {
2404        // Validate the const conditions of the impl associated type.
2405        let impl_ty_own_const_conditions =
2406            tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2407        for (const_condition, span) in impl_ty_own_const_conditions {
2408            let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2409            let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2410
2411            let cause = ObligationCause::new(
2412                span,
2413                impl_ty_def_id,
2414                ObligationCauseCode::CompareImplItem {
2415                    impl_item_def_id: impl_ty_def_id,
2416                    trait_item_def_id: trait_ty.def_id,
2417                    kind: impl_ty.kind,
2418                },
2419            );
2420            ocx.register_obligation(traits::Obligation::new(
2421                tcx,
2422                cause,
2423                param_env,
2424                const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2425            ));
2426        }
2427    }
2428
2429    // Check that all obligations are satisfied by the implementation's
2430    // version.
2431    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2432    if !errors.is_empty() {
2433        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2434        return Err(reported);
2435    }
2436
2437    // Finally, resolve all regions. This catches wily misuses of
2438    // lifetime parameters.
2439    ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2440}
2441
2442/// Validate that `ProjectionCandidate`s created for this associated type will
2443/// be valid.
2444///
2445/// Usually given
2446///
2447/// trait X { type Y: Copy } impl X for T { type Y = S; }
2448///
2449/// We are able to normalize `<T as X>::Y` to `S`, and so when we check the
2450/// impl is well-formed we have to prove `S: Copy`.
2451///
2452/// For default associated types the normalization is not possible (the value
2453/// from the impl could be overridden). We also can't normalize generic
2454/// associated types (yet) because they contain bound parameters.
2455#[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(2455u32),
                                    ::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:2467",
                                    "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(2467u32),
                                    ::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:2516",
                                                            "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(2516u32),
                                                            ::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:2539",
                                    "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(2539u32),
                                    ::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))]
2456pub(super) fn check_type_bounds<'tcx>(
2457    tcx: TyCtxt<'tcx>,
2458    trait_ty: ty::AssocItem,
2459    impl_ty: ty::AssocItem,
2460    impl_trait_ref: ty::TraitRef<'tcx>,
2461) -> Result<(), ErrorGuaranteed> {
2462    // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
2463    // other `Foo` impls are incoherent.
2464    tcx.ensure_result().coherent_trait(impl_trait_ref.def_id)?;
2465
2466    let param_env = tcx.param_env(impl_ty.def_id);
2467    debug!(?param_env);
2468
2469    let container_id = impl_ty.container_id(tcx);
2470    let impl_ty_def_id = impl_ty.def_id.expect_local();
2471    let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2472    let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2473
2474    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2475    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2476
2477    // A synthetic impl Trait for RPITIT desugaring or assoc type for effects desugaring has no HIR,
2478    // which we currently use to get the span for an impl's associated type. Instead, for these,
2479    // use the def_span for the synthesized  associated type.
2480    let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2481        tcx.def_span(impl_ty_def_id)
2482    } else {
2483        match tcx.hir_node_by_def_id(impl_ty_def_id) {
2484            hir::Node::TraitItem(hir::TraitItem {
2485                kind: hir::TraitItemKind::Type(_, Some(ty)),
2486                ..
2487            }) => ty.span,
2488            hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2489            item => span_bug!(
2490                tcx.def_span(impl_ty_def_id),
2491                "cannot call `check_type_bounds` on item: {item:?}",
2492            ),
2493        }
2494    };
2495    let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2496
2497    let normalize_cause = ObligationCause::new(
2498        impl_ty_span,
2499        impl_ty_def_id,
2500        ObligationCauseCode::CheckAssociatedTypeBounds {
2501            impl_item_def_id: impl_ty.def_id.expect_local(),
2502            trait_item_def_id: trait_ty.def_id,
2503        },
2504    );
2505    let mk_cause = |span: Span| {
2506        let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2507        ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2508    };
2509
2510    let mut obligations: Vec<_> = util::elaborate(
2511        tcx,
2512        tcx.explicit_item_bounds(trait_ty.def_id)
2513            .iter_instantiated_copied(tcx, rebased_args)
2514            .map(Unnormalized::skip_norm_wip)
2515            .map(|(concrete_ty_bound, span)| {
2516                debug!(?concrete_ty_bound);
2517                traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2518            }),
2519    )
2520    .collect();
2521
2522    // Only in a const implementation do we need to check that the `[const]` item bounds hold.
2523    if tcx.is_conditionally_const(impl_ty_def_id) {
2524        obligations.extend(util::elaborate(
2525            tcx,
2526            tcx.explicit_implied_const_bounds(trait_ty.def_id)
2527                .iter_instantiated_copied(tcx, rebased_args)
2528                .map(Unnormalized::skip_norm_wip)
2529                .map(|(c, span)| {
2530                    traits::Obligation::new(
2531                        tcx,
2532                        mk_cause(span),
2533                        param_env,
2534                        c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2535                    )
2536                }),
2537        ));
2538    }
2539    debug!(item_bounds=?obligations);
2540
2541    // Normalize predicates with the assumption that the GAT may always normalize
2542    // to its definition type. This should be the param-env we use to *prove* the
2543    // predicate too, but we don't do that because of performance issues.
2544    // See <https://github.com/rust-lang/rust/pull/117542#issue-1976337685>.
2545    let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2546    for obligation in &mut obligations {
2547        match ocx.deeply_normalize(
2548            &normalize_cause,
2549            normalize_param_env,
2550            Unnormalized::new_wip(obligation.predicate),
2551        ) {
2552            Ok(pred) => obligation.predicate = pred,
2553            Err(e) => {
2554                return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2555            }
2556        }
2557    }
2558
2559    // Check that all obligations are satisfied by the implementation's
2560    // version.
2561    ocx.register_obligations(obligations);
2562    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2563    if !errors.is_empty() {
2564        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2565        return Err(reported);
2566    }
2567
2568    // Finally, resolve all regions. This catches wily misuses of
2569    // lifetime parameters.
2570    ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2571}
2572
2573/// Install projection predicates that allow GATs to project to their own
2574/// definition types. This is not allowed in general in cases of default
2575/// associated types in trait definitions, or when specialization is involved,
2576/// but is needed when checking these definition types actually satisfy the
2577/// trait bounds of the GAT.
2578///
2579/// # How it works
2580///
2581/// ```ignore (example)
2582/// impl<A, B> Foo<u32> for (A, B) {
2583///     type Bar<C> = Wrapper<A, B, C>
2584/// }
2585/// ```
2586///
2587/// - `impl_trait_ref` would be `<(A, B) as Foo<u32>>`
2588/// - `normalize_impl_ty_args` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
2589/// - `normalize_impl_ty` would be `Wrapper<A, B, ^0.0>`
2590/// - `rebased_args` would be `[(A, B), u32, ^0.0]`, combining the args from
2591///    the *trait* with the generic associated type parameters (as bound vars).
2592///
2593/// A note regarding the use of bound vars here:
2594/// Imagine as an example
2595/// ```
2596/// trait Family {
2597///     type Member<C: Eq>;
2598/// }
2599///
2600/// impl Family for VecFamily {
2601///     type Member<C: Eq> = i32;
2602/// }
2603/// ```
2604/// Here, we would generate
2605/// ```ignore (pseudo-rust)
2606/// forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
2607/// ```
2608///
2609/// when we really would like to generate
2610/// ```ignore (pseudo-rust)
2611/// forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
2612/// ```
2613///
2614/// But, this is probably fine, because although the first clause can be used with types `C` that
2615/// do not implement `Eq`, for it to cause some kind of problem, there would have to be a
2616/// `VecFamily::Member<X>` for some type `X` where `!(X: Eq)`, that appears in the value of type
2617/// `Member<C: Eq> = ....` That type would fail a well-formedness check that we ought to be doing
2618/// elsewhere, which would check that any `<T as Family>::Member<X>` meets the bounds declared in
2619/// the trait (notably, that `X: Eq` and `T: Family`).
2620fn param_env_with_gat_bounds<'tcx>(
2621    tcx: TyCtxt<'tcx>,
2622    impl_ty: ty::AssocItem,
2623    impl_trait_ref: ty::TraitRef<'tcx>,
2624) -> ty::ParamEnv<'tcx> {
2625    let param_env = tcx.param_env(impl_ty.def_id);
2626    let container_id = impl_ty.container_id(tcx);
2627    let mut clauses = param_env.caller_bounds().to_vec();
2628
2629    // for RPITITs, we should install predicates that allow us to project all
2630    // of the RPITITs associated with the same body. This is because checking
2631    // the item bounds of RPITITs often involves nested RPITITs having to prove
2632    // bounds about themselves.
2633    let impl_tys_to_install = match impl_ty.kind {
2634        ty::AssocKind::Type {
2635            data:
2636                ty::AssocTypeData::Rpitit(
2637                    ty::ImplTraitInTraitData::Impl { fn_def_id }
2638                    | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2639                ),
2640        } => tcx
2641            .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2642            .iter()
2643            .map(|def_id| tcx.associated_item(*def_id))
2644            .collect(),
2645        _ => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [impl_ty]))vec![impl_ty],
2646    };
2647
2648    for impl_ty in impl_tys_to_install {
2649        let trait_ty = match impl_ty.container {
2650            ty::AssocContainer::InherentImpl => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
2651            ty::AssocContainer::Trait => impl_ty,
2652            ty::AssocContainer::TraitImpl(Err(_)) => continue,
2653            ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
2654                tcx.associated_item(trait_item_def_id)
2655            }
2656        };
2657
2658        let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind<'tcx>; 8]> =
2659            smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2660        // Extend the impl's identity args with late-bound GAT vars
2661        let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2662            .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2663                GenericParamDefKind::Type { .. } => {
2664                    let kind = ty::BoundTyKind::Param(param.def_id);
2665                    let bound_var = ty::BoundVariableKind::Ty(kind);
2666                    bound_vars.push(bound_var);
2667                    Ty::new_bound(
2668                        tcx,
2669                        ty::INNERMOST,
2670                        ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2671                    )
2672                    .into()
2673                }
2674                GenericParamDefKind::Lifetime => {
2675                    let kind = ty::BoundRegionKind::Named(param.def_id);
2676                    let bound_var = ty::BoundVariableKind::Region(kind);
2677                    bound_vars.push(bound_var);
2678                    ty::Region::new_bound(
2679                        tcx,
2680                        ty::INNERMOST,
2681                        ty::BoundRegion {
2682                            var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2683                            kind,
2684                        },
2685                    )
2686                    .into()
2687                }
2688                GenericParamDefKind::Const { .. } => {
2689                    let bound_var = ty::BoundVariableKind::Const;
2690                    bound_vars.push(bound_var);
2691                    ty::Const::new_bound(
2692                        tcx,
2693                        ty::INNERMOST,
2694                        ty::BoundConst::new(ty::BoundVar::from_usize(bound_vars.len() - 1)),
2695                    )
2696                    .into()
2697                }
2698            });
2699        // When checking something like
2700        //
2701        // trait X { type Y: PartialEq<<Self as X>::Y> }
2702        // impl X for T { default type Y = S; }
2703        //
2704        // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
2705        // we want <T as X>::Y to normalize to S. This is valid because we are
2706        // checking the default value specifically here. Add this equality to the
2707        // ParamEnv for normalization specifically.
2708        let normalize_impl_ty =
2709            tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args).skip_norm_wip();
2710        let rebased_args =
2711            normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2712        let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2713
2714        match normalize_impl_ty.kind() {
2715            &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
2716                if def_id == trait_ty.def_id && args == rebased_args =>
2717            {
2718                // Don't include this predicate if the projected type is
2719                // exactly the same as the projection. This can occur in
2720                // (somewhat dubious) code like this:
2721                //
2722                // impl<T> X for T where T: X { type Y = <T as X>::Y; }
2723            }
2724            _ => clauses.push(
2725                ty::Binder::bind_with_vars(
2726                    ty::ProjectionPredicate {
2727                        projection_term: ty::AliasTerm::new_from_def_id(
2728                            tcx,
2729                            trait_ty.def_id,
2730                            rebased_args,
2731                        ),
2732                        term: normalize_impl_ty.into(),
2733                    },
2734                    bound_vars,
2735                )
2736                .upcast(tcx),
2737            ),
2738        };
2739    }
2740
2741    ty::ParamEnv::new(tcx.mk_clauses(&clauses))
2742}
2743
2744/// Manually check here that `async fn foo()` wasn't matched against `fn foo()`,
2745/// and extract a better error if so.
2746fn try_report_async_mismatch<'tcx>(
2747    tcx: TyCtxt<'tcx>,
2748    infcx: &InferCtxt<'tcx>,
2749    errors: &[FulfillmentError<'tcx>],
2750    trait_m: ty::AssocItem,
2751    impl_m: ty::AssocItem,
2752    impl_sig: ty::FnSig<'tcx>,
2753) -> Result<(), ErrorGuaranteed> {
2754    if !tcx.asyncness(trait_m.def_id).is_async() {
2755        return Ok(());
2756    }
2757
2758    let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id: async_future_def_id }, .. }) =
2759        *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2760    else {
2761        ::rustc_middle::util::bug::bug_fmt(format_args!("expected `async fn` to return an RPITIT"));bug!("expected `async fn` to return an RPITIT");
2762    };
2763
2764    for error in errors {
2765        if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2766            && def_id == async_future_def_id
2767            && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2768            && let Some(proj) = proj.no_bound_vars()
2769            && infcx.can_eq(
2770                error.root_obligation.param_env,
2771                proj.term.expect_type(),
2772                impl_sig.output(),
2773            )
2774        {
2775            // FIXME: We should suggest making the fn `async`, but extracting
2776            // the right span is a bit difficult.
2777            return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2778                span: tcx.def_span(impl_m.def_id),
2779                method_name: tcx.item_ident(impl_m.def_id),
2780                trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
2781            }));
2782        }
2783    }
2784
2785    Ok(())
2786}