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::{TraitErrors, 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::solve::NextSolverError;
27use rustc_trait_selection::traits::{
28    self, FromSolverError, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
29};
30use tracing::{debug, instrument};
31
32use super::potentially_plural_count;
33use crate::diagnostics::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture};
34
35pub(super) mod refine;
36
37/// Call the query `tcx.compare_impl_item()` directly instead.
38pub(super) fn compare_impl_item(
39    tcx: TyCtxt<'_>,
40    impl_item_def_id: LocalDefId,
41) -> Result<(), ErrorGuaranteed> {
42    let impl_item = tcx.associated_item(impl_item_def_id);
43    let trait_item = tcx.associated_item(impl_item.expect_trait_impl()?);
44    let impl_trait_ref =
45        tcx.impl_trait_ref(impl_item.container_id(tcx)).instantiate_identity().skip_norm_wip();
46    {
    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:46",
                        "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(46u32),
                        ::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);
47
48    match impl_item.kind {
49        ty::AssocKind::Fn { .. } => compare_impl_method(tcx, impl_item, trait_item, impl_trait_ref),
50        ty::AssocKind::Type { .. } => compare_impl_ty(tcx, impl_item, trait_item, impl_trait_ref),
51        ty::AssocKind::Const { .. } => {
52            compare_impl_const(tcx, impl_item, trait_item, impl_trait_ref)
53        }
54    }
55}
56
57/// Checks that a method from an impl conforms to the signature of
58/// the same method as declared in the trait.
59///
60/// # Parameters
61///
62/// - `impl_m`: type of the method we are checking
63/// - `trait_m`: the method in the trait
64/// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
65#[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(65u32),
                                    ::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))]
66fn compare_impl_method<'tcx>(
67    tcx: TyCtxt<'tcx>,
68    impl_m: ty::AssocItem,
69    trait_m: ty::AssocItem,
70    impl_trait_ref: ty::TraitRef<'tcx>,
71) -> Result<(), ErrorGuaranteed> {
72    check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, false)?;
73    compare_method_clause_entailment(tcx, impl_m, trait_m, impl_trait_ref)?;
74    Ok(())
75}
76
77/// Checks a bunch of different properties of the impl/trait methods for
78/// compatibility, such as asyncness, number of argument, self receiver kind,
79/// and number of early- and late-bound generics.
80fn check_method_is_structurally_compatible<'tcx>(
81    tcx: TyCtxt<'tcx>,
82    impl_m: ty::AssocItem,
83    trait_m: ty::AssocItem,
84    impl_trait_ref: ty::TraitRef<'tcx>,
85    delay: bool,
86) -> Result<(), ErrorGuaranteed> {
87    compare_self_type(tcx, impl_m, trait_m, impl_trait_ref, delay)?;
88    compare_number_of_generics(tcx, impl_m, trait_m, delay)?;
89    compare_generic_param_kinds(tcx, impl_m, trait_m, delay)?;
90    compare_number_of_method_arguments(tcx, impl_m, trait_m, delay)?;
91    compare_synthetic_generics(tcx, impl_m, trait_m, delay)?;
92    check_region_bounds_on_impl_item(tcx, impl_m, trait_m, delay)?;
93    Ok(())
94}
95
96/// This function is best explained by example. Consider a trait with its implementation:
97///
98/// ```rust
99/// trait Trait<'t, T> {
100///     // `trait_m`
101///     fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
102/// }
103///
104/// struct Foo;
105///
106/// impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
107///     // `impl_m`
108///     fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo { Foo }
109/// }
110/// ```
111///
112/// We wish to decide if those two method types are compatible.
113/// For this we have to show that, assuming the bounds of the impl hold, the
114/// bounds of `trait_m` imply the bounds of `impl_m`.
115///
116/// We start out with `trait_to_impl_args`, that maps the trait
117/// type parameters to impl type parameters. This is taken from the
118/// impl trait reference:
119///
120/// ```rust,ignore (pseudo-Rust)
121/// trait_to_impl_args = {'t => 'j, T => &'i U, Self => Foo}
122/// ```
123///
124/// We create a mapping `dummy_args` that maps from the impl type
125/// parameters to fresh types and regions. For type parameters,
126/// this is the identity transform, but we could as well use any
127/// placeholder types. For regions, we convert from bound to free
128/// regions (Note: but only early-bound regions, i.e., those
129/// declared on the impl or used in type parameter bounds).
130///
131/// ```rust,ignore (pseudo-Rust)
132/// impl_to_placeholder_args = {'i => 'i0, U => U0, N => N0 }
133/// ```
134///
135/// Now we can apply `placeholder_args` to the type of the impl method
136/// to yield a new function type in terms of our fresh, placeholder
137/// types:
138///
139/// ```rust,ignore (pseudo-Rust)
140/// <'b> fn(t: &'i0 U0, m: &'b N0) -> Foo
141/// ```
142///
143/// We now want to extract and instantiate the type of the *trait*
144/// method and compare it. To do so, we must create a compound
145/// instantiation by combining `trait_to_impl_args` and
146/// `impl_to_placeholder_args`, and also adding a mapping for the method
147/// type parameters. We extend the mapping to also include
148/// the method parameters.
149///
150/// ```rust,ignore (pseudo-Rust)
151/// trait_to_placeholder_args = { T => &'i0 U0, Self => Foo, M => N0 }
152/// ```
153///
154/// Applying this to the trait method type yields:
155///
156/// ```rust,ignore (pseudo-Rust)
157/// <'a> fn(t: &'i0 U0, m: &'a N0) -> Foo
158/// ```
159///
160/// This type is also the same but the name of the bound region (`'a`
161/// vs `'b`). However, the normal subtyping rules on fn types handle
162/// this kind of equivalency just fine.
163///
164/// We now use these generic parameters to ensure that all declared bounds
165/// are satisfied by the implementation's method.
166///
167/// We do this by creating a parameter environment which contains a
168/// generic parameter corresponding to `impl_to_placeholder_args`. We then build
169/// `trait_to_placeholder_args` and use it to convert the clauses contained
170/// in the `trait_m` generics to the placeholder form.
171///
172/// Finally we register each of these clauses as an obligation and check that
173/// they hold.
174#[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(174u32),
                                    ::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:205",
                                    "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(205u32),
                                    ::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:257",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(257u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("caller_bounds")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("caller_bounds");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_env.caller_bounds())
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let infcx =
                &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
            let ocx = ObligationCtxt::new_with_diagnostics(infcx);
            let impl_m_own_bounds = impl_m_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:333",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(333u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_sig")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_sig");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_sig)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let trait_sig =
                tcx.fn_sig(trait_m.def_id).instantiate(tcx,
                        trait_to_impl_args).skip_norm_wip();
            let trait_sig =
                tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
            wf_tys.extend(trait_sig.inputs_and_output.iter());
            let trait_sig =
                ocx.normalize(&norm_cause, param_env,
                    Unnormalized::new_wip(trait_sig));
            wf_tys.extend(trait_sig.inputs_and_output.iter());
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:346",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(346u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_sig")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_sig");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_sig)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
            if let Err(terr) = result {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:358",
                                        "rustc_hir_analysis::check::compare_impl_item",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                        ::tracing_core::__macro_support::Option::Some(358u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                        ::tracing_core::field::FieldSet::new(&["message",
                                                        {
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("impl_sig")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("impl_sig");
                                                            NAME.as_str()
                                                        },
                                                        {
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("trait_sig")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("trait_sig");
                                                            NAME.as_str()
                                                        },
                                                        {
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("terr")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("terr");
                                                            NAME.as_str()
                                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("sub_types failed")
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_sig)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_sig)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&terr)
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                let emitted =
                    report_trait_method_mismatch(infcx, cause, param_env, terr,
                        (trait_m, trait_sig), (impl_m, impl_sig), impl_trait_ref);
                return Err(emitted);
            }
            if !(impl_sig, trait_sig).references_error() {
                for ty in unnormalized_impl_sig.inputs_and_output {
                    ocx.register_obligation(traits::Obligation::new(infcx.tcx,
                            cause.clone(), param_env,
                            ty::ClauseKind::WellFormed(ty.into())));
                }
            }
            let errors = ocx.evaluate_obligations_error_on_ambiguity();
            if let TraitErrors::HasErrors(errors) = errors {
                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))]
