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::Visitor;
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, Ty, TyCtxt, TypeFoldable,
18    TypeFolder, TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
19    Unnormalized, Upcast,
20};
21use rustc_span::{BytePos, DUMMY_SP, Span, bug, span_bug};
22use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
23use rustc_trait_selection::infer::InferCtxtExt;
24use rustc_trait_selection::regions::InferCtxtRegionExt;
25use rustc_trait_selection::solve::NextSolverError;
26use rustc_trait_selection::traits::{
27    self, FromSolverError, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
28};
29use tracing::{debug, instrument};
30
31use super::potentially_plural_count;
32use crate::diagnostics::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture};
33
34pub(super) mod refine;
35
36/// Call the query `tcx.compare_impl_item()` directly instead.
37pub(super) fn compare_impl_item(
38    tcx: TyCtxt<'_>,
39    impl_item_def_id: LocalDefId,
40) -> Result<(), ErrorGuaranteed> {
41    let impl_item = tcx.associated_item(impl_item_def_id);
42    let trait_item = tcx.associated_item(impl_item.expect_trait_impl()?);
43    let impl_trait_ref =
44        tcx.impl_trait_ref(impl_item.container_id(tcx)).instantiate_identity().skip_norm_wip();
45    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:45",
                        "rustc_hir_analysis::check::compare_impl_item",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                        ::tracing_core::__macro_support::Option::Some(45u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("impl_trait_ref")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("impl_trait_ref");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?impl_trait_ref);
46
47    match impl_item.kind {
48        ty::AssocKind::Fn { .. } => compare_impl_method(tcx, impl_item, trait_item, impl_trait_ref),
49        ty::AssocKind::Type { .. } => compare_impl_ty(tcx, impl_item, trait_item, impl_trait_ref),
50        ty::AssocKind::Const { .. } => {
51            compare_impl_const(tcx, impl_item, trait_item, impl_trait_ref)
52        }
53    }
54}
55
56/// Checks that a method from an impl conforms to the signature of
57/// the same method as declared in the trait.
58///
59/// # Parameters
60///
61/// - `impl_m`: type of the method we are checking
62/// - `trait_m`: the method in the trait
63/// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
64{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("compare_impl_method",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(64u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_m")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_m");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_m")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_m");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_trait_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_trait_ref");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_m)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_m)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let impl_m_def_id = impl_m.def_id.expect_local();
            let impl_m_span = tcx.def_span(impl_m_def_id);
            let cause =
                ObligationCause::new(impl_m_span, impl_m_def_id,
                    ObligationCauseCode::CompareImplItem {
                        impl_item_def_id: impl_m_def_id,
                        trait_item_def_id: trait_m.def_id,
                        kind: impl_m.kind,
                    });
            let impl_def_id = impl_m.container_id(tcx);
            let trait_to_impl_args =
                GenericArgs::identity_for_item(tcx,
                        impl_m.def_id).rebase_onto(tcx, impl_m.container_id(tcx),
                    impl_trait_ref.args);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:204",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(204u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_to_impl_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_to_impl_args");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_to_impl_args)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let impl_m_clauses = tcx.clauses_of(impl_m.def_id);
            let trait_m_clauses = tcx.clauses_of(trait_m.def_id);
            let impl_clauses = tcx.clauses_of(impl_m_clauses.parent.unwrap());
            let mut hybrid_clauses =
                impl_clauses.instantiate_identity(tcx).clauses;
            hybrid_clauses.extend(trait_m_clauses.instantiate_own(tcx,
                        trait_to_impl_args).map(|(clause, _)| clause));
            let is_conditionally_const =
                tcx.is_conditionally_const(impl_m.def_id);
            if is_conditionally_const {
                hybrid_clauses.extend(tcx.const_conditions(impl_def_id).instantiate_identity(tcx).into_iter().chain(tcx.const_conditions(trait_m.def_id).instantiate_own(tcx,
                                trait_to_impl_args)).map(|(trait_ref, _)|
                            {
                                trait_ref.to_host_effect_clause(tcx,
                                    ty::BoundConstness::Maybe)
                            }));
            }
            let hybrid_clauses =
                hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
            let normalize_cause =
                traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
            let param_env = ty::ParamEnv::new(tcx, 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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:256",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(256u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("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 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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:332",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(332u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_sig")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_sig");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_sig)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let trait_sig =
                tcx.fn_sig(trait_m.def_id).instantiate(tcx,
                        trait_to_impl_args).skip_norm_wip();
            let trait_sig =
                tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
            wf_tys.extend(trait_sig.inputs_and_output.iter());
            let trait_sig =
                ocx.normalize(&norm_cause, param_env,
                    Unnormalized::new_wip(trait_sig));
            wf_tys.extend(trait_sig.inputs_and_output.iter());
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:345",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(345u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_sig")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_sig");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_sig)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
            if let Err(terr) = result {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:357",
                                        "rustc_hir_analysis::check::compare_impl_item",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                        ::tracing_core::__macro_support::Option::Some(357u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                        ::tracing_core::field::FieldSet::new(&["message",
                                                        {
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("impl_sig")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("impl_sig");
                                                            NAME.as_str()
                                                        },
                                                        {
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("trait_sig")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("trait_sig");
                                                            NAME.as_str()
                                                        },
                                                        {
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("terr")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("terr");
                                                            NAME.as_str()
                                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("sub_types failed")
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_sig)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_sig)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&terr)
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                let emitted =
                    report_trait_method_mismatch(infcx, cause, param_env, terr,
                        (trait_m, trait_sig), (impl_m, impl_sig), impl_trait_ref);
                return Err(emitted);
            }
            if !(impl_sig, trait_sig).references_error() {
                for ty in unnormalized_impl_sig.inputs_and_output {
                    ocx.register_obligation(traits::Obligation::new(infcx.tcx,
                            cause.clone(), param_env,
                            ty::ClauseKind::WellFormed(ty.into())));
                }
            }
            let errors = ocx.evaluate_obligations_error_on_ambiguity();
            if 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))]