175fn compare_method_clause_entailment<'tcx>(
176    tcx: TyCtxt<'tcx>,
177    impl_m: ty::AssocItem,
178    trait_m: ty::AssocItem,
179    impl_trait_ref: ty::TraitRef<'tcx>,
180) -> Result<(), ErrorGuaranteed> {
181    // This node-id should be used for the `body_def_id` field on each
182    // `ObligationCause` (and the `FnCtxt`).
183    //
184    // FIXME(@lcnr): remove that after removing `cause.body_def_id` from
185    // obligations.
186    let impl_m_def_id = impl_m.def_id.expect_local();
187    let impl_m_span = tcx.def_span(impl_m_def_id);
188    let cause = ObligationCause::new(
189        impl_m_span,
190        impl_m_def_id,
191        ObligationCauseCode::CompareImplItem {
192            impl_item_def_id: impl_m_def_id,
193            trait_item_def_id: trait_m.def_id,
194            kind: impl_m.kind,
195        },
196    );
197
198    // Create mapping from trait method to impl method.
199    let impl_def_id = impl_m.container_id(tcx);
200    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
201        tcx,
202        impl_m.container_id(tcx),
203        impl_trait_ref.args,
204    );
205    debug!(?trait_to_impl_args);
206
207    let impl_m_clauses = tcx.clauses_of(impl_m.def_id);
208    let trait_m_clauses = tcx.clauses_of(trait_m.def_id);
209
210    // This is the only tricky bit of the new way we check implementation methods
211    // We need to build a set of clauses where only the method-level bounds
212    // are from the trait and we assume all other bounds from the implementation
213    // to be previously satisfied.
214    //
215    // We then register the obligations from the impl_m and check to see
216    // if all constraints hold.
217    let impl_clauses = tcx.clauses_of(impl_m_clauses.parent.unwrap());
218    let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
219    hybrid_clauses
220        .extend(trait_m_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(clause, _)| clause));
221
222    let is_conditionally_const = tcx.is_conditionally_const(impl_m.def_id);
223    if is_conditionally_const {
224        // Augment the hybrid param-env with the const conditions
225        // of the impl header and the trait method.
226        hybrid_clauses.extend(
227            tcx.const_conditions(impl_def_id)
228                .instantiate_identity(tcx)
229                .into_iter()
230                .chain(
231                    tcx.const_conditions(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args),
232                )
233                .map(|(trait_ref, _)| {
234                    trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
235                }),
236        );
237    }
238
239    let hybrid_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
240    let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
241    let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_clauses));
242    // NOTE(-Zhigher-ranked-assumptions): The `hybrid_preds`
243    // should be well-formed. However, using them may result in
244    // region errors as we currently don't track placeholder
245    // assumptions.
246    //
247    // We eagerly normalize the where-clauses here while ignoring
248    // region constraints. This means we can then use where-bounds
249    // whose normalization results in placeholder errors further
250    // down without getting any errors.
251    //
252    // This should be sound to do so as the only region errors here
253    // should be due to missing implied bounds.
254    //
255    // cc trait-system-refactor-initiative/issues/166.
256    let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
257    debug!(caller_bounds=?param_env.caller_bounds());
258
259    let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
260    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
261
262    // Create obligations for each clause declared by the impl
263    // definition in the context of the hybrid param-env. This makes
264    // sure that the impl's method's where clauses are not more
265    // restrictive than the trait's method (and the impl itself).
266    let impl_m_own_bounds = impl_m_clauses.instantiate_own_identity();
267    for (clause, span) in impl_m_own_bounds {
268        let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
269        let clause = ocx.normalize(&normalize_cause, param_env, clause);
270
271        let cause = ObligationCause::new(
272            span,
273            impl_m_def_id,
274            ObligationCauseCode::CompareImplItem {
275                impl_item_def_id: impl_m_def_id,
276                trait_item_def_id: trait_m.def_id,
277                kind: impl_m.kind,
278            },
279        );
280        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
281    }
282
283    // If we're within a const implementation, we need to make sure that the method
284    // does not assume stronger `[const]` bounds than the trait definition.
285    //
286    // This registers the `[const]` bounds of the impl method, which we will prove
287    // using the hybrid param-env that we earlier augmented with the const conditions
288    // from the impl header and trait method declaration.
289    if is_conditionally_const {
290        for (const_condition, span) in
291            tcx.const_conditions(impl_m.def_id).instantiate_own_identity()
292        {
293            let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
294            let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
295
296            let cause = ObligationCause::new(
297                span,
298                impl_m_def_id,
299                ObligationCauseCode::CompareImplItem {
300                    impl_item_def_id: impl_m_def_id,
301                    trait_item_def_id: trait_m.def_id,
302                    kind: impl_m.kind,
303                },
304            );
305            ocx.register_obligation(traits::Obligation::new(
306                tcx,
307                cause,
308                param_env,
309                const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
310            ));
311        }
312    }
313
314    // We now need to check that the signature of the impl method is
315    // compatible with that of the trait method. We do this by
316    // checking that `impl_fty <: trait_fty`.
317    //
318    // FIXME: We manually instantiate the trait method here as we need
319    // to manually compute its implied bounds. Otherwise this could just
320    // be `ocx.sub(impl_sig, trait_sig)`.
321
322    let mut wf_tys = FxIndexSet::default();
323
324    let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars(
325        impl_m_span,
326        BoundRegionConversionTime::HigherRankedType,
327        tcx.fn_sig(impl_m.def_id).instantiate_identity().skip_norm_wip(),
328    );
329
330    let norm_cause = ObligationCause::misc(impl_m_span, impl_m_def_id);
331    let impl_sig =
332        ocx.normalize(&norm_cause, param_env, Unnormalized::new_wip(unnormalized_impl_sig));
333    debug!(?impl_sig);
334
335    let trait_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args).skip_norm_wip();
336    let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
337
338    // Next, add all inputs and output as well-formed tys. Importantly,
339    // we have to do this before normalization, since the normalized ty may
340    // not contain the input parameters. See issue #87748.
341    wf_tys.extend(trait_sig.inputs_and_output.iter());
342    let trait_sig = ocx.normalize(&norm_cause, param_env, Unnormalized::new_wip(trait_sig));
343    // We also have to add the normalized trait signature
344    // as we don't normalize during implied bounds computation.
345    wf_tys.extend(trait_sig.inputs_and_output.iter());
346    debug!(?trait_sig);
347
348    // FIXME: We'd want to keep more accurate spans than "the method signature" when
349    // processing the comparison between the trait and impl fn, but we sadly lose them
350    // and point at the whole signature when a trait bound or specific input or output
351    // type would be more appropriate. In other places we have a `Vec<Span>`
352    // corresponding to their `Vec<Predicate>`, but we don't have that here.
353    // Fixing this would improve the output of test `issue-83765.rs`.
354    // There's the same issue in compare_eii code.
355    let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
356
357    if let Err(terr) = result {
358        debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
359
360        let emitted = report_trait_method_mismatch(
361            infcx,
362            cause,
363            param_env,
364            terr,
365            (trait_m, trait_sig),
366            (impl_m, impl_sig),
367            impl_trait_ref,
368        );
369        return Err(emitted);
370    }
371
372    if !(impl_sig, trait_sig).references_error() {
373        for ty in unnormalized_impl_sig.inputs_and_output {
374            ocx.register_obligation(traits::Obligation::new(
375                infcx.tcx,
376                cause.clone(),
377                param_env,
378                ty::ClauseKind::WellFormed(ty.into()),
379            ));
380        }
381    }
382
383    // Check that all obligations are satisfied by the implementation's
384    // version.
385    let errors = ocx.evaluate_obligations_error_on_ambiguity();
386    if let TraitErrors::HasErrors(errors) = errors {
387        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
388        return Err(reported);
389    }
390
391    // Finally, resolve all regions. This catches wily misuses of
392    // lifetime parameters.
393    let errors = infcx.resolve_regions(impl_m_def_id, param_env, wf_tys);
394    if !errors.is_empty() {
395        return Err(infcx
396            .tainted_by_errors()
397            .unwrap_or_else(|| infcx.err_ctxt().report_region_errors(impl_m_def_id, &errors)));
398    }
399
400    Ok(())
401}
402
403struct RemapLateParam<'tcx> {
404    tcx: TyCtxt<'tcx>,
405    mapping: FxIndexMap<ty::LateParamRegionKind, ty::LateParamRegionKind>,
406}
407
408impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateParam<'tcx> {
409    fn cx(&self) -> TyCtxt<'tcx> {
410        self.tcx
411    }
412
413    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
414        if let ty::ReLateParam(fr) = r.kind() {
415            ty::Region::new_late_param(
416                self.tcx,
417                fr.scope,
418                self.mapping.get(&fr.kind).copied().unwrap_or(fr.kind),
419            )
420        } else {
421            r
422        }
423    }
424}
425
426/// Given a method def-id in an impl, compare the method signature of the impl
427/// against the trait that it's implementing. In doing so, infer the hidden types
428/// that this method's signature provides to satisfy each return-position `impl Trait`
429/// in the trait signature.
430///
431/// The method is also responsible for making sure that the hidden types for each
432/// RPITIT actually satisfy the bounds of the `impl Trait`, i.e. that if we infer
433/// `impl Trait = Foo`, that `Foo: Trait` holds.
434///
435/// For example, given the sample code:
436///
437/// ```
438/// use std::ops::Deref;
439///
440/// trait Foo {
441///     fn bar() -> impl Deref<Target = impl Sized>;
442///     //          ^- RPITIT #1        ^- RPITIT #2
443/// }
444///
445/// impl Foo for () {
446///     fn bar() -> Box<String> { Box::new(String::new()) }
447/// }
448/// ```
449///
450/// The hidden types for the RPITITs in `bar` would be inferred to:
451///     * `impl Deref` (RPITIT #1) = `Box<String>`
452///     * `impl Sized` (RPITIT #2) = `String`
453///
454/// The relationship between these two types is straightforward in this case, but
455/// may be more tenuously connected via other `impl`s and normalization rules for
456/// cases of more complicated nested RPITITs.
457x;#[instrument(skip(tcx), level = "debug", ret)]
458pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
459    tcx: TyCtxt<'tcx>,
460    impl_m_def_id: LocalDefId,
461) -> Result<&'tcx DefIdMap<ty::EarlyBinder<'tcx, Ty<'tcx>>>, ErrorGuaranteed> {
462    let impl_m = tcx.associated_item(impl_m_def_id.to_def_id());
463    let trait_m = tcx.associated_item(impl_m.expect_trait_impl()?);
464    let impl_trait_ref = tcx
465        .impl_trait_ref(tcx.parent(impl_m_def_id.to_def_id()))
466        .instantiate_identity()
467        .skip_norm_wip();
468    // First, check a few of the same things as `compare_impl_method`,
469    // just so we don't ICE during instantiation later.
470    check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?;
471
472    let impl_m_hir_id = tcx.local_def_id_to_hir_id(impl_m_def_id);
473    let return_span = tcx.hir_fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
474    let cause = ObligationCause::new(
475        return_span,
476        impl_m_def_id,
477        ObligationCauseCode::CompareImplItem {
478            impl_item_def_id: impl_m_def_id,
479            trait_item_def_id: trait_m.def_id,
480            kind: impl_m.kind,
481        },
482    );
483
484    // Create mapping from trait to impl (i.e. impl trait header + impl method identity args).
485    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
486        tcx,
487        impl_m.container_id(tcx),
488        impl_trait_ref.args,
489    );
490
491    let hybrid_clauses = tcx
492        .clauses_of(impl_m.container_id(tcx))
493        .instantiate_identity(tcx)
494        .into_iter()
495        .chain(tcx.clauses_of(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args))
496        .map(|(clause, _)| clause.skip_norm_wip());
497    let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_clauses));
498    let param_env = traits::normalize_param_env_or_error(
499        tcx,
500        param_env,
501        ObligationCause::misc(tcx.def_span(impl_m_def_id), impl_m_def_id),
502    );
503
504    let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
505    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
506
507    // Check that the where clauses of the impl are satisfied by the hybrid param env.
508    // You might ask -- what does this have to do with RPITIT inference? Nothing.
509    // We check these because if the where clauses of the signatures do not match
510    // up, then we don't want to give spurious other errors that point at the RPITITs.
511    // They're not necessary to check, though, because we already check them in
512    // `compare_method_clause_entailment`.
513    let impl_m_own_bounds = tcx.clauses_of(impl_m_def_id).instantiate_own_identity();
514    for (clause, span) in impl_m_own_bounds {
515        let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
516        let clause = ocx.normalize(&normalize_cause, param_env, clause);
517
518        let cause = ObligationCause::new(
519            span,
520            impl_m_def_id,
521            ObligationCauseCode::CompareImplItem {
522                impl_item_def_id: impl_m_def_id,
523                trait_item_def_id: trait_m.def_id,
524                kind: impl_m.kind,
525            },
526        );
527        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
528    }
529
530    // Normalize the impl signature with fresh variables for lifetime inference.
531    let misc_cause = ObligationCause::misc(return_span, impl_m_def_id);
532    let impl_sig = ocx.normalize(
533        &misc_cause,
534        param_env,
535        Unnormalized::new_wip(infcx.instantiate_binder_with_fresh_vars(
536            return_span,
537            BoundRegionConversionTime::HigherRankedType,
538            tcx.fn_sig(impl_m.def_id).instantiate_identity().skip_norm_wip(),
539        )),
540    );
541    impl_sig.error_reported()?;
542    let impl_return_ty = impl_sig.output();
543
544    // Normalize the trait signature with liberated bound vars, passing it through
545    // the ImplTraitInTraitCollector, which gathers all of the RPITITs and replaces
546    // them with inference variables.
547    // We will use these inference variables to collect the hidden types of RPITITs.
548    let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_def_id);
549    let unnormalized_trait_sig = tcx
550        .liberate_late_bound_regions(
551            impl_m.def_id,
552            tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args).skip_norm_wip(),
553        )
554        .fold_with(&mut collector);
555
556    let trait_sig =
557        ocx.normalize(&misc_cause, param_env, Unnormalized::new_wip(unnormalized_trait_sig));
558    trait_sig.error_reported()?;
559    let trait_return_ty = trait_sig.output();
560
561    // RPITITs are allowed to use the implied predicates of the method that
562    // defines them. This is because we want code like:
563    // ```
564    // trait Foo {
565    //     fn test<'a, T>(_: &'a T) -> impl Sized;
566    // }
567    // impl Foo for () {
568    //     fn test<'a, T>(x: &'a T) -> &'a T { x }
569    // }
570    // ```
571    // .. to compile. However, since we use both the normalized and unnormalized
572    // inputs and outputs from the instantiated trait signature, we will end up
573    // seeing the hidden type of an RPIT in the signature itself. Naively, this
574    // means that we will use the hidden type to imply the hidden type's own
575    // well-formedness.
576    //
577    // To avoid this, we replace the infer vars used for hidden type inference
578    // with placeholders, which imply nothing about outlives bounds, and then
579    // prove below that the hidden types are well formed.
580    let universe = infcx.create_next_universe();
581    let mut idx = ty::BoundVar::ZERO;
582    let mapping: FxIndexMap<_, _> = collector
583        .types
584        .iter()
585        .map(|(_, &(ty, _))| {
586            assert!(
587                infcx.resolve_vars_if_possible(ty) == ty && ty.is_ty_var(),
588                "{ty:?} should not have been constrained via normalization",
589                ty = infcx.resolve_vars_if_possible(ty)
590            );
591            idx += 1;
592            (
593                ty,
594                Ty::new_placeholder(
595                    tcx,
596                    ty::PlaceholderType::new(
597                        universe,
598                        ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
599                    ),
600                ),
601            )
602        })
603        .collect();
604    let mut type_mapper = BottomUpFolder {
605        tcx,
606        ty_op: |ty| *mapping.get(&ty).unwrap_or(&ty),
607        lt_op: |lt| lt,
608        ct_op: |ct| ct,
609    };
610    let wf_tys = FxIndexSet::from_iter(
611        unnormalized_trait_sig
612            .inputs_and_output
613            .iter()
614            .chain(trait_sig.inputs_and_output.iter())
615            .map(|ty| ty.fold_with(&mut type_mapper)),
616    );
617
618    match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
619        Ok(()) => {}
620        Err(terr) => {
621            let mut diag = struct_span_code_err!(
622                tcx.dcx(),
623                cause.span,
624                E0053,
625                "method `{}` has an incompatible return type for trait",
626                trait_m.name()
627            );
628            infcx.err_ctxt().note_type_err(
629                &mut diag,
630                &cause,
631                tcx.hir_get_if_local(impl_m.def_id)
632                    .and_then(|node| node.fn_decl())
633                    .map(|decl| (decl.output.span(), Cow::from("return type in trait"), false)),
634                Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
635                    expected: trait_return_ty.into(),
636                    found: impl_return_ty.into(),
637                }))),
638                terr,
639                false,
640                None,
641            );
642            return Err(diag.emit());
643        }
644    }
645
646    debug!(?trait_sig, ?impl_sig, "equating function signatures");
647
648    // Unify the whole function signature. We need to do this to fully infer
649    // the lifetimes of the return type, but do this after unifying just the
650    // return types, since we want to avoid duplicating errors from
651    // `compare_method_clause_entailment`.
652    match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
653        Ok(()) => {}
654        Err(terr) => {
655            // This function gets called during `compare_method_clause_entailment` when normalizing a
656            // signature that contains RPITIT. When the method signatures don't match, we have to
657            // emit an error now because `compare_method_clause_entailment` will not report the error
658            // when normalization fails.
659            let emitted = report_trait_method_mismatch(
660                infcx,
661                cause,
662                param_env,
663                terr,
664                (trait_m, trait_sig),
665                (impl_m, impl_sig),
666                impl_trait_ref,
667            );
668            return Err(emitted);
669        }
670    }
671
672    if !unnormalized_trait_sig.output().references_error() && collector.types.is_empty() {
673        tcx.dcx().delayed_bug(
674            "expect >0 RPITITs in call to `collect_return_position_impl_trait_in_trait_tys`",
675        );
676    }
677
678    // FIXME: This has the same issue as #108544, but since this isn't breaking
679    // existing code, I'm not particularly inclined to do the same hack as above
680    // where we process wf obligations manually. This can be fixed in a forward-
681    // compatible way later.
682    let collected_types = collector.types;
683    for (_, &(ty, _)) in &collected_types {
684        ocx.register_obligation(traits::Obligation::new(
685            tcx,
686            misc_cause.clone(),
687            param_env,
688            ty::ClauseKind::WellFormed(ty.into()),
689        ));
690    }
691
692    // Check that all obligations are satisfied by the implementation's
693    // RPITs.
694    let errors = ocx.evaluate_obligations_error_on_ambiguity();
695    if let TraitErrors::HasErrors(errors) = errors {
696        if let Err(guar) = try_report_async_mismatch(tcx, infcx, &errors, trait_m, impl_m, impl_sig)
697        {
698            return Err(guar);
699        }
700
701        let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
702        return Err(guar);
703    }
704
705    // Finally, resolve all regions. This catches wily misuses of
706    // lifetime parameters.
707    ocx.resolve_regions_and_report_errors(impl_m_def_id, param_env, wf_tys)?;
708
709    let mut remapped_types = DefIdMap::default();
710    for (def_id, (ty, args)) in collected_types {
711        match infcx.fully_resolve(ty) {
712            Ok(ty) => {
713                // `ty` contains free regions that we created earlier while liberating the
714                // trait fn signature. However, projection normalization expects `ty` to
715                // contains `def_id`'s early-bound regions.
716                let id_args = GenericArgs::identity_for_item(tcx, def_id);
717                debug!(?id_args, ?args);
718                let map: FxIndexMap<_, _> = std::iter::zip(args, id_args)
719                    .skip(tcx.generics_of(trait_m.def_id).count())
720                    .filter_map(|(a, b)| Some((a.as_region()?, b.as_region()?)))
721                    .collect();
722                debug!(?map);
723
724                // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound
725                // region args that are synthesized during AST lowering. These are args
726                // that are appended to the parent args (trait and trait method). However,
727                // we're trying to infer the uninstantiated type value of the RPITIT inside
728                // the *impl*, so we can later use the impl's method args to normalize
729                // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`).
730                //
731                // Due to the design of RPITITs, during AST lowering, we have no idea that
732                // an impl method corresponds to a trait method with RPITITs in it. Therefore,
733                // we don't have a list of early-bound region args for the RPITIT in the impl.
734                // Since early region parameters are index-based, we can't just rebase these
735                // (trait method) early-bound region args onto the impl, and there's no
736                // guarantee that the indices from the trait args and impl args line up.
737                // So to fix this, we subtract the number of trait args and add the number of
738                // impl args to *renumber* these early-bound regions to their corresponding
739                // indices in the impl's generic parameters list.
740                //
741                // Also, we only need to account for a difference in trait and impl args,
742                // since we previously enforce that the trait method and impl method have the
743                // same generics.
744                let num_trait_args = impl_trait_ref.args.len();
745                let num_impl_args = tcx.generics_of(impl_m.container_id(tcx)).own_params.len();
746                let ty = match ty.try_fold_with(&mut RemapHiddenTyRegions {
747                    tcx,
748                    map,
749                    num_trait_args,
750                    num_impl_args,
751                    def_id,
752                    impl_m_def_id: impl_m.def_id,
753                    ty,
754                    return_span,
755                }) {
756                    Ok(ty) => ty,
757                    Err(guar) => Ty::new_error(tcx, guar),
758                };
759                remapped_types.insert(def_id, ty::EarlyBinder::bind(tcx, ty));
760            }
761            Err(err) => {
762                // This code path is not reached in any tests, but may be
763                // reachable. If this is triggered, it should be converted to
764                // `span_delayed_bug` and the triggering case turned into a
765                // test.
766                tcx.dcx()
767                    .span_bug(return_span, format!("could not fully resolve: {ty} => {err:?}"));
768            }
769        }
770    }
771
772    // We may not collect all RPITITs that we see in the HIR for a trait signature
773    // because an RPITIT was located within a missing item. Like if we have a sig
774    // returning `-> Missing<impl Sized>`, that gets converted to `-> {type error}`,
775    // and when walking through the signature we end up never collecting the def id
776    // of the `impl Sized`. Insert that here, so we don't ICE later.
777    for assoc_item in tcx.associated_types_for_impl_traits_in_associated_fn(trait_m.def_id) {
778        if !remapped_types.contains_key(assoc_item) {
779            remapped_types.insert(
780                *assoc_item,
781                ty::EarlyBinder::bind(
782                    tcx,
783                    Ty::new_error_with_message(
784                        tcx,
785                        return_span,
786                        "missing synthetic item for RPITIT",
787                    ),
788                ),
789            );
790        }
791    }
792
793    Ok(&*tcx.arena.alloc(remapped_types))
794}
795
796struct ImplTraitInTraitCollector<'a, 'tcx, E> {
797    ocx: &'a ObligationCtxt<'a, 'tcx, E>,
798    types: FxIndexMap<DefId, (Ty<'tcx>, ty::GenericArgsRef<'tcx>)>,
799    span: Span,
800    param_env: ty::ParamEnv<'tcx>,
801    impl_m_id: LocalDefId,
802}
803
804impl<'a, 'tcx, E> ImplTraitInTraitCollector<'a, 'tcx, E>
805where
806    E: FromSolverError<'tcx, NextSolverError<'tcx>>
807        + FromSolverError<'tcx, traits::OldSolverError<'tcx>>,
808{
809    fn new(
810        ocx: &'a ObligationCtxt<'a, 'tcx, E>,
811        span: Span,
812        param_env: ty::ParamEnv<'tcx>,
813        impl_m_id: LocalDefId,
814    ) -> Self {
815        ImplTraitInTraitCollector { ocx, types: FxIndexMap::default(), span, param_env, impl_m_id }
816    }
817}
818
819impl<'tcx, E> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx, E>
820where
821    E: FromSolverError<'tcx, NextSolverError<'tcx>>
822        + FromSolverError<'tcx, traits::OldSolverError<'tcx>>,
823{
824    fn cx(&self) -> TyCtxt<'tcx> {
825        self.ocx.infcx.tcx
826    }
827
828    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
829        if let &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args: proj_args, .. }) =
830            ty.kind()
831            && self.cx().is_impl_trait_in_trait(def_id)
832        {
833            if let Some((ty, _)) = self.types.get(&def_id) {
834                return *ty;
835            }
836            //FIXME(RPITIT): Deny nested RPITIT in args too
837            if proj_args.has_escaping_bound_vars() {
838                ::rustc_middle::util::bug::bug_fmt(format_args!("FIXME(RPITIT): error here"));bug!("FIXME(RPITIT): error here");
839            }
840            // Replace with infer var
841            let infer_ty = self.ocx.infcx.next_ty_var(self.span);
842            self.types.insert(def_id, (infer_ty, proj_args));
843            // Recurse into bounds
844            for (pred, pred_span) in self
845                .cx()
846                .explicit_item_bounds(def_id)
847                .iter_instantiated_copied(self.cx(), proj_args)
848                .map(Unnormalized::skip_norm_wip)
849            {
850                let pred = pred.fold_with(self);
851                let pred = self.ocx.normalize(
852                    &ObligationCause::misc(self.span, self.impl_m_id),
853                    self.param_env,
854                    Unnormalized::new_wip(pred),
855                );
856
857                self.ocx.register_obligation(traits::Obligation::new(
858                    self.cx(),
859                    ObligationCause::new(
860                        self.span,
861                        self.impl_m_id,
862                        ObligationCauseCode::WhereClause(def_id, pred_span),
863                    ),
864                    self.param_env,
865                    pred,
866                ));
867            }
868            infer_ty
869        } else {
870            ty.super_fold_with(self)
871        }
872    }
873}
874
875struct RemapHiddenTyRegions<'tcx> {
876    tcx: TyCtxt<'tcx>,
877    /// Map from early/late params of the impl to identity regions of the RPITIT (GAT)
878    /// in the trait.
879    map: FxIndexMap<ty::Region<'tcx>, ty::Region<'tcx>>,
880    num_trait_args: usize,
881    num_impl_args: usize,
882    /// Def id of the RPITIT (GAT) in the *trait*.
883    def_id: DefId,
884    /// Def id of the impl method which owns the opaque hidden type we're remapping.
885    impl_m_def_id: DefId,
886    /// The hidden type we're remapping. Useful for diagnostics.
887    ty: Ty<'tcx>,
888    /// Span of the return type. Useful for diagnostics.
889    return_span: Span,
890}
891
892impl<'tcx> ty::FallibleTypeFolder<TyCtxt<'tcx>> for RemapHiddenTyRegions<'tcx> {
893    type Error = ErrorGuaranteed;
894
895    fn cx(&self) -> TyCtxt<'tcx> {
896        self.tcx
897    }
898
899    fn try_fold_region(
900        &mut self,
901        region: ty::Region<'tcx>,
902    ) -> Result<ty::Region<'tcx>, Self::Error> {
903        match region.kind() {
904            // Never remap bound regions or `'static`
905            ty::ReBound(..) | ty::ReStatic | ty::ReError(_) => return Ok(region),
906            // We always remap liberated late-bound regions from the function.
907            ty::ReLateParam(_) => {}
908            // Remap early-bound regions as long as they don't come from the `impl` itself,
909            // in which case we don't really need to renumber them.
910            ty::ReEarlyParam(ebr) => {
911                if ebr.index as usize >= self.num_impl_args {
912                    // Remap
913                } else {
914                    return Ok(region);
915                }
916            }
917            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!(
918                "should not have leaked vars or placeholders into hidden type of RPITIT"
919            ),
920        }
921
922        let e = if let Some(id_region) = self.map.get(&region) {
923            if let ty::ReEarlyParam(e) = id_region.kind() {
924                e
925            } else {
926                ::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!(
927                    "expected to map region {region} to early-bound identity region, but got {id_region}"
928                );
929            }
930        } else {
931            let guar = match region.opt_param_def_id(self.tcx, self.impl_m_def_id) {
932                Some(def_id) => {
933                    let return_span = if let &ty::Alias(
934                        _,
935                        ty::AliasTy { kind: ty::Opaque { def_id: opaque_ty_def_id }, .. },
936                    ) = self.ty.kind()
937                    {
938                        self.tcx.def_span(opaque_ty_def_id)
939                    } else {
940                        self.return_span
941                    };
942                    self.tcx
943                        .dcx()
944                        .struct_span_err(
945                            return_span,
946                            "return type captures more lifetimes than trait definition",
947                        )
948                        .with_span_label(self.tcx.def_span(def_id), "this lifetime was captured")
949                        .with_span_note(
950                            self.tcx.def_span(self.def_id),
951                            "hidden type must only reference lifetimes captured by this impl trait",
952                        )
953                        .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))
954                        .emit()
955                }
956                None => {
957                    // This code path is not reached in any tests, but may be
958                    // reachable. If this is triggered, it should be converted
959                    // to `delayed_bug` and the triggering case turned into a
960                    // test.
961                    self.tcx.dcx().bug("should've been able to remap region");
962                }
963            };
964            return Err(guar);
965        };
966
967        Ok(ty::Region::new_early_param(
968            self.tcx,
969            ty::EarlyParamRegion {
970                name: e.name,
971                index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32,
972            },
973        ))
974    }
975}
976
977/// Gets the string for an explicit self declaration, e.g. "self", "&self",
978/// etc.
979fn get_self_string<'tcx, P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> String
980where
981    P: Fn(Ty<'tcx>) -> bool,
982{
983    if is_self_ty(self_arg_ty) {
984        "self".to_owned()
985    } else if let ty::Ref(_, ty, mutbl) = self_arg_ty.kind()
986        && is_self_ty(*ty)
987    {
988        match mutbl {
989            hir::Mutability::Not => "&self".to_owned(),
990            hir::Mutability::Mut => "&mut self".to_owned(),
991        }
992    } else {
993        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("self: {0}", self_arg_ty))
    })format!("self: {self_arg_ty}")
994    }
995}
996
997fn report_trait_method_mismatch<'tcx>(
998    infcx: &InferCtxt<'tcx>,
999    mut cause: ObligationCause<'tcx>,
1000    param_env: ty::ParamEnv<'tcx>,
1001    terr: TypeError<'tcx>,
1002    (trait_m, trait_sig): (ty::AssocItem, ty::FnSig<'tcx>),
1003    (impl_m, impl_sig): (ty::AssocItem, ty::FnSig<'tcx>),
1004    impl_trait_ref: ty::TraitRef<'tcx>,
1005) -> ErrorGuaranteed {
1006    let tcx = infcx.tcx;
1007    let (impl_err_span, trait_err_span) =
1008        extract_spans_for_error_reporting(infcx, terr, &cause, impl_m, trait_m);
1009
1010    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!(
1011        tcx.dcx(),
1012        impl_err_span,
1013        E0053,
1014        "method `{}` has an incompatible type for trait",
1015        trait_m.name()
1016    );
1017    match &terr {
1018        TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
1019            if trait_m.is_method() =>
1020        {
1021            let ty = trait_sig.inputs()[0];
1022            let sugg = get_self_string(ty, |ty| ty == impl_trait_ref.self_ty());
1023
1024            // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
1025            // span points only at the type `Box<Self`>, but we want to cover the whole
1026            // argument pattern and type.
1027            let (sig, body) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1028            let span = tcx
1029                .hir_body_param_idents(body)
1030                .zip(sig.decl.inputs.iter())
1031                .map(|(param_ident, ty)| {
1032                    if let Some(param_ident) = param_ident {
1033                        param_ident.span.to(ty.span)
1034                    } else {
1035                        ty.span
1036                    }
1037                })
1038                .next()
1039                .unwrap_or(impl_err_span);
1040
1041            diag.span_suggestion_verbose(
1042                span,
1043                "change the self-receiver type to match the trait",
1044                sugg,
1045                Applicability::MachineApplicable,
1046            );
1047        }
1048        TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
1049            if trait_sig.inputs().len() == *i {
1050                // Suggestion to change output type. We do not suggest in `async` functions
1051                // to avoid complex logic or incorrect output.
1052                if let ImplItemKind::Fn(sig, _) =
1053                    &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).kind
1054                    && !sig.header.asyncness.is_async()
1055                {
1056                    let msg = "change the output type to match the trait";
1057                    let ap = Applicability::MachineApplicable;
1058                    match sig.decl.output {
1059                        hir::FnRetTy::DefaultReturn(sp) => {
1060                            let sugg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" -> {0}", trait_sig.output()))
    })format!(" -> {}", trait_sig.output());
1061                            diag.span_suggestion_verbose(sp, msg, sugg, ap);
1062                        }
1063                        hir::FnRetTy::Return(hir_ty) => {
1064                            let sugg = trait_sig.output();
1065                            diag.span_suggestion_verbose(hir_ty.span, msg, sugg, ap);
1066                        }
1067                    };
1068                };
1069            } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
1070                diag.span_suggestion_verbose(
1071                    impl_err_span,
1072                    "change the parameter type to match the trait",
1073                    trait_ty,
1074                    Applicability::MachineApplicable,
1075                );
1076            }
1077        }
1078        _ => {}
1079    }
1080
1081    cause.span = impl_err_span;
1082    infcx.err_ctxt().note_type_err(
1083        &mut diag,
1084        &cause,
1085        trait_err_span.map(|sp| (sp, Cow::from("type in trait"), false)),
1086        Some(param_env.and(infer::ValuePairs::PolySigs(ExpectedFound {
1087            expected: ty::Binder::dummy(trait_sig),
1088            found: ty::Binder::dummy(impl_sig),
1089        }))),
1090        terr,
1091        false,
1092        None,
1093    );
1094
1095    diag.emit()
1096}
1097
1098fn check_region_bounds_on_impl_item<'tcx>(
1099    tcx: TyCtxt<'tcx>,
1100    impl_m: ty::AssocItem,
1101    trait_m: ty::AssocItem,
1102    delay: bool,
1103) -> Result<(), ErrorGuaranteed> {
1104    let impl_generics = tcx.generics_of(impl_m.def_id);
1105    let impl_params = impl_generics.own_counts().lifetimes;
1106
1107    let trait_generics = tcx.generics_of(trait_m.def_id);
1108    let trait_params = trait_generics.own_counts().lifetimes;
1109
1110    let Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span }) =
1111        check_number_of_early_bound_regions(
1112            tcx,
1113            impl_m.def_id.expect_local(),
1114            trait_m.def_id,
1115            impl_generics,
1116            impl_params,
1117            trait_generics,
1118            trait_params,
1119        )
1120    else {
1121        return Ok(());
1122    };
1123
1124    if !delay && let Some(guar) = check_region_late_boundedness(tcx, impl_m, trait_m) {
1125        return Err(guar);
1126    }
1127
1128    let reported = tcx
1129        .dcx()
1130        .create_err(LifetimesOrBoundsMismatchOnTrait {
1131            span,
1132            item_kind: impl_m.descr(),
1133            ident: impl_m.ident(tcx),
1134            generics_span,
1135            bounds_span,
1136            where_span,
1137        })
1138        .emit_unless_delay(delay);
1139
1140    Err(reported)
1141}
1142
1143pub(super) struct CheckNumberOfEarlyBoundRegionsError {
1144    pub(super) span: Span,
1145    pub(super) generics_span: Span,
1146    pub(super) bounds_span: Vec<Span>,
1147    pub(super) where_span: Option<Span>,
1148}
1149
1150pub(super) fn check_number_of_early_bound_regions<'tcx>(
1151    tcx: TyCtxt<'tcx>,
1152    impl_def_id: LocalDefId,
1153    trait_def_id: DefId,
1154    impl_generics: &Generics,
1155    impl_params: usize,
1156    trait_generics: &Generics,
1157    trait_params: usize,
1158) -> Result<(), CheckNumberOfEarlyBoundRegionsError> {
1159    {
    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:1159",
                        "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(1159u32),
                        ::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);
1160
1161    // Must have same number of early-bound lifetime parameters.
1162    // Unfortunately, if the user screws up the bounds, then this
1163    // will change classification between early and late. E.g.,
1164    // if in trait we have `<'a,'b:'a>`, and in impl we just have
1165    // `<'a,'b>`, then we have 2 early-bound lifetime parameters
1166    // in trait but 0 in the impl. But if we report "expected 2
1167    // but found 0" it's confusing, because it looks like there
1168    // are zero. Since I don't quite know how to phrase things at
1169    // the moment, give a kind of vague error message.
1170    if trait_params == impl_params {
1171        return Ok(());
1172    }
1173
1174    let span = tcx
1175        .hir_get_generics(impl_def_id)
1176        .expect("expected impl item to have generics or else we can't compare them")
1177        .span;
1178
1179    let mut generics_span = tcx.def_span(trait_def_id);
1180    let mut bounds_span = ::alloc::vec::Vec::new()vec![];
1181    let mut where_span = None;
1182
1183    if let Some(trait_node) = tcx.hir_get_if_local(trait_def_id)
1184        && let Some(trait_generics) = trait_node.generics()
1185    {
1186        generics_span = trait_generics.span;
1187        // FIXME: we could potentially look at the impl's bounds to not point at bounds that
1188        // *are* present in the impl.
1189        for p in trait_generics.predicates {
1190            match p.kind {
1191                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1192                    bounds,
1193                    ..
1194                })
1195                | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1196                    bounds,
1197                    ..
1198                }) => {
1199                    for b in *bounds {
1200                        if let hir::GenericBound::Outlives(lt) = b {
1201                            bounds_span.push(lt.ident.span);
1202                        }
1203                    }
1204                }
1205            }
1206        }
1207        if let Some(impl_node) = tcx.hir_get_if_local(impl_def_id.into())
1208            && let Some(impl_generics) = impl_node.generics()
1209        {
1210            let mut impl_bounds = 0;
1211            for p in impl_generics.predicates {
1212                match p.kind {
1213                    hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1214                        bounds,
1215                        ..
1216                    })
1217                    | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1218                        bounds,
1219                        ..
1220                    }) => {
1221                        for b in *bounds {
1222                            if let hir::GenericBound::Outlives(_) = b {
1223                                impl_bounds += 1;
1224                            }
1225                        }
1226                    }
1227                }
1228            }
1229            if impl_bounds == bounds_span.len() {
1230                bounds_span = ::alloc::vec::Vec::new()vec![];
1231            } else if impl_generics.has_where_clause_predicates {
1232                where_span = Some(impl_generics.where_clause_span);
1233            }
1234        }
1235    }
1236
1237    Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span })
1238}
1239
1240#[allow(unused)]
1241enum LateEarlyMismatch<'tcx> {
1242    EarlyInImpl(DefId, DefId, ty::Region<'tcx>),
1243    LateInImpl(DefId, DefId, ty::Region<'tcx>),
1244}
1245
1246fn check_region_late_boundedness<'tcx>(
1247    tcx: TyCtxt<'tcx>,
1248    impl_m: ty::AssocItem,
1249    trait_m: ty::AssocItem,
1250) -> Option<ErrorGuaranteed> {
1251    if !impl_m.is_fn() {
1252        return None;
1253    }
1254
1255    let (infcx, param_env) = tcx
1256        .infer_ctxt()
1257        .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, impl_m.def_id));
1258
1259    let impl_m_args = infcx.fresh_args_for_item(DUMMY_SP, impl_m.def_id);
1260    let impl_m_sig = tcx.fn_sig(impl_m.def_id).instantiate(tcx, impl_m_args).skip_norm_wip();
1261    let impl_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, impl_m_sig);
1262
1263    let trait_m_args = infcx.fresh_args_for_item(DUMMY_SP, trait_m.def_id);
1264    let trait_m_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_args).skip_norm_wip();
1265    let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_m_sig);
1266
1267    let ocx = ObligationCtxt::new(&infcx);
1268
1269    // Equate the signatures so that we can infer whether a late-bound param was present where
1270    // an early-bound param was expected, since we replace the late-bound lifetimes with
1271    // `ReLateParam`, and early-bound lifetimes with infer vars, so the early-bound args will
1272    // resolve to `ReLateParam` if there is a mismatch.
1273    let Ok(()) = ocx.eq(
1274        &ObligationCause::dummy(),
1275        param_env,
1276        ty::Binder::dummy(trait_m_sig),
1277        ty::Binder::dummy(impl_m_sig),
1278    ) else {
1279        return None;
1280    };
1281
1282    let errors = ocx.try_evaluate_obligations();
1283    if !errors.no_errors() {
1284        return None;
1285    }
1286
1287    let mut mismatched = ::alloc::vec::Vec::new()vec![];
1288
1289    let impl_generics = tcx.generics_of(impl_m.def_id);
1290    for (id_arg, arg) in
1291        std::iter::zip(ty::GenericArgs::identity_for_item(tcx, impl_m.def_id), impl_m_args)
1292    {
1293        if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1294            && let ty::ReVar(vid) = r.kind()
1295            && let r = infcx
1296                .inner
1297                .borrow_mut()
1298                .unwrap_region_constraints()
1299                .opportunistic_resolve_var(tcx, vid)
1300            && let ty::ReLateParam(ty::LateParamRegion {
1301                kind: ty::LateParamRegionKind::Named(trait_param_def_id),
1302                ..
1303            }) = r.kind()
1304            && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1305        {
1306            mismatched.push(LateEarlyMismatch::EarlyInImpl(
1307                impl_generics.region_param(ebr, tcx).def_id,
1308                trait_param_def_id,
1309                id_arg.expect_region(),
1310            ));
1311        }
1312    }
1313
1314    let trait_generics = tcx.generics_of(trait_m.def_id);
1315    for (id_arg, arg) in
1316        std::iter::zip(ty::GenericArgs::identity_for_item(tcx, trait_m.def_id), trait_m_args)
1317    {
1318        if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1319            && let ty::ReVar(vid) = r.kind()
1320            && let r = infcx
1321                .inner
1322                .borrow_mut()
1323                .unwrap_region_constraints()
1324                .opportunistic_resolve_var(tcx, vid)
1325            && let ty::ReLateParam(ty::LateParamRegion {
1326                kind: ty::LateParamRegionKind::Named(impl_param_def_id),
1327                ..
1328            }) = r.kind()
1329            && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1330        {
1331            mismatched.push(LateEarlyMismatch::LateInImpl(
1332                impl_param_def_id,
1333                trait_generics.region_param(ebr, tcx).def_id,
1334                id_arg.expect_region(),
1335            ));
1336        }
1337    }
1338
1339    if mismatched.is_empty() {
1340        return None;
1341    }
1342
1343    let spans: Vec<_> = mismatched
1344        .iter()
1345        .map(|param| {
1346            let (LateEarlyMismatch::EarlyInImpl(impl_param_def_id, ..)
1347            | LateEarlyMismatch::LateInImpl(impl_param_def_id, ..)) = *param;
1348            tcx.def_span(impl_param_def_id)
1349        })
1350        .collect();
1351
1352    let mut diag = tcx
1353        .dcx()
1354        .struct_span_err(spans, "lifetime parameters do not match the trait definition")
1355        .with_note("lifetime parameters differ in whether they are early- or late-bound")
1356        .with_code(E0195);
1357    for mismatch in mismatched {
1358        match mismatch {
1359            LateEarlyMismatch::EarlyInImpl(
1360                impl_param_def_id,
1361                trait_param_def_id,
1362                early_bound_region,
1363            ) => {
1364                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![
1365                    tcx.def_span(impl_param_def_id),
1366                    tcx.def_span(trait_param_def_id),
1367                ]);
1368                multispan
1369                    .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1370                multispan
1371                    .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1372                multispan.push_span_label(
1373                    tcx.def_span(impl_param_def_id),
1374                    ::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)),
1375                );
1376                multispan.push_span_label(
1377                    tcx.def_span(trait_param_def_id),
1378                    ::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)),
1379                );
1380                if let Some(span) = find_region_in_clauses(tcx, impl_m.def_id, early_bound_region) {
1381                    multispan.push_span_label(
1382                        span,
1383                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
                tcx.item_name(impl_param_def_id)))
    })format!(
1384                            "this lifetime bound makes `{}` early-bound",
1385                            tcx.item_name(impl_param_def_id)
1386                        ),
1387                    );
1388                }
1389                diag.span_note(
1390                    multispan,
1391                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
                tcx.item_name(impl_param_def_id)))
    })format!(
1392                        "`{}` differs between the trait and impl",
1393                        tcx.item_name(impl_param_def_id)
1394                    ),
1395                );
1396            }
1397            LateEarlyMismatch::LateInImpl(
1398                impl_param_def_id,
1399                trait_param_def_id,
1400                early_bound_region,
1401            ) => {
1402                let mut multispan = MultiSpan::from_spans(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [tcx.def_span(impl_param_def_id), tcx.def_span(trait_param_def_id)]))vec![
1403                    tcx.def_span(impl_param_def_id),
1404                    tcx.def_span(trait_param_def_id),
1405                ]);
1406                multispan
1407                    .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1408                multispan
1409                    .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1410                multispan.push_span_label(
1411                    tcx.def_span(impl_param_def_id),
1412                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is late-bound",
                tcx.item_name(impl_param_def_id)))
    })format!("`{}` is late-bound", tcx.item_name(impl_param_def_id)),