174fn compare_method_clause_entailment<'tcx>(
175    tcx: TyCtxt<'tcx>,
176    impl_m: ty::AssocItem,
177    trait_m: ty::AssocItem,
178    impl_trait_ref: ty::TraitRef<'tcx>,
179) -> Result<(), ErrorGuaranteed> {
180    // This node-id should be used for the `body_def_id` field on each
181    // `ObligationCause` (and the `FnCtxt`).
182    //
183    // FIXME(@lcnr): remove that after removing `cause.body_def_id` from
184    // obligations.
185    let impl_m_def_id = impl_m.def_id.expect_local();
186    let impl_m_span = tcx.def_span(impl_m_def_id);
187    let cause = ObligationCause::new(
188        impl_m_span,
189        impl_m_def_id,
190        ObligationCauseCode::CompareImplItem {
191            impl_item_def_id: impl_m_def_id,
192            trait_item_def_id: trait_m.def_id,
193            kind: impl_m.kind,
194        },
195    );
196
197    // Create mapping from trait method to impl method.
198    let impl_def_id = impl_m.container_id(tcx);
199    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
200        tcx,
201        impl_m.container_id(tcx),
202        impl_trait_ref.args,
203    );
204    debug!(?trait_to_impl_args);
205
206    let impl_m_clauses = tcx.clauses_of(impl_m.def_id);
207    let trait_m_clauses = tcx.clauses_of(trait_m.def_id);
208
209    // This is the only tricky bit of the new way we check implementation methods
210    // We need to build a set of clauses where only the method-level bounds
211    // are from the trait and we assume all other bounds from the implementation
212    // to be previously satisfied.
213    //
214    // We then register the obligations from the impl_m and check to see
215    // if all constraints hold.
216    let impl_clauses = tcx.clauses_of(impl_m_clauses.parent.unwrap());
217    let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
218    hybrid_clauses
219        .extend(trait_m_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(clause, _)| clause));
220
221    let is_conditionally_const = tcx.is_conditionally_const(impl_m.def_id);
222    if is_conditionally_const {
223        // Augment the hybrid param-env with the const conditions
224        // of the impl header and the trait method.
225        hybrid_clauses.extend(
226            tcx.const_conditions(impl_def_id)
227                .instantiate_identity(tcx)
228                .into_iter()
229                .chain(
230                    tcx.const_conditions(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args),
231                )
232                .map(|(trait_ref, _)| {
233                    trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
234                }),
235        );
236    }
237
238    let hybrid_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
239    let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
240    let param_env = ty::ParamEnv::new(tcx, hybrid_clauses);
241    // NOTE(-Zhigher-ranked-assumptions): The `hybrid_preds`
242    // should be well-formed. However, using them may result in
243    // region errors as we currently don't track placeholder
244    // assumptions.
245    //
246    // We eagerly normalize the where-clauses here while ignoring
247    // region constraints. This means we can then use where-bounds
248    // whose normalization results in placeholder errors further
249    // down without getting any errors.
250    //
251    // This should be sound to do so as the only region errors here
252    // should be due to missing implied bounds.
253    //
254    // cc trait-system-refactor-initiative/issues/166.
255    let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
256    debug!(?param_env);
257
258    let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
259    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
260
261    // Create obligations for each clause declared by the impl
262    // definition in the context of the hybrid param-env. This makes
263    // sure that the impl's method's where clauses are not more
264    // restrictive than the trait's method (and the impl itself).
265    let impl_m_own_bounds = impl_m_clauses.instantiate_own_identity();
266    for (clause, span) in impl_m_own_bounds {
267        let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
268        let clause = ocx.normalize(&normalize_cause, param_env, clause);
269
270        let cause = ObligationCause::new(
271            span,
272            impl_m_def_id,
273            ObligationCauseCode::CompareImplItem {
274                impl_item_def_id: impl_m_def_id,
275                trait_item_def_id: trait_m.def_id,
276                kind: impl_m.kind,
277            },
278        );
279        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
280    }
281
282    // If we're within a const implementation, we need to make sure that the method
283    // does not assume stronger `[const]` bounds than the trait definition.
284    //
285    // This registers the `[const]` bounds of the impl method, which we will prove
286    // using the hybrid param-env that we earlier augmented with the const conditions
287    // from the impl header and trait method declaration.
288    if is_conditionally_const {
289        for (const_condition, span) in
290            tcx.const_conditions(impl_m.def_id).instantiate_own_identity()
291        {
292            let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
293            let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
294
295            let cause = ObligationCause::new(
296                span,
297                impl_m_def_id,
298                ObligationCauseCode::CompareImplItem {
299                    impl_item_def_id: impl_m_def_id,
300                    trait_item_def_id: trait_m.def_id,
301                    kind: impl_m.kind,
302                },
303            );
304            ocx.register_obligation(traits::Obligation::new(
305                tcx,
306                cause,
307                param_env,
308                const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
309            ));
310        }
311    }
312
313    // We now need to check that the signature of the impl method is
314    // compatible with that of the trait method. We do this by
315    // checking that `impl_fty <: trait_fty`.
316    //
317    // FIXME: We manually instantiate the trait method here as we need
318    // to manually compute its implied bounds. Otherwise this could just
319    // be `ocx.sub(impl_sig, trait_sig)`.
320
321    let mut wf_tys = FxIndexSet::default();
322
323    let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars(
324        impl_m_span,
325        BoundRegionConversionTime::HigherRankedType,
326        tcx.fn_sig(impl_m.def_id).instantiate_identity().skip_norm_wip(),
327    );
328
329    let norm_cause = ObligationCause::misc(impl_m_span, impl_m_def_id);
330    let impl_sig =
331        ocx.normalize(&norm_cause, param_env, Unnormalized::new_wip(unnormalized_impl_sig));
332    debug!(?impl_sig);
333
334    let trait_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args).skip_norm_wip();
335    let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
336
337    // Next, add all inputs and output as well-formed tys. Importantly,
338    // we have to do this before normalization, since the normalized ty may
339    // not contain the input parameters. See issue #87748.
340    wf_tys.extend(trait_sig.inputs_and_output.iter());
341    let trait_sig = ocx.normalize(&norm_cause, param_env, Unnormalized::new_wip(trait_sig));
342    // We also have to add the normalized trait signature
343    // as we don't normalize during implied bounds computation.
344    wf_tys.extend(trait_sig.inputs_and_output.iter());
345    debug!(?trait_sig);
346
347    // FIXME: We'd want to keep more accurate spans than "the method signature" when
348    // processing the comparison between the trait and impl fn, but we sadly lose them
349    // and point at the whole signature when a trait bound or specific input or output
350    // type would be more appropriate. In other places we have a `Vec<Span>`
351    // corresponding to their `Vec<Predicate>`, but we don't have that here.
352    // Fixing this would improve the output of test `issue-83765.rs`.
353    // There's the same issue in compare_eii code.
354    let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
355
356    if let Err(terr) = result {
357        debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
358
359        let emitted = report_trait_method_mismatch(
360            infcx,
361            cause,
362            param_env,
363            terr,
364            (trait_m, trait_sig),
365            (impl_m, impl_sig),
366            impl_trait_ref,
367        );
368        return Err(emitted);
369    }
370
371    if !(impl_sig, trait_sig).references_error() {
372        for ty in unnormalized_impl_sig.inputs_and_output {
373            ocx.register_obligation(traits::Obligation::new(
374                infcx.tcx,
375                cause.clone(),
376                param_env,
377                ty::ClauseKind::WellFormed(ty.into()),
378            ));
379        }
380    }
381
382    // Check that all obligations are satisfied by the implementation's
383    // version.
384    let errors = ocx.evaluate_obligations_error_on_ambiguity();
385    if let TraitErrors::HasErrors(errors) = errors {
386        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
387        return Err(reported);
388    }
389
390    // Finally, resolve all regions. This catches wily misuses of
391    // lifetime parameters.
392    let errors = infcx.resolve_regions(impl_m_def_id, param_env, wf_tys);
393    if !errors.is_empty() {
394        return Err(infcx
395            .tainted_by_errors()
396            .unwrap_or_else(|| infcx.err_ctxt().report_region_errors(impl_m_def_id, &errors)));
397    }
398
399    Ok(())
400}
401
402struct RemapLateParam<'tcx> {
403    tcx: TyCtxt<'tcx>,
404    mapping: FxIndexMap<ty::LateParamRegionKind, ty::LateParamRegionKind>,
405}
406
407impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateParam<'tcx> {
408    fn cx(&self) -> TyCtxt<'tcx> {
409        self.tcx
410    }
411
412    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
413        if let ty::ReLateParam(fr) = r.kind() {
414            ty::Region::new_late_param(
415                self.tcx,
416                fr.scope,
417                self.mapping.get(&fr.kind).copied().unwrap_or(fr.kind),
418            )
419        } else {
420            r
421        }
422    }
423}
424
425/// Given a method def-id in an impl, compare the method signature of the impl
426/// against the trait that it's implementing. In doing so, infer the hidden types
427/// that this method's signature provides to satisfy each return-position `impl Trait`
428/// in the trait signature.
429///
430/// The method is also responsible for making sure that the hidden types for each
431/// RPITIT actually satisfy the bounds of the `impl Trait`, i.e. that if we infer
432/// `impl Trait = Foo`, that `Foo: Trait` holds.
433///
434/// For example, given the sample code:
435///
436/// ```
437/// use std::ops::Deref;
438///
439/// trait Foo {
440///     fn bar() -> impl Deref<Target = impl Sized>;
441///     //          ^- RPITIT #1        ^- RPITIT #2
442/// }
443///
444/// impl Foo for () {
445///     fn bar() -> Box<String> { Box::new(String::new()) }
446/// }
447/// ```
448///
449/// The hidden types for the RPITITs in `bar` would be inferred to:
450///     * `impl Deref` (RPITIT #1) = `Box<String>`
451///     * `impl Sized` (RPITIT #2) = `String`
452///
453/// The relationship between these two types is straightforward in this case, but
454/// may be more tenuously connected via other `impl`s and normalization rules for
455/// cases of more complicated nested RPITITs.
456{}
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("collect_return_position_impl_trait_in_trait_tys",
                                "rustc_hir_analysis::check::compare_impl_item",
                                ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                ::tracing_core::__macro_support::Option::Some(456u32),
                                ::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_def_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("impl_m_def_id");
                                                    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_def_id)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

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