1413                );
1414                multispan.push_span_label(
1415                    tcx.def_span(trait_param_def_id),
1416                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is early-bound",
                tcx.item_name(trait_param_def_id)))
    })format!("`{}` is early-bound", tcx.item_name(trait_param_def_id)),
1417                );
1418                if let Some(span) = find_region_in_clauses(tcx, trait_m.def_id, early_bound_region)
1419                {
1420                    multispan.push_span_label(
1421                        span,
1422                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
                tcx.item_name(trait_param_def_id)))
    })format!(
1423                            "this lifetime bound makes `{}` early-bound",
1424                            tcx.item_name(trait_param_def_id)
1425                        ),
1426                    );
1427                }
1428                diag.span_note(
1429                    multispan,
1430                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
                tcx.item_name(impl_param_def_id)))
    })format!(
1431                        "`{}` differs between the trait and impl",
1432                        tcx.item_name(impl_param_def_id)
1433                    ),
1434                );
1435            }
1436        }
1437    }
1438
1439    Some(diag.emit())
1440}
1441
1442fn find_region_in_clauses<'tcx>(
1443    tcx: TyCtxt<'tcx>,
1444    def_id: DefId,
1445    early_bound_region: ty::Region<'tcx>,
1446) -> Option<Span> {
1447    for (clause, span) in tcx.explicit_clauses_of(def_id).instantiate_identity(tcx) {
1448        if clause.skip_norm_wip().visit_with(&mut FindRegion(early_bound_region)).is_break() {
1449            return Some(span);
1450        }
1451    }
1452
1453    struct FindRegion<'tcx>(ty::Region<'tcx>);
1454    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindRegion<'tcx> {
1455        type Result = ControlFlow<()>;
1456        fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
1457            if r == self.0 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
1458        }
1459    }
1460
1461    None
1462}
1463
1464#[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(1464u32),
                                    ::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))]
1465fn extract_spans_for_error_reporting<'tcx>(
1466    infcx: &infer::InferCtxt<'tcx>,
1467    terr: TypeError<'_>,
1468    cause: &ObligationCause<'tcx>,
1469    impl_m: ty::AssocItem,
1470    trait_m: ty::AssocItem,
1471) -> (Span, Option<Span>) {
1472    let tcx = infcx.tcx;
1473    let mut impl_args = {
1474        let (sig, _) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1475        sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1476    };
1477
1478    let trait_args = trait_m.def_id.as_local().map(|def_id| {
1479        let (sig, _) = tcx.hir_expect_trait_item(def_id).expect_fn();
1480        sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1481    });
1482
1483    match terr {
1484        TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1485            (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1486        }
1487        _ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
1488    }
1489}
1490
1491fn compare_self_type<'tcx>(
1492    tcx: TyCtxt<'tcx>,
1493    impl_m: ty::AssocItem,
1494    trait_m: ty::AssocItem,
1495    impl_trait_ref: ty::TraitRef<'tcx>,
1496    delay: bool,
1497) -> Result<(), ErrorGuaranteed> {
1498    // Try to give more informative error messages about self typing
1499    // mismatches. Note that any mismatch will also be detected
1500    // below, where we construct a canonical function type that
1501    // includes the self parameter as a normal parameter. It's just
1502    // that the error messages you get out of this code are a bit more
1503    // inscrutable, particularly for cases where one method has no
1504    // self.
1505
1506    let self_string = |method: ty::AssocItem| {
1507        let untransformed_self_ty = match method.container {
1508            ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1509                impl_trait_ref.self_ty()
1510            }
1511            ty::AssocContainer::Trait => tcx.types.self_param,
1512        };
1513        let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip().input(0);
1514        let (infcx, param_env) = tcx
1515            .infer_ctxt()
1516            .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, method.def_id));
1517        let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1518        let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
1519        get_self_string(self_arg_ty, can_eq_self)
1520    };
1521
1522    match (trait_m.is_method(), impl_m.is_method()) {
1523        (false, false) | (true, true) => {}
1524
1525        (false, true) => {
1526            let self_descr = self_string(impl_m);
1527            let impl_m_span = tcx.def_span(impl_m.def_id);
1528            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!(
1529                tcx.dcx(),
1530                impl_m_span,
1531                E0185,
1532                "method `{}` has a `{}` declaration in the impl, but not in the trait",
1533                trait_m.name(),
1534                self_descr
1535            );
1536            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"));
1537            if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1538                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}`"));
1539            } else {
1540                err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1541            }
1542            return Err(err.emit_unless_delay(delay));
1543        }
1544
1545        (true, false) => {
1546            let self_descr = self_string(trait_m);
1547            let impl_m_span = tcx.def_span(impl_m.def_id);
1548            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!(
1549                tcx.dcx(),
1550                impl_m_span,
1551                E0186,
1552                "method `{}` has a `{}` declaration in the trait, but not in the impl",
1553                trait_m.name(),
1554                self_descr
1555            );
1556            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"));
1557            if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1558                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"));
1559            } else {
1560                err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1561            }
1562
1563            return Err(err.emit_unless_delay(delay));
1564        }
1565    }
1566
1567    Ok(())
1568}
1569
1570/// Checks that the number of generics on a given assoc item in a trait impl is the same
1571/// as the number of generics on the respective assoc item in the trait definition.
1572///
1573/// For example this code emits the errors in the following code:
1574/// ```rust,compile_fail
1575/// trait Trait {
1576///     fn foo();
1577///     type Assoc<T>;
1578/// }
1579///
1580/// impl Trait for () {
1581///     fn foo<T>() {}
1582///     //~^ error
1583///     type Assoc = u32;
1584///     //~^ error
1585/// }
1586/// ```
1587///
1588/// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
1589/// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
1590/// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
1591fn compare_number_of_generics<'tcx>(
1592    tcx: TyCtxt<'tcx>,
1593    impl_: ty::AssocItem,
1594    trait_: ty::AssocItem,
1595    delay: bool,
1596) -> Result<(), ErrorGuaranteed> {
1597    let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1598    let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1599
1600    // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
1601    // in `compare_generic_param_kinds` which will give a nicer error message than something like:
1602    // "expected 1 type parameter, found 0 type parameters"
1603    if (trait_own_counts.types + trait_own_counts.consts)
1604        == (impl_own_counts.types + impl_own_counts.consts)
1605    {
1606        return Ok(());
1607    }
1608
1609    // We never need to emit a separate error for RPITITs, since if an RPITIT
1610    // has mismatched type or const generic arguments, then the method that it's
1611    // inheriting the generics from will also have mismatched arguments, and
1612    // we'll report an error for that instead. Delay a bug for safety, though.
1613    if trait_.is_impl_trait_in_trait() {
1614        // FIXME: no tests trigger this. If you find example code that does
1615        // trigger this, please add it to the test suite.
1616        tcx.dcx()
1617            .bug("errors comparing numbers of generics of trait/impl functions were not emitted");
1618    }
1619
1620    let matchings = [
1621        ("type", trait_own_counts.types, impl_own_counts.types),
1622        ("const", trait_own_counts.consts, impl_own_counts.consts),
1623    ];
1624
1625    let item_kind = impl_.descr();
1626
1627    let mut err_occurred = None;
1628    for (kind, trait_count, impl_count) in matchings {
1629        if impl_count != trait_count {
1630            let arg_spans = |item: &ty::AssocItem, generics: &hir::Generics<'_>| {
1631                let mut spans = generics
1632                    .params
1633                    .iter()
1634                    .filter(|p| match p.kind {
1635                        hir::GenericParamKind::Lifetime {
1636                            kind: hir::LifetimeParamKind::Elided(_),
1637                        } => {
1638                            // A fn can have an arbitrary number of extra elided lifetimes for the
1639                            // same signature.
1640                            !item.is_fn()
1641                        }
1642                        _ => true,
1643                    })
1644                    .map(|p| p.span)
1645                    .collect::<Vec<Span>>();
1646                if spans.is_empty() {
1647                    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]
1648                }
1649                spans
1650            };
1651            let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1652                let trait_item = tcx.hir_expect_trait_item(def_id);
1653                let arg_spans: Vec<Span> = arg_spans(&trait_, trait_item.generics);
1654                let impl_trait_spans: Vec<Span> = trait_item
1655                    .generics
1656                    .params
1657                    .iter()
1658                    .filter_map(|p| match p.kind {
1659                        GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1660                        _ => None,
1661                    })
1662                    .collect();
1663                (Some(arg_spans), impl_trait_spans)
1664            } else {
1665                let trait_span = tcx.hir_span_if_local(trait_.def_id);
1666                (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![])
1667            };
1668
1669            let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
1670            let impl_item_impl_trait_spans: Vec<Span> = impl_item
1671                .generics
1672                .params
1673                .iter()
1674                .filter_map(|p| match p.kind {
1675                    GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1676                    _ => None,
1677                })
1678                .collect();
1679            let spans = arg_spans(&impl_, impl_item.generics);
1680            let span = spans.first().copied();
1681
1682            let mut err = tcx.dcx().struct_span_err(
1683                spans,
1684                ::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!(
1685                    "{} `{}` has {} {kind} parameter{} but its trait \
1686                     declaration has {} {kind} parameter{}",
1687                    item_kind,
1688                    trait_.name(),
1689                    impl_count,
1690                    pluralize!(impl_count),
1691                    trait_count,
1692                    pluralize!(trait_count),
1693                    kind = kind,
1694                ),
1695            );
1696            err.code(E0049);
1697
1698            let msg =
1699                ::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),);
1700            if let Some(spans) = trait_spans {
1701                let mut spans = spans.iter();
1702                if let Some(span) = spans.next() {
1703                    err.span_label(*span, msg);
1704                }
1705                for span in spans {
1706                    err.span_label(*span, "");
1707                }
1708            } else {
1709                err.span_label(tcx.def_span(trait_.def_id), msg);
1710            }
1711
1712            if let Some(span) = span {
1713                err.span_label(
1714                    span,
1715                    ::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),),
1716                );
1717            }
1718
1719            for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1720                err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1721            }
1722
1723            let reported = err.emit_unless_delay(delay);
1724            err_occurred = Some(reported);
1725        }
1726    }
1727
1728    if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1729}
1730
1731fn compare_number_of_method_arguments<'tcx>(
1732    tcx: TyCtxt<'tcx>,
1733    impl_m: ty::AssocItem,
1734    trait_m: ty::AssocItem,
1735    delay: bool,
1736) -> Result<(), ErrorGuaranteed> {
1737    let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1738    let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1739    let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
1740    let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1741
1742    if trait_number_args != impl_number_args {
1743        let trait_span = trait_m
1744            .def_id
1745            .as_local()
1746            .and_then(|def_id| {
1747                let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
1748                let pos = trait_number_args.saturating_sub(1);
1749                trait_m_sig.decl.inputs.get(pos).map(|arg| {
1750                    if pos == 0 {
1751                        arg.span
1752                    } else {
1753                        arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1754                    }
1755                })
1756            })
1757            .or_else(|| tcx.hir_span_if_local(trait_m.def_id));
1758
1759        let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1760        let pos = impl_number_args.saturating_sub(1);
1761        let impl_span = impl_m_sig
1762            .decl
1763            .inputs
1764            .get(pos)
1765            .map(|arg| {
1766                if pos == 0 {
1767                    arg.span
1768                } else {
1769                    arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1770                }
1771            })
1772            .unwrap_or_else(|| tcx.def_span(impl_m.def_id));
1773
1774        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!(
1775            tcx.dcx(),
1776            impl_span,
1777            E0050,
1778            "method `{}` has {} but the declaration in trait `{}` has {}",
1779            trait_m.name(),
1780            potentially_plural_count(impl_number_args, "parameter"),
1781            tcx.def_path_str(trait_m.def_id),
1782            trait_number_args
1783        );
1784
1785        if let Some(trait_span) = trait_span {
1786            err.span_label(
1787                trait_span,
1788                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("trait requires {0}",
                potentially_plural_count(trait_number_args, "parameter")))
    })format!(
1789                    "trait requires {}",
1790                    potentially_plural_count(trait_number_args, "parameter")
1791                ),
1792            );
1793        } else {
1794            err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1795        }
1796
1797        err.span_label(
1798            impl_span,
1799            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found {1}",
                potentially_plural_count(trait_number_args, "parameter"),
                impl_number_args))
    })format!(
1800                "expected {}, found {}",
1801                potentially_plural_count(trait_number_args, "parameter"),
1802                impl_number_args
1803            ),
1804        );
1805
1806        // Only emit verbose suggestions when the trait span isn’t local (e.g., cross-crate).
1807        if !trait_m.def_id.is_local() {
1808            let trait_sig = tcx.fn_sig(trait_m.def_id);
1809            let trait_arg_idents = tcx.fn_arg_idents(trait_m.def_id);
1810            let sm = tcx.sess.source_map();
1811            // Find the span of the space between the parentheses in a method.
1812            // fn foo(...) {}
1813            //        ^^^
1814            let impl_inputs_span = if let (Some(first), Some(last)) =
1815                (impl_m_sig.decl.inputs.first(), impl_m_sig.decl.inputs.last())
1816            {
1817                // We have inputs; construct the span from those.
1818                // fn foo( a: i32, b: u32 ) {}
1819                //        ^^^^^^^^^^^^^^^^
1820                let arg_idents = tcx.fn_arg_idents(impl_m.def_id);
1821                let first_lo = arg_idents
1822                    .get(0)
1823                    .and_then(|id| id.map(|id| id.span.lo()))
1824                    .unwrap_or(first.span.lo());
1825                Some(impl_m_sig.span.with_lo(first_lo).with_hi(last.span.hi()))
1826            } else {
1827                // We have no inputs; construct the span to the left of the last parenthesis
1828                // fn foo( ) {}
1829                //        ^
1830                // FIXME: Keep spans for function parentheses around to make this more robust.
1831                sm.span_to_snippet(impl_m_sig.span).ok().and_then(|s| {
1832                    let right_paren = s.as_bytes().iter().rposition(|&b| b == b')')?;
1833                    let pos = impl_m_sig.span.lo() + BytePos(right_paren as u32);
1834                    Some(impl_m_sig.span.with_lo(pos).with_hi(pos))
1835                })
1836            };
1837            let suggestion = match trait_number_args.cmp(&impl_number_args) {
1838                Ordering::Greater => {
1839                    // Span is right before the end parenthesis:
1840                    // fn foo(a: i32 ) {}
1841                    //              ^
1842                    let trait_inputs = trait_sig.skip_binder().inputs().skip_binder();
1843                    let missing = trait_inputs
1844                        .iter()
1845                        .enumerate()
1846                        .skip(impl_number_args)
1847                        .map(|(idx, ty)| {
1848                            let name = trait_arg_idents
1849                                .get(idx)
1850                                .and_then(|ident| *ident)
1851                                .map(|ident| ident.to_string())
1852                                .unwrap_or_else(|| "_".to_string());
1853                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", name, ty))
    })format!("{name}: {ty}")
1854                        })
1855                        .collect::<Vec<_>>();
1856
1857                    if missing.is_empty() {
1858                        None
1859                    } else {
1860                        impl_inputs_span.map(|s| {
1861                            let span = s.shrink_to_hi();
1862                            let prefix = if impl_number_args == 0 { "" } else { ", " };
1863                            let replacement = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}{0}", missing.join(", "),
                prefix))
    })format!("{prefix}{}", missing.join(", "));
1864                            (
1865                                span,
1866                                ::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!(
1867                                    "add the missing parameter{} from the trait",
1868                                    pluralize!(trait_number_args - impl_number_args)
1869                                ),
1870                                replacement,
1871                            )
1872                        })
1873                    }
1874                }
1875                Ordering::Less => impl_inputs_span.and_then(|full| {
1876                    // Span of the arguments that there are too many of:
1877                    // fn foo(a: i32, b: u32) {}
1878                    //              ^^^^^^^^
1879                    let lo = if trait_number_args == 0 {
1880                        full.lo()
1881                    } else {
1882                        impl_m_sig
1883                            .decl
1884                            .inputs
1885                            .get(trait_number_args - 1)
1886                            .map(|arg| arg.span.hi())?
1887                    };
1888                    let span = full.with_lo(lo);
1889                    Some((
1890                        span,
1891                        ::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!(
1892                            "remove the extra parameter{} to match the trait",
1893                            pluralize!(impl_number_args - trait_number_args)
1894                        ),
1895                        String::new(),
1896                    ))
1897                }),
1898                Ordering::Equal => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1899            };
1900            if let Some((span, msg, replacement)) = suggestion {
1901                err.span_suggestion_verbose(span, msg, replacement, Applicability::MaybeIncorrect);
1902            }
1903        }
1904
1905        return Err(err.emit_unless_delay(delay));
1906    }
1907
1908    Ok(())
1909}
1910
1911fn compare_synthetic_generics<'tcx>(
1912    tcx: TyCtxt<'tcx>,
1913    impl_m: ty::AssocItem,
1914    trait_m: ty::AssocItem,
1915    delay: bool,
1916) -> Result<(), ErrorGuaranteed> {
1917    // FIXME(chrisvittal) Clean up this function, list of FIXME items:
1918    //     1. Better messages for the span labels
1919    //     2. Explanation as to what is going on
1920    // If we get here, we already have the same number of generics, so the zip will
1921    // be okay.
1922    let mut error_found = None;
1923    let impl_m_generics = tcx.generics_of(impl_m.def_id);
1924    let trait_m_generics = tcx.generics_of(trait_m.def_id);
1925    let impl_m_type_params =
1926        impl_m_generics.own_params.iter().filter_map(|param| match param.kind {
1927            GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1928            GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1929        });
1930    let trait_m_type_params =
1931        trait_m_generics.own_params.iter().filter_map(|param| match param.kind {
1932            GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1933            GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1934        });
1935    for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1936        iter::zip(impl_m_type_params, trait_m_type_params)
1937    {
1938        if impl_synthetic != trait_synthetic {
1939            let impl_def_id = impl_def_id.expect_local();
1940            let impl_span = tcx.def_span(impl_def_id);
1941            let trait_span = tcx.def_span(trait_def_id);
1942            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!(
1943                tcx.dcx(),
1944                impl_span,
1945                E0643,
1946                "method `{}` has incompatible signature for trait",
1947                trait_m.name()
1948            );
1949            err.span_label(trait_span, "declaration in trait here");
1950            if impl_synthetic {
1951                // The case where the impl method uses `impl Trait` but the trait method uses
1952                // explicit generics
1953                err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1954                try {
1955                    // try taking the name from the trait impl
1956                    // FIXME: this is obviously suboptimal since the name can already be used
1957                    // as another generic argument
1958                    let new_name = tcx.opt_item_name(trait_def_id)?;
1959                    let trait_m = trait_m.def_id.as_local()?;
1960                    let trait_m = tcx.hir_expect_trait_item(trait_m);
1961
1962                    let impl_m = impl_m.def_id.as_local()?;
1963                    let impl_m = tcx.hir_expect_impl_item(impl_m);
1964
1965                    // in case there are no generics, take the spot between the function name
1966                    // and the opening paren of the argument list
1967                    let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1968                    // in case there are generics, just replace them
1969                    let generics_span = impl_m.generics.span.substitute_dummy(new_generics_span);
1970                    // replace with the generics from the trait
1971                    let new_generics =
1972                        tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1973
1974                    err.multipart_suggestion(
1975                        "try changing the `impl Trait` argument to a generic parameter",
1976                        ::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![
1977                            // replace `impl Trait` with `T`
1978                            (impl_span, new_name.to_string()),
1979                            // replace impl method generics with trait method generics
1980                            // This isn't quite right, as users might have changed the names
1981                            // of the generics, but it works for the common case
1982                            (generics_span, new_generics),
1983                        ],
1984                        Applicability::MaybeIncorrect,
1985                    );
1986                };
1987            } else {
1988                // The case where the trait method uses `impl Trait`, but the impl method uses
1989                // explicit generics.
1990                err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1991                try {
1992                    let impl_m = impl_m.def_id.as_local()?;
1993                    let impl_m = tcx.hir_expect_impl_item(impl_m);
1994                    let (sig, _) = impl_m.expect_fn();
1995                    let input_tys = sig.decl.inputs;
1996
1997                    struct Visitor(hir::def_id::LocalDefId);
1998                    impl<'v> intravisit::Visitor<'v> for Visitor {
1999                        type Result = ControlFlow<Span>;
2000                        fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) -> Self::Result {
2001                            if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
2002                                && let Res::Def(DefKind::TyParam, def_id) = path.res
2003                                && def_id == self.0.to_def_id()
2004                            {
2005                                ControlFlow::Break(ty.span)
2006                            } else {
2007                                intravisit::walk_ty(self, ty)
2008                            }
2009                        }
2010                    }
2011
2012                    let span = input_tys
2013                        .iter()
2014                        .find_map(|ty| Visitor(impl_def_id).visit_ty_unambig(ty).break_value())?;
2015
2016                    let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
2017                    let bounds = bounds.first()?.span().to(bounds.last()?.span());
2018                    let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
2019
2020                    err.multipart_suggestion(
2021                        "try removing the generic parameter and using `impl Trait` instead",
2022                        ::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![
2023                            // delete generic parameters
2024                            (impl_m.generics.span, String::new()),
2025                            // replace param usage with `impl Trait`
2026                            (span, format!("impl {bounds}")),
2027                        ],
2028                        Applicability::MaybeIncorrect,
2029                    );
2030                };
2031            }
2032            error_found = Some(err.emit_unless_delay(delay));
2033        }
2034    }
2035    if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
2036}
2037
2038/// Checks that all parameters in the generics of a given assoc item in a trait impl have
2039/// the same kind as the respective generic parameter in the trait def.
2040///
2041/// For example all 4 errors in the following code are emitted here:
2042/// ```rust,ignore (pseudo-Rust)
2043/// trait Foo {
2044///     fn foo<const N: u8>();
2045///     type Bar<const N: u8>;
2046///     fn baz<const N: u32>();
2047///     type Blah<T>;
2048/// }
2049///
2050/// impl Foo for () {
2051///     fn foo<const N: u64>() {}
2052///     //~^ error
2053///     type Bar<const N: u64> = ();
2054///     //~^ error
2055///     fn baz<T>() {}
2056///     //~^ error
2057///     type Blah<const N: i64> = u32;
2058///     //~^ error
2059/// }
2060/// ```
2061///
2062/// This function does not handle lifetime parameters
2063fn compare_generic_param_kinds<'tcx>(
2064    tcx: TyCtxt<'tcx>,
2065    impl_item: ty::AssocItem,
2066    trait_item: ty::AssocItem,
2067    delay: bool,
2068) -> Result<(), ErrorGuaranteed> {
2069    {
    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());
2070
2071    let ty_const_params_of = |def_id| {
2072        tcx.generics_of(def_id).own_params.iter().filter(|param| {
2073            #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. } =>
        true,
    _ => false,
}matches!(
2074                param.kind,
2075                GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
2076            )
2077        })
2078    };
2079
2080    for (param_impl, param_trait) in
2081        iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
2082    {
2083        use GenericParamDefKind::*;
2084        if match (&param_impl.kind, &param_trait.kind) {
2085            (Const { .. }, Const { .. })
2086                if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
2087            {
2088                true
2089            }
2090            (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
2091            // this is exhaustive so that anyone adding new generic param kinds knows
2092            // to make sure this error is reported for them.
2093            (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
2094            (Lifetime { .. }, _) | (_, Lifetime { .. }) => {
2095                ::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`")
2096            }
2097        } {
2098            let param_impl_span = tcx.def_span(param_impl.def_id);
2099            let param_trait_span = tcx.def_span(param_trait.def_id);
2100
2101            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!(
2102                tcx.dcx(),
2103                param_impl_span,
2104                E0053,
2105                "{} `{}` has an incompatible generic parameter for trait `{}`",
2106                impl_item.descr(),
2107                trait_item.name(),
2108                &tcx.def_path_str(tcx.parent(trait_item.def_id))
2109            );
2110
2111            let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
2112                Const { .. } => {
2113                    ::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!(
2114                        "{} const parameter of type `{}`",
2115                        prefix,
2116                        tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip()
2117                    )
2118                }
2119                Type { .. } => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} type parameter", prefix))
    })format!("{prefix} type parameter"),
2120                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!(
2121                    tcx.def_span(param.def_id),
2122                    "lifetime params are expected to be filtered by `ty_const_params_of`"
2123                ),
2124            };
2125
2126            let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
2127            err.span_label(trait_header_span, "");
2128            err.span_label(param_trait_span, make_param_message("expected", param_trait));
2129
2130            let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
2131            err.span_label(impl_header_span, "");
2132            err.span_label(param_impl_span, make_param_message("found", param_impl));
2133
2134            let reported = err.emit_unless_delay(delay);
2135            return Err(reported);
2136        }
2137    }
2138
2139    Ok(())
2140}
2141
2142fn compare_impl_const<'tcx>(
2143    tcx: TyCtxt<'tcx>,
2144    impl_const_item: ty::AssocItem,
2145    trait_const_item: ty::AssocItem,
2146    impl_trait_ref: ty::TraitRef<'tcx>,
2147) -> Result<(), ErrorGuaranteed> {
2148    compare_type_const(tcx, impl_const_item, trait_const_item)?;
2149    compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
2150    compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
2151    check_region_bounds_on_impl_item(tcx, impl_const_item, trait_const_item, false)?;
2152    compare_const_clause_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
2153}
2154
2155fn compare_type_const<'tcx>(
2156    tcx: TyCtxt<'tcx>,
2157    impl_const_item: ty::AssocItem,
2158    trait_const_item: ty::AssocItem,
2159) -> Result<(), ErrorGuaranteed> {
2160    let impl_is_type_const = tcx.is_type_const(impl_const_item.def_id);
2161    let trait_type_const_span = tcx.type_const_span(trait_const_item.def_id);
2162
2163    if let Some(trait_type_const_span) = trait_type_const_span
2164        && !impl_is_type_const
2165    {
2166        return Err(tcx
2167            .dcx()
2168            .struct_span_err(
2169                tcx.def_span(impl_const_item.def_id),
2170                "implementation of a `type const` must also be marked as `type const`",
2171            )
2172            .with_span_note(
2173                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![
2174                    tcx.def_span(trait_const_item.def_id),
2175                    trait_type_const_span,
2176                ]),
2177                "trait declaration of const is marked as `type const`",
2178            )
2179            .emit());
2180    }
2181    Ok(())
2182}
2183
2184/// The equivalent of [compare_method_clause_entailment], but for associated constants
2185/// instead of associated functions.
2186// FIXME(generic_const_items): If possible extract the common parts of
2187// `compare_{type,const}_clause_entailment`.
2188#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("compare_const_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(2188u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_ct")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_ct");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_ct")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_ct");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_trait_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_trait_ref");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ct)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ct)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let impl_ct_def_id = impl_ct.def_id.expect_local();
            let impl_ct_span = tcx.def_span(impl_ct_def_id);
            let trait_to_impl_args =
                GenericArgs::identity_for_item(tcx,
                        impl_ct.def_id).rebase_onto(tcx, impl_ct.container_id(tcx),
                    impl_trait_ref.args);
            let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
            let trait_ty =
                tcx.type_of(trait_ct.def_id).instantiate(tcx,
                    trait_to_impl_args);
            let code =
                ObligationCauseCode::CompareImplItem {
                    impl_item_def_id: impl_ct_def_id,
                    trait_item_def_id: trait_ct.def_id,
                    kind: impl_ct.kind,
                };
            let mut cause =
                ObligationCause::new(impl_ct_span, impl_ct_def_id,
                    code.clone());
            let impl_ct_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: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("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:2257",
                                    "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(2257u32),
                                    ::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:2262",
                                        "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(2262u32),
                                        ::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 let TraitErrors::HasErrors(errors) = errors {
                return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
            }
            ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env,
                [])
        }
    }
}#[instrument(level = "debug", skip(tcx))]
2189fn compare_const_clause_entailment<'tcx>(
2190    tcx: TyCtxt<'tcx>,
2191    impl_ct: ty::AssocItem,
2192    trait_ct: ty::AssocItem,
2193    impl_trait_ref: ty::TraitRef<'tcx>,
2194) -> Result<(), ErrorGuaranteed> {
2195    let impl_ct_def_id = impl_ct.def_id.expect_local();
2196    let impl_ct_span = tcx.def_span(impl_ct_def_id);
2197
2198    // The below is for the most part highly similar to the procedure
2199    // for methods above. It is simpler in many respects, especially
2200    // because we shouldn't really have to deal with lifetimes or
2201    // predicates. In fact some of this should probably be put into
2202    // shared functions because of DRY violations...
2203    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id).rebase_onto(
2204        tcx,
2205        impl_ct.container_id(tcx),
2206        impl_trait_ref.args,
2207    );
2208
2209    // Create a parameter environment that represents the implementation's
2210    // associated const.
2211    let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
2212
2213    let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
2214    let code = ObligationCauseCode::CompareImplItem {
2215        impl_item_def_id: impl_ct_def_id,
2216        trait_item_def_id: trait_ct.def_id,
2217        kind: impl_ct.kind,
2218    };
2219    let mut cause = ObligationCause::new(impl_ct_span, impl_ct_def_id, code.clone());
2220
2221    let impl_ct_clauses = tcx.clauses_of(impl_ct.def_id);
2222    let trait_ct_clauses = tcx.clauses_of(trait_ct.def_id);
2223
2224    // The clauses declared by the impl definition, the trait and the
2225    // associated const in the trait are assumed.
2226    let impl_clauses = tcx.clauses_of(impl_ct_clauses.parent.unwrap());
2227    let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
2228    hybrid_clauses.extend(
2229        trait_ct_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(clause, _)| clause),
2230    );
2231    let hybrid_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
2232
2233    let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_clauses));
2234    let param_env = traits::normalize_param_env_or_error(
2235        tcx,
2236        param_env,
2237        ObligationCause::misc(impl_ct_span, impl_ct_def_id),
2238    );
2239
2240    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2241    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2242
2243    let impl_ct_own_bounds = impl_ct_clauses.instantiate_own_identity();
2244    for (clause, span) in impl_ct_own_bounds {
2245        let cause = ObligationCause::misc(span, impl_ct_def_id);
2246        let clause = ocx.normalize(&cause, param_env, clause);
2247
2248        let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
2249        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
2250    }
2251
2252    // There is no "body" here, so just pass dummy id.
2253    let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
2254    debug!(?impl_ty);
2255
2256    let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
2257    debug!(?trait_ty);
2258
2259    let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
2260
2261    if let Err(terr) = err {
2262        debug!(?impl_ty, ?trait_ty);
2263
2264        // Locate the Span containing just the type of the offending impl
2265        let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
2266        cause.span = ty.span;
2267
2268        let mut diag = struct_span_code_err!(
2269            tcx.dcx(),
2270            cause.span,
2271            E0326,
2272            "implemented const `{}` has an incompatible type for trait",
2273            trait_ct.name()
2274        );
2275
2276        let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
2277            // Add a label to the Span containing just the type of the const
2278            let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
2279            ty.span
2280        });
2281
2282        infcx.err_ctxt().note_type_err(
2283            &mut diag,
2284            &cause,
2285            trait_c_span.map(|span| (span, Cow::from("type in trait"), false)),
2286            Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2287                expected: trait_ty.into(),
2288                found: impl_ty.into(),
2289            }))),
2290            terr,
2291            false,
2292            None,
2293        );
2294        return Err(diag.emit());
2295    };
2296
2297    // Check that all obligations are satisfied by the implementation's
2298    // version.
2299    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2300    if let TraitErrors::HasErrors(errors) = errors {
2301        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2302    }
2303
2304    ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env, [])
2305}
2306
2307#[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(2307u32),
                                    ::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))]
2308fn compare_impl_ty<'tcx>(
2309    tcx: TyCtxt<'tcx>,
2310    impl_ty: ty::AssocItem,
2311    trait_ty: ty::AssocItem,
2312    impl_trait_ref: ty::TraitRef<'tcx>,
2313) -> Result<(), ErrorGuaranteed> {
2314    compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
2315    compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
2316    check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
2317    compare_type_clause_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
2318    check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
2319}
2320
2321/// The equivalent of [compare_method_clause_entailment], but for associated types
2322/// instead of associated functions.
2323#[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(2323u32),
                                    ::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:2351",
                                    "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(2351u32),
                                    ::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:2360",
                                    "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(2360u32),
                                    ::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:2385",
                                    "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(2385u32),
                                    ::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 let TraitErrors::HasErrors(errors) = errors {
                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))]
2324fn compare_type_clause_entailment<'tcx>(
2325    tcx: TyCtxt<'tcx>,
2326    impl_ty: ty::AssocItem,
2327    trait_ty: ty::AssocItem,
2328    impl_trait_ref: ty::TraitRef<'tcx>,
2329) -> Result<(), ErrorGuaranteed> {
2330    let impl_def_id = impl_ty.container_id(tcx);
2331    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
2332        tcx,
2333        impl_def_id,
2334        impl_trait_ref.args,
2335    );
2336
2337    let impl_ty_clauses = tcx.clauses_of(impl_ty.def_id);
2338    let trait_ty_clauses = tcx.clauses_of(trait_ty.def_id);
2339
2340    let impl_ty_own_bounds = impl_ty_clauses.instantiate_own_identity();
2341    // If there are no bounds, then there are no const conditions, so no need to check that here.
2342    if impl_ty_own_bounds.len() == 0 {
2343        // Nothing to check.
2344        return Ok(());
2345    }
2346
2347    // This `DefId` should be used for the `body_def_id` field on each
2348    // `ObligationCause` (and the `FnCtxt`). This is what
2349    // `regionck_item` expects.
2350    let impl_ty_def_id = impl_ty.def_id.expect_local();
2351    debug!(?trait_to_impl_args);
2352
2353    // The clauses declared by the impl definition, the trait and the
2354    // associated type in the trait are assumed.
2355    let impl_clauses = tcx.clauses_of(impl_ty_clauses.parent.unwrap());
2356    let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
2357    hybrid_clauses.extend(
2358        trait_ty_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(predicate, _)| predicate),
2359    );
2360    debug!(?hybrid_clauses);
2361
2362    let impl_ty_span = tcx.def_span(impl_ty_def_id);
2363    let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
2364
2365    let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
2366    if is_conditionally_const {
2367        // Augment the hybrid param-env with the const conditions
2368        // of the impl header and the trait assoc type.
2369        hybrid_clauses.extend(
2370            tcx.const_conditions(impl_ty_clauses.parent.unwrap())
2371                .instantiate_identity(tcx)
2372                .into_iter()
2373                .chain(
2374                    tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
2375                )
2376                .map(|(trait_ref, _)| {
2377                    trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
2378                }),
2379        );
2380    }
2381
2382    let hybrid_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
2383    let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_clauses));
2384    let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
2385    debug!(caller_bounds=?param_env.caller_bounds());
2386
2387    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2388    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2389
2390    for (clause, span) in impl_ty_own_bounds {
2391        let cause = ObligationCause::misc(span, impl_ty_def_id);
2392        let clause = ocx.normalize(&cause, param_env, clause);
2393
2394        let cause = ObligationCause::new(
2395            span,
2396            impl_ty_def_id,
2397            ObligationCauseCode::CompareImplItem {
2398                impl_item_def_id: impl_ty.def_id.expect_local(),
2399                trait_item_def_id: trait_ty.def_id,
2400                kind: impl_ty.kind,
2401            },
2402        );
2403        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
2404    }
2405
2406    if is_conditionally_const {
2407        // Validate the const conditions of the impl associated type.
2408        let impl_ty_own_const_conditions =
2409            tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2410        for (const_condition, span) in impl_ty_own_const_conditions {
2411            let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2412            let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2413
2414            let cause = ObligationCause::new(
2415                span,
2416                impl_ty_def_id,
2417                ObligationCauseCode::CompareImplItem {
2418                    impl_item_def_id: impl_ty_def_id,
2419                    trait_item_def_id: trait_ty.def_id,
2420                    kind: impl_ty.kind,
2421                },
2422            );
2423            ocx.register_obligation(traits::Obligation::new(
2424                tcx,
2425                cause,
2426                param_env,
2427                const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2428            ));
2429        }
2430    }
2431
2432    // Check that all obligations are satisfied by the implementation's
2433    // version.
2434    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2435    if let TraitErrors::HasErrors(errors) = errors {
2436        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2437        return Err(reported);
2438    }
2439
2440    // Finally, resolve all regions. This catches wily misuses of
2441    // lifetime parameters.
2442    ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2443}
2444
2445/// Validate that `ProjectionCandidate`s created for this associated type will
2446/// be valid.
2447///
2448/// Usually given
2449///
2450/// trait X { type Y: Copy } impl X for T { type Y = S; }
2451///
2452/// We are able to normalize `<T as X>::Y` to `S`, and so when we check the
2453/// impl is well-formed we have to prove `S: Copy`.
2454///
2455/// For default associated types the normalization is not possible (the value
2456/// from the impl could be overridden). We also can't normalize generic
2457/// associated types (yet) because they contain bound parameters.
2458#[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(2458u32),
                                    ::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:2470",
                                    "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(2470u32),
                                    ::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:2519",
                                                            "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(2519u32),
                                                            ::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:2542",
                                    "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(2542u32),
                                    ::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 let TraitErrors::HasErrors(errors) = errors {
                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))]
2459pub(super) fn check_type_bounds<'tcx>(
2460    tcx: TyCtxt<'tcx>,
2461    trait_ty: ty::AssocItem,
2462    impl_ty: ty::AssocItem,
2463    impl_trait_ref: ty::TraitRef<'tcx>,
2464) -> Result<(), ErrorGuaranteed> {
2465    // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
2466    // other `Foo` impls are incoherent.
2467    tcx.ensure_result().coherent_trait(impl_trait_ref.def_id)?;
2468
2469    let param_env = tcx.param_env(impl_ty.def_id);
2470    debug!(?param_env);
2471
2472    let container_id = impl_ty.container_id(tcx);
2473    let impl_ty_def_id = impl_ty.def_id.expect_local();
2474    let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2475    let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2476
2477    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2478    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2479
2480    // A synthetic impl Trait for RPITIT desugaring or assoc type for effects desugaring has no HIR,
2481    // which we currently use to get the span for an impl's associated type. Instead, for these,
2482    // use the def_span for the synthesized  associated type.
2483    let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2484        tcx.def_span(impl_ty_def_id)
2485    } else {
2486        match tcx.hir_node_by_def_id(impl_ty_def_id) {
2487            hir::Node::TraitItem(hir::TraitItem {
2488                kind: hir::TraitItemKind::Type(_, Some(ty)),
2489                ..
2490            }) => ty.span,
2491            hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2492            item => span_bug!(
2493                tcx.def_span(impl_ty_def_id),
2494                "cannot call `check_type_bounds` on item: {item:?}",
2495            ),
2496        }
2497    };
2498    let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2499
2500    let normalize_cause = ObligationCause::new(
2501        impl_ty_span,
2502        impl_ty_def_id,
2503        ObligationCauseCode::CheckAssociatedTypeBounds {
2504            impl_item_def_id: impl_ty.def_id.expect_local(),
2505            trait_item_def_id: trait_ty.def_id,
2506        },
2507    );
2508    let mk_cause = |span: Span| {
2509        let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2510        ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2511    };
2512
2513    let mut obligations: Vec<_> = util::elaborate(
2514        tcx,
2515        tcx.explicit_item_bounds(trait_ty.def_id)
2516            .iter_instantiated_copied(tcx, rebased_args)
2517            .map(Unnormalized::skip_norm_wip)
2518            .map(|(concrete_ty_bound, span)| {
2519                debug!(?concrete_ty_bound);
2520                traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2521            }),
2522    )
2523    .collect();
2524
2525    // Only in a const implementation do we need to check that the `[const]` item bounds hold.
2526    if tcx.is_conditionally_const(impl_ty_def_id) {
2527        obligations.extend(util::elaborate(
2528            tcx,
2529            tcx.explicit_implied_const_bounds(trait_ty.def_id)
2530                .iter_instantiated_copied(tcx, rebased_args)
2531                .map(Unnormalized::skip_norm_wip)
2532                .map(|(c, span)| {
2533                    traits::Obligation::new(
2534                        tcx,
2535                        mk_cause(span),
2536                        param_env,
2537                        c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2538                    )
2539                }),
2540        ));
2541    }
2542    debug!(item_bounds=?obligations);
2543
2544    // Normalize predicates with the assumption that the GAT may always normalize
2545    // to its definition type. This should be the param-env we use to *prove* the
2546    // predicate too, but we don't do that because of performance issues.
2547    // See <https://github.com/rust-lang/rust/pull/117542#issue-1976337685>.
2548    let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2549    for obligation in &mut obligations {
2550        match ocx.deeply_normalize(
2551            &normalize_cause,
2552            normalize_param_env,
2553            Unnormalized::new_wip(obligation.predicate),
2554        ) {
2555            Ok(pred) => obligation.predicate = pred,
2556            Err(e) => {
2557                return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2558            }
2559        }
2560    }
2561
2562    // Check that all obligations are satisfied by the implementation's
2563    // version.
2564    ocx.register_obligations(obligations);
2565    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2566    if let TraitErrors::HasErrors(errors) = errors {
2567        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2568        return Err(reported);
2569    }
2570
2571    // Finally, resolve all regions. This catches wily misuses of
2572    // lifetime parameters.
2573    ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2574}
2575
2576/// Install projection predicates that allow GATs to project to their own
2577/// definition types. This is not allowed in general in cases of default
2578/// associated types in trait definitions, or when specialization is involved,
2579/// but is needed when checking these definition types actually satisfy the
2580/// trait bounds of the GAT.
2581///
2582/// # How it works
2583///
2584/// ```ignore (example)
2585/// impl<A, B> Foo<u32> for (A, B) {
2586///     type Bar<C> = Wrapper<A, B, C>
2587/// }
2588/// ```
2589///
2590/// - `impl_trait_ref` would be `<(A, B) as Foo<u32>>`
2591/// - `normalize_impl_ty_args` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
2592/// - `normalize_impl_ty` would be `Wrapper<A, B, ^0.0>`
2593/// - `rebased_args` would be `[(A, B), u32, ^0.0]`, combining the args from
2594///    the *trait* with the generic associated type parameters (as bound vars).
2595///
2596/// A note regarding the use of bound vars here:
2597/// Imagine as an example
2598/// ```
2599/// trait Family {
2600///     type Member<C: Eq>;
2601/// }
2602///
2603/// impl Family for VecFamily {
2604///     type Member<C: Eq> = i32;
2605/// }
2606/// ```
2607/// Here, we would generate
2608/// ```ignore (pseudo-rust)
2609/// forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
2610/// ```
2611///
2612/// when we really would like to generate
2613/// ```ignore (pseudo-rust)
2614/// forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
2615/// ```
2616///
2617/// But, this is probably fine, because although the first clause can be used with types `C` that
2618/// do not implement `Eq`, for it to cause some kind of problem, there would have to be a
2619/// `VecFamily::Member<X>` for some type `X` where `!(X: Eq)`, that appears in the value of type
2620/// `Member<C: Eq> = ....` That type would fail a well-formedness check that we ought to be doing
2621/// elsewhere, which would check that any `<T as Family>::Member<X>` meets the bounds declared in
2622/// the trait (notably, that `X: Eq` and `T: Family`).
2623fn param_env_with_gat_bounds<'tcx>(
2624    tcx: TyCtxt<'tcx>,
2625    impl_ty: ty::AssocItem,
2626    impl_trait_ref: ty::TraitRef<'tcx>,
2627) -> ty::ParamEnv<'tcx> {
2628    let param_env = tcx.param_env(impl_ty.def_id);
2629    let container_id = impl_ty.container_id(tcx);
2630    let mut clauses = param_env.caller_bounds().to_vec();
2631
2632    // for RPITITs, we should install predicates that allow us to project all
2633    // of the RPITITs associated with the same body. This is because checking
2634    // the item bounds of RPITITs often involves nested RPITITs having to prove
2635    // bounds about themselves.
2636    let impl_tys_to_install = match impl_ty.kind {
2637        ty::AssocKind::Type {
2638            data:
2639                ty::AssocTypeData::Rpitit(
2640                    ty::ImplTraitInTraitData::Impl { fn_def_id }
2641                    | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2642                ),
2643        } => tcx
2644            .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2645            .iter()
2646            .map(|def_id| tcx.associated_item(*def_id))
2647            .collect(),
2648        _ => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [impl_ty]))vec![impl_ty],
2649    };
2650
2651    for impl_ty in impl_tys_to_install {
2652        let trait_ty = match impl_ty.container {
2653            ty::AssocContainer::InherentImpl => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
2654            ty::AssocContainer::Trait => impl_ty,
2655            ty::AssocContainer::TraitImpl(Err(_)) => continue,
2656            ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
2657                tcx.associated_item(trait_item_def_id)
2658            }
2659        };
2660
2661        let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind<'tcx>; 8]> =
2662            smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2663        // Extend the impl's identity args with late-bound GAT vars
2664        let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2665            .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2666                GenericParamDefKind::Type { .. } => {
2667                    let kind = ty::BoundTyKind::Param(param.def_id);
2668                    let bound_var = ty::BoundVariableKind::Ty(kind);
2669                    bound_vars.push(bound_var);
2670                    Ty::new_bound(
2671                        tcx,
2672                        ty::INNERMOST,
2673                        ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2674                    )
2675                    .into()
2676                }
2677                GenericParamDefKind::Lifetime => {
2678                    let kind = ty::BoundRegionKind::Named(param.def_id);
2679                    let bound_var = ty::BoundVariableKind::Region(kind);
2680                    bound_vars.push(bound_var);
2681                    ty::Region::new_bound(
2682                        tcx,
2683                        ty::INNERMOST,
2684                        ty::BoundRegion {
2685                            var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2686                            kind,
2687                        },
2688                    )
2689                    .into()
2690                }
2691                GenericParamDefKind::Const { .. } => {
2692                    let bound_var = ty::BoundVariableKind::Const;
2693                    bound_vars.push(bound_var);
2694                    ty::Const::new_bound(
2695                        tcx,
2696                        ty::INNERMOST,
2697                        ty::BoundConst::new(ty::BoundVar::from_usize(bound_vars.len() - 1)),
2698                    )
2699                    .into()
2700                }
2701            });
2702        // When checking something like
2703        //
2704        // trait X { type Y: PartialEq<<Self as X>::Y> }
2705        // impl X for T { default type Y = S; }
2706        //
2707        // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
2708        // we want <T as X>::Y to normalize to S. This is valid because we are
2709        // checking the default value specifically here. Add this equality to the
2710        // ParamEnv for normalization specifically.
2711        let normalize_impl_ty =
2712            tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args).skip_norm_wip();
2713        let rebased_args =
2714            normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2715        let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2716
2717        match normalize_impl_ty.kind() {
2718            &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
2719                if def_id == trait_ty.def_id && args == rebased_args =>
2720            {
2721                // Don't include this predicate if the projected type is
2722                // exactly the same as the projection. This can occur in
2723                // (somewhat dubious) code like this:
2724                //
2725                // impl<T> X for T where T: X { type Y = <T as X>::Y; }
2726            }
2727            _ => clauses.push(
2728                ty::Binder::bind_with_vars(
2729                    ty::ProjectionPredicate {
2730                        projection_term: ty::AliasTerm::new_from_def_id(
2731                            tcx,
2732                            trait_ty.def_id,
2733                            rebased_args,
2734                        ),
2735                        term: normalize_impl_ty.into(),
2736                    },
2737                    bound_vars,
2738                )
2739                .upcast(tcx),
2740            ),
2741        };
2742    }
2743
2744    ty::ParamEnv::new(tcx.mk_clauses(&clauses))
2745}
2746
2747/// Manually check here that `async fn foo()` wasn't matched against `fn foo()`,
2748/// and extract a better error if so.
2749fn try_report_async_mismatch<'tcx>(
2750    tcx: TyCtxt<'tcx>,
2751    infcx: &InferCtxt<'tcx>,
2752    errors: &[FulfillmentError<'tcx>],
2753    trait_m: ty::AssocItem,
2754    impl_m: ty::AssocItem,
2755    impl_sig: ty::FnSig<'tcx>,
2756) -> Result<(), ErrorGuaranteed> {
2757    if !tcx.asyncness(trait_m.def_id).is_async() {
2758        return Ok(());
2759    }
2760
2761    let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id: async_future_def_id }, .. }) =
2762        *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2763    else {
2764        ::rustc_middle::util::bug::bug_fmt(format_args!("expected `async fn` to return an RPITIT"));bug!("expected `async fn` to return an RPITIT");
2765    };
2766
2767    for error in errors {
2768        if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2769            && def_id == async_future_def_id
2770            && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2771            && let Some(proj) = proj.no_bound_vars()
2772            && infcx.can_eq(
2773                error.root_obligation.param_env,
2774                proj.term.expect_type(),
2775                impl_sig.output(),
2776            )
2777        {
2778            // FIXME: We should suggest making the fn `async`, but extracting
2779            // the right span is a bit difficult.
2780            return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2781                span: tcx.def_span(impl_m.def_id),
2782                method_name: tcx.item_ident(impl_m.def_id),
2783                trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
2784            }));
2785        }
2786    }
2787
2788    Ok(())
2789}