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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: (Span, Option<Span>) = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = infcx.tcx;
            let mut impl_args =
                {
                    let (sig, _) =
                        tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
                    sig.decl.inputs.iter().map(|t|
                                t.span).chain(iter::once(sig.decl.output.span()))
                };
            let trait_args =
                trait_m.def_id.as_local().map(|def_id|
                        {
                            let (sig, _) =
                                tcx.hir_expect_trait_item(def_id).expect_fn();
                            sig.decl.inputs.iter().map(|t|
                                        t.span).chain(iter::once(sig.decl.output.span()))
                        });
            match terr {
                TypeError::ArgumentMutability(i) |
                    TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
                    (impl_args.nth(i).unwrap(),
                        trait_args.and_then(|mut args| args.nth(i)))
                }
                _ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
            }
        }
    }
}#[instrument(level = "debug", skip(infcx))]
1465fn extract_spans_for_error_reporting<'tcx>(
1466    infcx: &infer::InferCtxt<'tcx>,
1467    terr: TypeError<'_>,
1468    cause: &ObligationCause<'tcx>,
1469    impl_m: ty::AssocItem,
1470    trait_m: ty::AssocItem,
1471) -> (Span, Option<Span>) {
1472    let tcx = infcx.tcx;
1473    let mut impl_args = {
1474        let (sig, _) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1475        sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1476    };
1477
1478    let trait_args = trait_m.def_id.as_local().map(|def_id| {
1479        let (sig, _) = tcx.hir_expect_trait_item(def_id).expect_fn();
1480        sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1481    });
1482
1483    match terr {
1484        TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1485            (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1486        }
1487        _ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
1488    }
1489}
1490
1491fn compare_self_type<'tcx>(
1492    tcx: TyCtxt<'tcx>,
1493    impl_m: ty::AssocItem,
1494    trait_m: ty::AssocItem,
1495    impl_trait_ref: ty::TraitRef<'tcx>,
1496    delay: bool,
1497) -> Result<(), ErrorGuaranteed> {
1498    // Try to give more informative error messages about self typing
1499    // mismatches. Note that any mismatch will also be detected
1500    // below, where we construct a canonical function type that
1501    // includes the self parameter as a normal parameter. It's just
1502    // that the error messages you get out of this code are a bit more
1503    // inscrutable, particularly for cases where one method has no
1504    // self.
1505
1506    let self_string = |method: ty::AssocItem| {
1507        let untransformed_self_ty = match method.container {
1508            ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1509                impl_trait_ref.self_ty()
1510            }
1511            ty::AssocContainer::Trait => tcx.types.self_param,
1512        };
1513        let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip().input(0);
1514        let (infcx, param_env) = tcx
1515            .infer_ctxt()
1516            .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, method.def_id));
1517        let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1518        let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
1519        get_self_string(self_arg_ty, can_eq_self)
1520    };
1521
1522    match (trait_m.is_method(), impl_m.is_method()) {
1523        (false, false) | (true, true) => {}
1524
1525        (false, true) => {
1526            let self_descr = self_string(impl_m);
1527            let impl_m_span = tcx.def_span(impl_m.def_id);
1528            let mut err = {
    tcx.dcx().struct_span_err(impl_m_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("method `{0}` has a `{1}` declaration in the impl, but not in the trait",
                            trait_m.name(), self_descr))
                })).with_code(E0185)
}struct_span_code_err!(
1529                tcx.dcx(),
1530                impl_m_span,
1531                E0185,
1532                "method `{}` has a `{}` declaration in the impl, but not in the trait",
1533                trait_m.name(),
1534                self_descr
1535            );
1536            err.span_label(impl_m_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` used in impl", self_descr))
    })format!("`{self_descr}` used in impl"));
1537            if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1538                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("trait method declared without `{0}`",
                self_descr))
    })format!("trait method declared without `{self_descr}`"));
1539            } else {
1540                err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1541            }
1542            return Err(err.emit_err_unless_delay(delay));
1543        }
1544
1545        (true, false) => {
1546            let self_descr = self_string(trait_m);
1547            let impl_m_span = tcx.def_span(impl_m.def_id);
1548            let mut err = {
    tcx.dcx().struct_span_err(impl_m_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("method `{0}` has a `{1}` declaration in the trait, but not in the impl",
                            trait_m.name(), self_descr))
                })).with_code(E0186)
}struct_span_code_err!(
1549                tcx.dcx(),
1550                impl_m_span,
1551                E0186,
1552                "method `{}` has a `{}` declaration in the trait, but not in the impl",
1553                trait_m.name(),
1554                self_descr
1555            );
1556            err.span_label(impl_m_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}` in impl",
                self_descr))
    })format!("expected `{self_descr}` in impl"));
1557            if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1558                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` used in trait", self_descr))
    })format!("`{self_descr}` used in trait"));
1559            } else {
1560                err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1561            }
1562
1563            return Err(err.emit_err_unless_delay(delay));
1564        }
1565    }
1566
1567    Ok(())
1568}
1569
1570/// Checks that the number of generics on a given assoc item in a trait impl is the same
1571/// as the number of generics on the respective assoc item in the trait definition.
1572///
1573/// For example this code emits the errors in the following code:
1574/// ```rust,compile_fail
1575/// trait Trait {
1576///     fn foo();
1577///     type Assoc<T>;
1578/// }
1579///
1580/// impl Trait for () {
1581///     fn foo<T>() {}
1582///     //~^ error
1583///     type Assoc = u32;
1584///     //~^ error
1585/// }
1586/// ```
1587///
1588/// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
1589/// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
1590/// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
1591fn compare_number_of_generics<'tcx>(
1592    tcx: TyCtxt<'tcx>,
1593    impl_: ty::AssocItem,
1594    trait_: ty::AssocItem,
1595    delay: bool,
1596) -> Result<(), ErrorGuaranteed> {
1597    let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1598    let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1599
1600    // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
1601    // in `compare_generic_param_kinds` which will give a nicer error message than something like:
1602    // "expected 1 type parameter, found 0 type parameters"
1603    if (trait_own_counts.types + trait_own_counts.consts)
1604        == (impl_own_counts.types + impl_own_counts.consts)
1605    {
1606        return Ok(());
1607    }
1608
1609    // We never need to emit a separate error for RPITITs, since if an RPITIT
1610    // has mismatched type or const generic arguments, then the method that it's
1611    // inheriting the generics from will also have mismatched arguments, and
1612    // we'll report an error for that instead. Delay a bug for safety, though.
1613    if trait_.is_impl_trait_in_trait() {
1614        // FIXME: no tests trigger this. If you find example code that does
1615        // trigger this, please add it to the test suite.
1616        tcx.dcx()
1617            .bug("errors comparing numbers of generics of trait/impl functions were not emitted");
1618    }
1619
1620    let matchings = [
1621        ("type", trait_own_counts.types, impl_own_counts.types),
1622        ("const", trait_own_counts.consts, impl_own_counts.consts),
1623    ];
1624
1625    let item_kind = impl_.descr();
1626
1627    let mut err_occurred = None;
1628    for (kind, trait_count, impl_count) in matchings {
1629        if impl_count != trait_count {
1630            let arg_spans = |item: &ty::AssocItem, generics: &hir::Generics<'_>| {
1631                let mut spans = generics
1632                    .params
1633                    .iter()
1634                    .filter(|p| match p.kind {
1635                        hir::GenericParamKind::Lifetime {
1636                            kind: hir::LifetimeParamKind::Elided(_),
1637                        } => {
1638                            // A fn can have an arbitrary number of extra elided lifetimes for the
1639                            // same signature.
1640                            !item.is_fn()
1641                        }
1642                        _ => true,
1643                    })
1644                    .map(|p| p.span)
1645                    .collect::<Vec<Span>>();
1646                if spans.is_empty() {
1647                    spans = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [generics.span]))vec![generics.span]
1648                }
1649                spans
1650            };
1651            let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1652                let trait_item = tcx.hir_expect_trait_item(def_id);
1653                let arg_spans: Vec<Span> = arg_spans(&trait_, trait_item.generics);
1654                let impl_trait_spans: Vec<Span> = trait_item
1655                    .generics
1656                    .params
1657                    .iter()
1658                    .filter_map(|p| match p.kind {
1659                        GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1660                        _ => None,
1661                    })
1662                    .collect();
1663                (Some(arg_spans), impl_trait_spans)
1664            } else {
1665                let trait_span = tcx.hir_span_if_local(trait_.def_id);
1666                (trait_span.map(|s| ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [s]))vec![s]), ::alloc::vec::Vec::new()vec![])
1667            };
1668
1669            let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
1670            let impl_item_impl_trait_spans: Vec<Span> = impl_item
1671                .generics
1672                .params
1673                .iter()
1674                .filter_map(|p| match p.kind {
1675                    GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1676                    _ => None,
1677                })
1678                .collect();
1679            let spans = arg_spans(&impl_, impl_item.generics);
1680            let span = spans.first().copied();
1681
1682            let mut err = tcx.dcx().struct_span_err(
1683                spans,
1684                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}` has {2} {6} parameter{3} but its trait declaration has {4} {6} parameter{5}",
                item_kind, trait_.name(), impl_count,
                if impl_count == 1 { "" } else { "s" }, trait_count,
                if trait_count == 1 { "" } else { "s" }, kind))
    })format!(
1685                    "{} `{}` has {} {kind} parameter{} but its trait \
1686                     declaration has {} {kind} parameter{}",
1687                    item_kind,
1688                    trait_.name(),
1689                    impl_count,
1690                    pluralize!(impl_count),
1691                    trait_count,
1692                    pluralize!(trait_count),
1693                    kind = kind,
1694                ),
1695            );
1696            err.code(E0049);
1697
1698            let msg =
1699                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {1} {2} parameter{0}",
                if trait_count == 1 { "" } else { "s" }, trait_count, kind))
    })format!("expected {trait_count} {kind} parameter{}", pluralize!(trait_count),);
1700            if let Some(spans) = trait_spans {
1701                let mut spans = spans.iter();
1702                if let Some(span) = spans.next() {
1703                    err.span_label(*span, msg);
1704                }
1705                for span in spans {
1706                    err.span_label(*span, "");
1707                }
1708            } else {
1709                err.span_label(tcx.def_span(trait_.def_id), msg);
1710            }
1711
1712            if let Some(span) = span {
1713                err.span_label(
1714                    span,
1715                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("found {0} {1} parameter{2}",
                impl_count, kind, if impl_count == 1 { "" } else { "s" }))
    })format!("found {} {} parameter{}", impl_count, kind, pluralize!(impl_count),),
1716                );
1717            }
1718
1719            for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1720                err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1721            }
1722
1723            let guar = err.emit_err_unless_delay(delay);
1724            err_occurred = Some(guar);
1725        }
1726    }
1727
1728    if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1729}
1730
1731fn compare_number_of_method_arguments<'tcx>(
1732    tcx: TyCtxt<'tcx>,
1733    impl_m: ty::AssocItem,
1734    trait_m: ty::AssocItem,
1735    delay: bool,
1736) -> Result<(), ErrorGuaranteed> {
1737    let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1738    let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1739    let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
1740    let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1741
1742    if trait_number_args != impl_number_args {
1743        let trait_span = trait_m
1744            .def_id
1745            .as_local()
1746            .and_then(|def_id| {
1747                let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
1748                let pos = trait_number_args.saturating_sub(1);
1749                trait_m_sig.decl.inputs.get(pos).map(|arg| {
1750                    if pos == 0 {
1751                        arg.span
1752                    } else {
1753                        arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1754                    }
1755                })
1756            })
1757            .or_else(|| tcx.hir_span_if_local(trait_m.def_id));
1758
1759        let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1760        let pos = impl_number_args.saturating_sub(1);
1761        let impl_span = impl_m_sig
1762            .decl
1763            .inputs
1764            .get(pos)
1765            .map(|arg| {
1766                if pos == 0 {
1767                    arg.span
1768                } else {
1769                    arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1770                }
1771            })
1772            .unwrap_or_else(|| tcx.def_span(impl_m.def_id));
1773
1774        let mut err = {
    tcx.dcx().struct_span_err(impl_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("method `{0}` has {1} but the declaration in trait `{2}` has {3}",
                            trait_m.name(),
                            potentially_plural_count(impl_number_args, "parameter"),
                            tcx.def_path_str(trait_m.def_id), trait_number_args))
                })).with_code(E0050)
}struct_span_code_err!(
1775            tcx.dcx(),
1776            impl_span,
1777            E0050,
1778            "method `{}` has {} but the declaration in trait `{}` has {}",
1779            trait_m.name(),
1780            potentially_plural_count(impl_number_args, "parameter"),
1781            tcx.def_path_str(trait_m.def_id),
1782            trait_number_args
1783        );
1784
1785        if let Some(trait_span) = trait_span {
1786            err.span_label(
1787                trait_span,
1788                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("trait requires {0}",
                potentially_plural_count(trait_number_args, "parameter")))
    })format!(
1789                    "trait requires {}",
1790                    potentially_plural_count(trait_number_args, "parameter")
1791                ),
1792            );
1793        } else {
1794            err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1795        }
1796
1797        err.span_label(
1798            impl_span,
1799            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found {1}",
                potentially_plural_count(trait_number_args, "parameter"),
                impl_number_args))
    })format!(
1800                "expected {}, found {}",
1801                potentially_plural_count(trait_number_args, "parameter"),
1802                impl_number_args
1803            ),
1804        );
1805
1806        // Only emit verbose suggestions when the trait span isn’t local (e.g., cross-crate).
1807        if !trait_m.def_id.is_local() {
1808            let trait_sig = tcx.fn_sig(trait_m.def_id);
1809            let trait_arg_idents = tcx.fn_arg_idents(trait_m.def_id);
1810            let sm = tcx.sess.source_map();
1811            // Find the span of the space between the parentheses in a method.
1812            // fn foo(...) {}
1813            //        ^^^
1814            let impl_inputs_span = if let (Some(first), Some(last)) =
1815                (impl_m_sig.decl.inputs.first(), impl_m_sig.decl.inputs.last())
1816            {
1817                // We have inputs; construct the span from those.
1818                // fn foo( a: i32, b: u32 ) {}
1819                //        ^^^^^^^^^^^^^^^^
1820                let arg_idents = tcx.fn_arg_idents(impl_m.def_id);
1821                let first_lo = arg_idents
1822                    .get(0)
1823                    .and_then(|id| id.map(|id| id.span.lo()))
1824                    .unwrap_or(first.span.lo());
1825                Some(impl_m_sig.span.with_lo(first_lo).with_hi(last.span.hi()))
1826            } else {
1827                // We have no inputs; construct the span to the left of the last parenthesis
1828                // fn foo( ) {}
1829                //        ^
1830                // FIXME: Keep spans for function parentheses around to make this more robust.
1831                sm.span_to_snippet(impl_m_sig.span).ok().and_then(|s| {
1832                    let right_paren = s.as_bytes().iter().rposition(|&b| b == b')')?;
1833                    let pos = impl_m_sig.span.lo() + BytePos(right_paren as u32);
1834                    Some(impl_m_sig.span.with_lo(pos).with_hi(pos))
1835                })
1836            };
1837            let suggestion = match trait_number_args.cmp(&impl_number_args) {
1838                Ordering::Greater => {
1839                    // Span is right before the end parenthesis:
1840                    // fn foo(a: i32 ) {}
1841                    //              ^
1842                    let trait_inputs = trait_sig.skip_binder().inputs().skip_binder();
1843                    let missing = trait_inputs
1844                        .iter()
1845                        .enumerate()
1846                        .skip(impl_number_args)
1847                        .map(|(idx, ty)| {
1848                            let name = trait_arg_idents
1849                                .get(idx)
1850                                .and_then(|ident| *ident)
1851                                .map(|ident| ident.to_string())
1852                                .unwrap_or_else(|| "_".to_string());
1853                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", name, ty))
    })format!("{name}: {ty}")
1854                        })
1855                        .collect::<Vec<_>>();
1856
1857                    if missing.is_empty() {
1858                        None
1859                    } else {
1860                        impl_inputs_span.map(|s| {
1861                            let span = s.shrink_to_hi();
1862                            let prefix = if impl_number_args == 0 { "" } else { ", " };
1863                            let replacement = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}{0}", missing.join(", "),
                prefix))
    })format!("{prefix}{}", missing.join(", "));
1864                            (
1865                                span,
1866                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add the missing parameter{0} from the trait",
                if trait_number_args - impl_number_args == 1 {
                    ""
                } else { "s" }))
    })format!(
1867                                    "add the missing parameter{} from the trait",
1868                                    pluralize!(trait_number_args - impl_number_args)
1869                                ),
1870                                replacement,
1871                            )
1872                        })
1873                    }
1874                }
1875                Ordering::Less => impl_inputs_span.and_then(|full| {
1876                    // Span of the arguments that there are too many of:
1877                    // fn foo(a: i32, b: u32) {}
1878                    //              ^^^^^^^^
1879                    let lo = if trait_number_args == 0 {
1880                        full.lo()
1881                    } else {
1882                        impl_m_sig
1883                            .decl
1884                            .inputs
1885                            .get(trait_number_args - 1)
1886                            .map(|arg| arg.span.hi())?
1887                    };
1888                    let span = full.with_lo(lo);
1889                    Some((
1890                        span,
1891                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("remove the extra parameter{0} to match the trait",
                if impl_number_args - trait_number_args == 1 {
                    ""
                } else { "s" }))
    })format!(
1892                            "remove the extra parameter{} to match the trait",
1893                            pluralize!(impl_number_args - trait_number_args)
1894                        ),
1895                        String::new(),
1896                    ))
1897                }),
1898                Ordering::Equal => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1899            };
1900            if let Some((span, msg, replacement)) = suggestion {
1901                err.span_suggestion_verbose(span, msg, replacement, Applicability::MaybeIncorrect);
1902            }
1903        }
1904
1905        return Err(err.emit_err_unless_delay(delay));
1906    }
1907
1908    Ok(())
1909}
1910
1911fn compare_synthetic_generics<'tcx>(
1912    tcx: TyCtxt<'tcx>,
1913    impl_m: ty::AssocItem,
1914    trait_m: ty::AssocItem,
1915    delay: bool,
1916) -> Result<(), ErrorGuaranteed> {
1917    // FIXME(chrisvittal) Clean up this function, list of FIXME items:
1918    //     1. Better messages for the span labels
1919    //     2. Explanation as to what is going on
1920    // If we get here, we already have the same number of generics, so the zip will
1921    // be okay.
1922    let mut error_found = None;
1923    let impl_m_generics = tcx.generics_of(impl_m.def_id);
1924    let trait_m_generics = tcx.generics_of(trait_m.def_id);
1925    let impl_m_type_params =
1926        impl_m_generics.own_params.iter().filter_map(|param| match param.kind {
1927            GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1928            GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1929        });
1930    let trait_m_type_params =
1931        trait_m_generics.own_params.iter().filter_map(|param| match param.kind {
1932            GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1933            GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1934        });
1935    for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1936        iter::zip(impl_m_type_params, trait_m_type_params)
1937    {
1938        if impl_synthetic != trait_synthetic {
1939            let impl_def_id = impl_def_id.expect_local();
1940            let impl_span = tcx.def_span(impl_def_id);
1941            let trait_span = tcx.def_span(trait_def_id);
1942            let mut err = {
    tcx.dcx().struct_span_err(impl_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("method `{0}` has incompatible signature for trait",
                            trait_m.name()))
                })).with_code(E0643)
}struct_span_code_err!(
1943                tcx.dcx(),
1944                impl_span,
1945                E0643,
1946                "method `{}` has incompatible signature for trait",
1947                trait_m.name()
1948            );
1949            err.span_label(trait_span, "declaration in trait here");
1950            if impl_synthetic {
1951                // The case where the impl method uses `impl Trait` but the trait method uses
1952                // explicit generics
1953                err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1954                try {
1955                    // try taking the name from the trait impl
1956                    // FIXME: this is obviously suboptimal since the name can already be used
1957                    // as another generic argument
1958                    let new_name = tcx.opt_item_name(trait_def_id)?;
1959                    let trait_m = trait_m.def_id.as_local()?;
1960                    let trait_m = tcx.hir_expect_trait_item(trait_m);
1961
1962                    let impl_m = impl_m.def_id.as_local()?;
1963                    let impl_m = tcx.hir_expect_impl_item(impl_m);
1964
1965                    // in case there are no generics, take the spot between the function name
1966                    // and the opening paren of the argument list
1967                    let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1968                    // in case there are generics, just replace them
1969                    let generics_span = impl_m.generics.span.substitute_dummy(new_generics_span);
1970                    // replace with the generics from the trait
1971                    let new_generics =
1972                        tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1973
1974                    err.multipart_suggestion(
1975                        "try changing the `impl Trait` argument to a generic parameter",
1976                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(impl_span, new_name.to_string()), (generics_span, new_generics)]))vec![
1977                            // replace `impl Trait` with `T`
1978                            (impl_span, new_name.to_string()),
1979                            // replace impl method generics with trait method generics
1980                            // This isn't quite right, as users might have changed the names
1981                            // of the generics, but it works for the common case
1982                            (generics_span, new_generics),
1983                        ],
1984                        Applicability::MaybeIncorrect,
1985                    );
1986                };
1987            } else {
1988                // The case where the trait method uses `impl Trait`, but the impl method uses
1989                // explicit generics.
1990                err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1991                try {
1992                    let impl_m = impl_m.def_id.as_local()?;
1993                    let impl_m = tcx.hir_expect_impl_item(impl_m);
1994                    let (sig, _) = impl_m.expect_fn();
1995                    let input_tys = sig.decl.inputs;
1996
1997                    struct Visitor(hir::def_id::LocalDefId);
1998                    impl<'v> intravisit::Visitor<'v> for Visitor {
1999                        type Result = ControlFlow<Span>;
2000                        fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) -> Self::Result {
2001                            if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
2002                                && let Res::Def(DefKind::TyParam, def_id) = path.res
2003                                && def_id == self.0.to_def_id()
2004                            {
2005                                ControlFlow::Break(ty.span)
2006                            } else {
2007                                intravisit::walk_ty(self, ty)
2008                            }
2009                        }
2010                    }
2011
2012                    let span = input_tys
2013                        .iter()
2014                        .find_map(|ty| Visitor(impl_def_id).visit_ty_unambig(ty).break_value())?;
2015
2016                    let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
2017                    let bounds = bounds.first()?.span().to(bounds.last()?.span());
2018                    let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
2019
2020                    err.multipart_suggestion(
2021                        "try removing the generic parameter and using `impl Trait` instead",
2022                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(impl_m.generics.span, String::new()),
                (span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("impl {0}", bounds))
                        }))]))vec![
2023                            // delete generic parameters
2024                            (impl_m.generics.span, String::new()),
2025                            // replace param usage with `impl Trait`
2026                            (span, format!("impl {bounds}")),
2027                        ],
2028                        Applicability::MaybeIncorrect,
2029                    );
2030                };
2031            }
2032            error_found = Some(err.emit_err_unless_delay(delay));
2033        }
2034    }
2035    if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
2036}
2037
2038/// Checks that corresponding generic parameters in a trait item and its impl
2039/// are both type parameters or both const parameters.
2040fn compare_generic_param_kinds<'tcx>(
2041    tcx: TyCtxt<'tcx>,
2042    impl_item: ty::AssocItem,
2043    trait_item: ty::AssocItem,
2044    delay: bool,
2045) -> Result<(), ErrorGuaranteed> {
2046    {
    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());
2047
2048    let ty_const_params_of = |def_id| {
2049        tcx.generics_of(def_id).own_params.iter().filter(|param| {
2050            #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. } =>
        true,
    _ => false,
}matches!(
2051                param.kind,
2052                GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
2053            )
2054        })
2055    };
2056
2057    for (param_impl, param_trait) in
2058        iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
2059    {
2060        use GenericParamDefKind::*;
2061        if match (&param_impl.kind, &param_trait.kind) {
2062            (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
2063            // this is exhaustive so that anyone adding new generic param kinds knows
2064            // to make sure this error is reported for them.
2065            (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
2066            (Lifetime { .. }, _) | (_, Lifetime { .. }) => {
2067                ::rustc_span::macros::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`")
2068            }
2069        } {
2070            let param_impl_span = tcx.def_span(param_impl.def_id);
2071            let param_trait_span = tcx.def_span(param_trait.def_id);
2072
2073            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!(
2074                tcx.dcx(),
2075                param_impl_span,
2076                E0053,
2077                "{} `{}` has an incompatible generic parameter for trait `{}`",
2078                impl_item.descr(),
2079                trait_item.name(),
2080                tcx.def_path_str(tcx.parent(trait_item.def_id))
2081            );
2082
2083            let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
2084                Const { .. } => {
2085                    ::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!(
2086                        "{} const parameter of type `{}`",
2087                        prefix,
2088                        tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip()
2089                    )
2090                }
2091                Type { .. } => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} type parameter", prefix))
    })format!("{prefix} type parameter"),
2092                Lifetime { .. } => ::rustc_span::macros::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!(
2093                    tcx.def_span(param.def_id),
2094                    "lifetime params are expected to be filtered by `ty_const_params_of`"
2095                ),
2096            };
2097
2098            let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
2099            err.span_context(trait_header_span);
2100            err.span_label(param_trait_span, make_param_message("expected", param_trait));
2101
2102            let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
2103            err.span_context(impl_header_span);
2104            err.span_label(param_impl_span, make_param_message("found", param_impl));
2105
2106            let guar = err.emit_err_unless_delay(delay);
2107            return Err(guar);
2108        }
2109    }
2110
2111    Ok(())
2112}
2113
2114/// Checks that corresponding const generic parameters in a trait item and its
2115/// impl have compatible types.
2116fn compare_const_generic_param_types<'tcx>(
2117    tcx: TyCtxt<'tcx>,
2118    impl_item: ty::AssocItem,
2119    trait_item: ty::AssocItem,
2120    impl_trait_ref: ty::TraitRef<'tcx>,
2121    delay: bool,
2122) -> Result<(), ErrorGuaranteed> {
2123    {
    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());
2124    use GenericParamDefKind::*;
2125
2126    let const_params_of = |def_id| {
2127        tcx.generics_of(def_id).own_params.iter().filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    Const { .. } => true,
    _ => false,
}matches!(param.kind, Const { .. }))
2128    };
2129
2130    // Map the trait item's generic parameters into the impl item's generic context.
2131    let trait_to_impl_args = ty::GenericArgs::identity_for_item(tcx, impl_item.def_id).rebase_onto(
2132        tcx,
2133        impl_item.container_id(tcx),
2134        impl_trait_ref.args,
2135    );
2136    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2137    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2138    let param_env = tcx.param_env(impl_item.def_id);
2139
2140    let param_iter =
2141        iter::zip(const_params_of(impl_item.def_id), const_params_of(trait_item.def_id));
2142
2143    for (param_impl, param_trait) in param_iter {
2144        let param_impl_ty_span = tcx.ty_span(param_impl.def_id.expect_local());
2145
2146        let cause = ObligationCause::new(
2147            param_impl_ty_span,
2148            impl_item.def_id.expect_local(),
2149            ObligationCauseCode::CompareImplItem {
2150                impl_item_def_id: impl_item.def_id.expect_local(),
2151                trait_item_def_id: trait_item.def_id,
2152                kind: impl_item.kind,
2153            },
2154        );
2155
2156        let impl_ty =
2157            ocx.normalize(&cause, param_env, tcx.type_of(param_impl.def_id).instantiate_identity());
2158
2159        let trait_ty = ocx.normalize(
2160            &cause,
2161            param_env,
2162            tcx.type_of(param_trait.def_id).instantiate(tcx, trait_to_impl_args),
2163        );
2164
2165        match ocx.eq(&cause, param_env, trait_ty, impl_ty) {
2166            // Despite returning `Ok` all may not be well. As such, outside of this
2167            // loop we invoke `ocx.evaluate_obligations_error_on_ambiguity()` to check
2168            // for any other errors that may have occurred.
2169            Ok(_) => {}
2170            Err(terr) => {
2171                let param_trait_ty_span =
2172                    param_trait.def_id.as_local().map(|def_id| tcx.ty_span(def_id));
2173                let mut diag = {
    tcx.dcx().struct_span_err(param_impl_ty_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} `{1}` has an incompatible type for const generic parameter",
                            trait_item.descr(), trait_item.name()))
                })).with_code(E0053)
}struct_span_code_err!(
2174                    tcx.dcx(),
2175                    param_impl_ty_span,
2176                    E0053,
2177                    "{} `{}` has an incompatible type for const generic parameter",
2178                    trait_item.descr(),
2179                    trait_item.name(),
2180                );
2181                infcx.err_ctxt().note_type_err(
2182                    &mut diag,
2183                    &cause,
2184                    param_trait_ty_span.map(|span| (span, Cow::from("type in trait"), false)),
2185                    Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2186                        expected: trait_ty.into(),
2187                        found: impl_ty.into(),
2188                    }))),
2189                    terr,
2190                    false,
2191                    None,
2192                );
2193                let reported = diag.emit_err_unless_delay(delay);
2194                return Err(reported);
2195            }
2196        }
2197    }
2198
2199    if let TraitErrors::HasErrors(errors) = ocx.evaluate_obligations_error_on_ambiguity() {
2200        Err(infcx.err_ctxt().report_fulfillment_errors(errors))
2201    } else {
2202        Ok(())
2203    }
2204}
2205
2206fn compare_impl_const<'tcx>(
2207    tcx: TyCtxt<'tcx>,
2208    impl_const_item: ty::AssocItem,
2209    trait_const_item: ty::AssocItem,
2210    impl_trait_ref: ty::TraitRef<'tcx>,
2211) -> Result<(), ErrorGuaranteed> {
2212    compare_const_directness(tcx, impl_const_item, trait_const_item)?;
2213    compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
2214    compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
2215    compare_const_generic_param_types(
2216        tcx,
2217        impl_const_item,
2218        trait_const_item,
2219        impl_trait_ref,
2220        false,
2221    )?;
2222    check_region_bounds_on_impl_item(tcx, impl_const_item, trait_const_item, false)?;
2223    compare_const_clause_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
2224}
2225
2226pub(super) fn compare_const_directness<'tcx>(
2227    tcx: TyCtxt<'tcx>,
2228    impl_const_item: ty::AssocItem,
2229    trait_const_item: ty::AssocItem,
2230) -> Result<(), ErrorGuaranteed> {
2231    let trait_is_gca = tcx.is_always_gca(trait_const_item.def_id);
2232    let impl_is_gca = tcx.const_of_item(impl_const_item.def_id).is_some();
2233
2234    if trait_is_gca == impl_is_gca {
2235        return Ok(());
2236    }
2237    // feature(gca_const_items) is allowed to impl non-GCA traits with a GCA const
2238    if tcx.features().gca_const_items() && !trait_is_gca && impl_is_gca {
2239        return Ok(());
2240    }
2241
2242    let guar = if trait_is_gca {
2243        tcx.dcx()
2244            .struct_span_err(
2245                tcx.def_span(impl_const_item.def_id),
2246                "implementation of a `#[rustc_always_gca]` must have a `gca!` RHS",
2247            )
2248            .with_span_note(
2249                tcx.def_span(trait_const_item.def_id),
2250                "trait declaration of const is marked as `#[rustc_always_gca]`",
2251            )
2252            .emit_err()
2253    } else {
2254        tcx.dcx()
2255            .struct_span_err(
2256                tcx.def_span(impl_const_item.def_id),
2257                "implementation of a regular const cannot have a `gca!` RHS",
2258            )
2259            .with_span_note(
2260                tcx.def_span(trait_const_item.def_id),
2261                "trait declaration of const is not marked as `#[rustc_always_gca]`",
2262            )
2263            .emit_err()
2264    };
2265    Err(guar)
2266}
2267
2268/// The equivalent of [compare_method_clause_entailment], but for associated constants
2269/// instead of associated functions.
2270// FIXME(generic_const_items): If possible extract the common parts of
2271// `compare_{type,const}_clause_entailment`.
2272{}
#[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/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2272u32),
                                    ::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/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2338",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2338u32),
                                    ::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/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2341",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2341u32),
                                    ::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/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2346",
                                        "rustc_hir_analysis::check::compare_impl_item",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                        ::tracing_core::__macro_support::Option::Some(2346u32),
                                        ::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_err());
            };
            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))]
2273fn compare_const_clause_entailment<'tcx>(
2274    tcx: TyCtxt<'tcx>,
2275    impl_ct: ty::AssocItem,
2276    trait_ct: ty::AssocItem,
2277    impl_trait_ref: ty::TraitRef<'tcx>,
2278) -> Result<(), ErrorGuaranteed> {
2279    let impl_ct_def_id = impl_ct.def_id.expect_local();
2280    let impl_ct_span = tcx.def_span(impl_ct_def_id);
2281
2282    // The below is for the most part highly similar to the procedure
2283    // for methods above. It is simpler in many respects, especially
2284    // because we shouldn't really have to deal with lifetimes or
2285    // predicates. In fact some of this should probably be put into
2286    // shared functions because of DRY violations...
2287    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id).rebase_onto(
2288        tcx,
2289        impl_ct.container_id(tcx),
2290        impl_trait_ref.args,
2291    );
2292
2293    // Create a parameter environment that represents the implementation's
2294    // associated const.
2295    let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
2296
2297    let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
2298    let code = ObligationCauseCode::CompareImplItem {
2299        impl_item_def_id: impl_ct_def_id,
2300        trait_item_def_id: trait_ct.def_id,
2301        kind: impl_ct.kind,
2302    };
2303    let mut cause = ObligationCause::new(impl_ct_span, impl_ct_def_id, code.clone());
2304
2305    let impl_ct_clauses = tcx.clauses_of(impl_ct.def_id);
2306    let trait_ct_clauses = tcx.clauses_of(trait_ct.def_id);
2307
2308    // The clauses declared by the impl definition, the trait and the
2309    // associated const in the trait are assumed.
2310    let impl_clauses = tcx.clauses_of(impl_ct_clauses.parent.unwrap());
2311    let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
2312    hybrid_clauses.extend(
2313        trait_ct_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(clause, _)| clause),
2314    );
2315    let hybrid_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
2316
2317    let param_env = ty::ParamEnv::new(tcx, hybrid_clauses);
2318    let param_env = traits::normalize_param_env_or_error(
2319        tcx,
2320        param_env,
2321        ObligationCause::misc(impl_ct_span, impl_ct_def_id),
2322    );
2323
2324    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2325    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2326
2327    let impl_ct_own_bounds = impl_ct_clauses.instantiate_own_identity();
2328    for (clause, span) in impl_ct_own_bounds {
2329        let cause = ObligationCause::misc(span, impl_ct_def_id);
2330        let clause = ocx.normalize(&cause, param_env, clause);
2331
2332        let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
2333        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
2334    }
2335
2336    // There is no "body" here, so just pass dummy id.
2337    let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
2338    debug!(?impl_ty);
2339
2340    let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
2341    debug!(?trait_ty);
2342
2343    let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
2344
2345    if let Err(terr) = err {
2346        debug!(?impl_ty, ?trait_ty);
2347
2348        // Locate the Span containing just the type of the offending impl
2349        let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
2350        cause.span = ty.span;
2351
2352        let mut diag = struct_span_code_err!(
2353            tcx.dcx(),
2354            cause.span,
2355            E0326,
2356            "implemented const `{}` has an incompatible type for trait",
2357            trait_ct.name()
2358        );
2359
2360        let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
2361            // Add a label to the Span containing just the type of the const
2362            let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
2363            ty.span
2364        });
2365
2366        infcx.err_ctxt().note_type_err(
2367            &mut diag,
2368            &cause,
2369            trait_c_span.map(|span| (span, Cow::from("type in trait"), false)),
2370            Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2371                expected: trait_ty.into(),
2372                found: impl_ty.into(),
2373            }))),
2374            terr,
2375            false,
2376            None,
2377        );
2378        return Err(diag.emit_err());
2379    };
2380
2381    // Check that all obligations are satisfied by the implementation's
2382    // version.
2383    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2384    if let TraitErrors::HasErrors(errors) = errors {
2385        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2386    }
2387
2388    ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env, [])
2389}
2390
2391{}
#[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/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2391u32),
                                    ::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)?;
            compare_const_generic_param_types(tcx, impl_ty, trait_ty,
                    impl_trait_ref, 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))]
2392fn compare_impl_ty<'tcx>(
2393    tcx: TyCtxt<'tcx>,
2394    impl_ty: ty::AssocItem,
2395    trait_ty: ty::AssocItem,
2396    impl_trait_ref: ty::TraitRef<'tcx>,
2397) -> Result<(), ErrorGuaranteed> {
2398    compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
2399    compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
2400    compare_const_generic_param_types(tcx, impl_ty, trait_ty, impl_trait_ref, false)?;
2401    check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
2402    compare_type_clause_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
2403    check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
2404}
2405
2406/// The equivalent of [compare_method_clause_entailment], but for associated types
2407/// instead of associated functions.
2408{}
#[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/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2408u32),
                                    ::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/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2436",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2436u32),
                                    ::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/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2445",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2445u32),
                                    ::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/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2470",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2470u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("param_env")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("param_env");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_env)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let 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))]
2409fn compare_type_clause_entailment<'tcx>(
2410    tcx: TyCtxt<'tcx>,
2411    impl_ty: ty::AssocItem,
2412    trait_ty: ty::AssocItem,
2413    impl_trait_ref: ty::TraitRef<'tcx>,
2414) -> Result<(), ErrorGuaranteed> {
2415    let impl_def_id = impl_ty.container_id(tcx);
2416    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
2417        tcx,
2418        impl_def_id,
2419        impl_trait_ref.args,
2420    );
2421
2422    let impl_ty_clauses = tcx.clauses_of(impl_ty.def_id);
2423    let trait_ty_clauses = tcx.clauses_of(trait_ty.def_id);
2424
2425    let impl_ty_own_bounds = impl_ty_clauses.instantiate_own_identity();
2426    // If there are no bounds, then there are no const conditions, so no need to check that here.
2427    if impl_ty_own_bounds.len() == 0 {
2428        // Nothing to check.
2429        return Ok(());
2430    }
2431
2432    // This `DefId` should be used for the `body_def_id` field on each
2433    // `ObligationCause` (and the `FnCtxt`). This is what
2434    // `regionck_item` expects.
2435    let impl_ty_def_id = impl_ty.def_id.expect_local();
2436    debug!(?trait_to_impl_args);
2437
2438    // The clauses declared by the impl definition, the trait and the
2439    // associated type in the trait are assumed.
2440    let impl_clauses = tcx.clauses_of(impl_ty_clauses.parent.unwrap());
2441    let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
2442    hybrid_clauses.extend(
2443        trait_ty_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(predicate, _)| predicate),
2444    );
2445    debug!(?hybrid_clauses);
2446
2447    let impl_ty_span = tcx.def_span(impl_ty_def_id);
2448    let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
2449
2450    let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
2451    if is_conditionally_const {
2452        // Augment the hybrid param-env with the const conditions
2453        // of the impl header and the trait assoc type.
2454        hybrid_clauses.extend(
2455            tcx.const_conditions(impl_ty_clauses.parent.unwrap())
2456                .instantiate_identity(tcx)
2457                .into_iter()
2458                .chain(
2459                    tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
2460                )
2461                .map(|(trait_ref, _)| {
2462                    trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
2463                }),
2464        );
2465    }
2466
2467    let hybrid_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
2468    let param_env = ty::ParamEnv::new(tcx, hybrid_clauses);
2469    let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
2470    debug!(?param_env);
2471
2472    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2473    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2474
2475    for (clause, span) in impl_ty_own_bounds {
2476        let cause = ObligationCause::misc(span, impl_ty_def_id);
2477        let clause = ocx.normalize(&cause, param_env, clause);
2478
2479        let cause = ObligationCause::new(
2480            span,
2481            impl_ty_def_id,
2482            ObligationCauseCode::CompareImplItem {
2483                impl_item_def_id: impl_ty.def_id.expect_local(),
2484                trait_item_def_id: trait_ty.def_id,
2485                kind: impl_ty.kind,
2486            },
2487        );
2488        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
2489    }
2490
2491    if is_conditionally_const {
2492        // Validate the const conditions of the impl associated type.
2493        let impl_ty_own_const_conditions =
2494            tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2495        for (const_condition, span) in impl_ty_own_const_conditions {
2496            let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2497            let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2498
2499            let cause = ObligationCause::new(
2500                span,
2501                impl_ty_def_id,
2502                ObligationCauseCode::CompareImplItem {
2503                    impl_item_def_id: impl_ty_def_id,
2504                    trait_item_def_id: trait_ty.def_id,
2505                    kind: impl_ty.kind,
2506                },
2507            );
2508            ocx.register_obligation(traits::Obligation::new(
2509                tcx,
2510                cause,
2511                param_env,
2512                const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2513            ));
2514        }
2515    }
2516
2517    // Check that all obligations are satisfied by the implementation's
2518    // version.
2519    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2520    if let TraitErrors::HasErrors(errors) = errors {
2521        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2522        return Err(reported);
2523    }
2524
2525    // Finally, resolve all regions. This catches wily misuses of
2526    // lifetime parameters.
2527    ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2528}
2529
2530/// Validate that `ProjectionCandidate`s created for this associated type will
2531/// be valid.
2532///
2533/// Usually given
2534///
2535/// trait X { type Y: Copy } impl X for T { type Y = S; }
2536///
2537/// We are able to normalize `<T as X>::Y` to `S`, and so when we check the
2538/// impl is well-formed we have to prove `S: Copy`.
2539///
2540/// For default associated types the normalization is not possible (the value
2541/// from the impl could be overridden). We also can't normalize generic
2542/// associated types (yet) because they contain bound parameters.
2543{}
#[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/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2543u32),
                                    ::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/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2555",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2555u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("param_env")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("param_env");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_env)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let container_id = impl_ty.container_id(tcx);
            let impl_ty_def_id = impl_ty.def_id.expect_local();
            let impl_ty_args =
                GenericArgs::identity_for_item(tcx, impl_ty.def_id);
            let rebased_args =
                impl_ty_args.rebase_onto(tcx, container_id,
                    impl_trait_ref.args);
            let infcx =
                tcx.infer_ctxt().build(TypingMode::non_body_analysis());
            let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
            let impl_ty_span =
                if impl_ty.is_impl_trait_in_trait() {
                    tcx.def_span(impl_ty_def_id)
                } else {
                    match tcx.hir_node_by_def_id(impl_ty_def_id) {
                        hir::Node::TraitItem(hir::TraitItem {
                            kind: hir::TraitItemKind::Type(_, Some(ty)), .. }) =>
                            ty.span,
                        hir::Node::ImplItem(hir::ImplItem {
                            kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
                        item =>
                            ::rustc_span::macros::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/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2604",
                                                            "rustc_hir_analysis::check::compare_impl_item",
                                                            ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(2604u32),
                                                            ::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/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2627",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/822182db4c4a1827256881d8c7aa685f0bcf2b11/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2627u32),
                                    ::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))]
2544pub(super) fn check_type_bounds<'tcx>(
2545    tcx: TyCtxt<'tcx>,
2546    trait_ty: ty::AssocItem,
2547    impl_ty: ty::AssocItem,
2548    impl_trait_ref: ty::TraitRef<'tcx>,
2549) -> Result<(), ErrorGuaranteed> {
2550    // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
2551    // other `Foo` impls are incoherent.
2552    tcx.ensure_result().coherent_trait(impl_trait_ref.def_id)?;
2553
2554    let param_env = tcx.param_env(impl_ty.def_id);
2555    debug!(?param_env);
2556
2557    let container_id = impl_ty.container_id(tcx);
2558    let impl_ty_def_id = impl_ty.def_id.expect_local();
2559    let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2560    let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2561
2562    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2563    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2564
2565    // A synthetic impl Trait for RPITIT desugaring or assoc type for effects desugaring has no HIR,
2566    // which we currently use to get the span for an impl's associated type. Instead, for these,
2567    // use the def_span for the synthesized  associated type.
2568    let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2569        tcx.def_span(impl_ty_def_id)
2570    } else {
2571        match tcx.hir_node_by_def_id(impl_ty_def_id) {
2572            hir::Node::TraitItem(hir::TraitItem {
2573                kind: hir::TraitItemKind::Type(_, Some(ty)),
2574                ..
2575            }) => ty.span,
2576            hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2577            item => span_bug!(
2578                tcx.def_span(impl_ty_def_id),
2579                "cannot call `check_type_bounds` on item: {item:?}",
2580            ),
2581        }
2582    };
2583    let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2584
2585    let normalize_cause = ObligationCause::new(
2586        impl_ty_span,
2587        impl_ty_def_id,
2588        ObligationCauseCode::CheckAssociatedTypeBounds {
2589            impl_item_def_id: impl_ty.def_id.expect_local(),
2590            trait_item_def_id: trait_ty.def_id,
2591        },
2592    );
2593    let mk_cause = |span: Span| {
2594        let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2595        ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2596    };
2597
2598    let mut obligations: Vec<_> = util::elaborate(
2599        tcx,
2600        tcx.explicit_item_bounds(trait_ty.def_id)
2601            .iter_instantiated_copied(tcx, rebased_args)
2602            .map(Unnormalized::skip_norm_wip)
2603            .map(|(concrete_ty_bound, span)| {
2604                debug!(?concrete_ty_bound);
2605                traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2606            }),
2607    )
2608    .collect();
2609
2610    // Only in a const implementation do we need to check that the `[const]` item bounds hold.
2611    if tcx.is_conditionally_const(impl_ty_def_id) {
2612        obligations.extend(util::elaborate(
2613            tcx,
2614            tcx.explicit_implied_const_bounds(trait_ty.def_id)
2615                .iter_instantiated_copied(tcx, rebased_args)
2616                .map(Unnormalized::skip_norm_wip)
2617                .map(|(c, span)| {
2618                    traits::Obligation::new(
2619                        tcx,
2620                        mk_cause(span),
2621                        param_env,
2622                        c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2623                    )
2624                }),
2625        ));
2626    }
2627    debug!(item_bounds=?obligations);
2628
2629    // Normalize predicates with the assumption that the GAT may always normalize
2630    // to its definition type. This should be the param-env we use to *prove* the
2631    // predicate too, but we don't do that because of performance issues.
2632    // See <https://github.com/rust-lang/rust/pull/117542#issue-1976337685>.
2633    let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2634    for obligation in &mut obligations {
2635        match ocx.deeply_normalize(
2636            &normalize_cause,
2637            normalize_param_env,
2638            Unnormalized::new_wip(obligation.predicate),
2639        ) {
2640            Ok(pred) => obligation.predicate = pred,
2641            Err(e) => {
2642                return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2643            }
2644        }
2645    }
2646
2647    // Check that all obligations are satisfied by the implementation's
2648    // version.
2649    ocx.register_obligations(obligations);
2650    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2651    if let TraitErrors::HasErrors(errors) = errors {
2652        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2653        return Err(reported);
2654    }
2655
2656    // Finally, resolve all regions. This catches wily misuses of
2657    // lifetime parameters.
2658    ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2659}
2660
2661/// Install projection predicates that allow GATs to project to their own
2662/// definition types. This is not allowed in general in cases of default
2663/// associated types in trait definitions, or when specialization is involved,
2664/// but is needed when checking these definition types actually satisfy the
2665/// trait bounds of the GAT.
2666///
2667/// # How it works
2668///
2669/// ```ignore (example)
2670/// impl<A, B> Foo<u32> for (A, B) {
2671///     type Bar<C> = Wrapper<A, B, C>
2672/// }
2673/// ```
2674///
2675/// - `impl_trait_ref` would be `<(A, B) as Foo<u32>>`
2676/// - `normalize_impl_ty_args` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
2677/// - `normalize_impl_ty` would be `Wrapper<A, B, ^0.0>`
2678/// - `rebased_args` would be `[(A, B), u32, ^0.0]`, combining the args from
2679///    the *trait* with the generic associated type parameters (as bound vars).
2680///
2681/// A note regarding the use of bound vars here:
2682/// Imagine as an example
2683/// ```
2684/// trait Family {
2685///     type Member<C: Eq>;
2686/// }
2687///
2688/// impl Family for VecFamily {
2689///     type Member<C: Eq> = i32;
2690/// }
2691/// ```
2692/// Here, we would generate
2693/// ```ignore (pseudo-rust)
2694/// forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
2695/// ```
2696///
2697/// when we really would like to generate
2698/// ```ignore (pseudo-rust)
2699/// forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
2700/// ```
2701///
2702/// But, this is probably fine, because although the first clause can be used with types `C` that
2703/// do not implement `Eq`, for it to cause some kind of problem, there would have to be a
2704/// `VecFamily::Member<X>` for some type `X` where `!(X: Eq)`, that appears in the value of type
2705/// `Member<C: Eq> = ....` That type would fail a well-formedness check that we ought to be doing
2706/// elsewhere, which would check that any `<T as Family>::Member<X>` meets the bounds declared in
2707/// the trait (notably, that `X: Eq` and `T: Family`).
2708fn param_env_with_gat_bounds<'tcx>(
2709    tcx: TyCtxt<'tcx>,
2710    impl_ty: ty::AssocItem,
2711    impl_trait_ref: ty::TraitRef<'tcx>,
2712) -> ty::ParamEnv<'tcx> {
2713    let param_env = tcx.param_env(impl_ty.def_id);
2714    let container_id = impl_ty.container_id(tcx);
2715    let mut clauses = param_env.caller_bounds().collect::<Vec<_>>();
2716
2717    // for RPITITs, we should install predicates that allow us to project all
2718    // of the RPITITs associated with the same body. This is because checking
2719    // the item bounds of RPITITs often involves nested RPITITs having to prove
2720    // bounds about themselves.
2721    let impl_tys_to_install = match impl_ty.kind {
2722        ty::AssocKind::Type {
2723            data:
2724                ty::AssocTypeData::Rpitit(
2725                    ty::ImplTraitInTraitData::Impl { fn_def_id }
2726                    | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2727                ),
2728        } => tcx
2729            .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2730            .iter()
2731            .map(|def_id| tcx.associated_item(*def_id))
2732            .collect(),
2733        _ => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [impl_ty]))vec![impl_ty],
2734    };
2735
2736    for impl_ty in impl_tys_to_install {
2737        let trait_ty = match impl_ty.container {
2738            ty::AssocContainer::InherentImpl => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
2739            ty::AssocContainer::Trait => impl_ty,
2740            ty::AssocContainer::TraitImpl(Err(_)) => continue,
2741            ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
2742                tcx.associated_item(trait_item_def_id)
2743            }
2744        };
2745
2746        let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind<'tcx>; 8]> =
2747            smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2748        // Extend the impl's identity args with late-bound GAT vars
2749        let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2750            .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2751                GenericParamDefKind::Type { .. } => {
2752                    let kind = ty::BoundTyKind::Param(param.def_id);
2753                    let bound_var = ty::BoundVariableKind::Ty(kind);
2754                    bound_vars.push(bound_var);
2755                    Ty::new_bound(
2756                        tcx,
2757                        ty::INNERMOST,
2758                        ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2759                    )
2760                    .into()
2761                }
2762                GenericParamDefKind::Lifetime => {
2763                    let kind = ty::BoundRegionKind::Named(param.def_id);
2764                    let bound_var = ty::BoundVariableKind::Region(kind);
2765                    bound_vars.push(bound_var);
2766                    ty::Region::new_bound(
2767                        tcx,
2768                        ty::INNERMOST,
2769                        ty::BoundRegion {
2770                            var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2771                            kind,
2772                        },
2773                    )
2774                    .into()
2775                }
2776                GenericParamDefKind::Const { .. } => {
2777                    let bound_var = ty::BoundVariableKind::Const;
2778                    bound_vars.push(bound_var);
2779                    ty::Const::new_bound(
2780                        tcx,
2781                        ty::INNERMOST,
2782                        ty::BoundConst::new(ty::BoundVar::from_usize(bound_vars.len() - 1)),
2783                    )
2784                    .into()
2785                }
2786            });
2787        // When checking something like
2788        //
2789        // trait X { type Y: PartialEq<<Self as X>::Y> }
2790        // impl X for T { default type Y = S; }
2791        //
2792        // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
2793        // we want <T as X>::Y to normalize to S. This is valid because we are
2794        // checking the default value specifically here. Add this equality to the
2795        // ParamEnv for normalization specifically.
2796        let normalize_impl_ty =
2797            tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args).skip_norm_wip();
2798        let rebased_args =
2799            normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2800        let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2801
2802        match normalize_impl_ty.kind() {
2803            &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
2804                if def_id == trait_ty.def_id && args == rebased_args =>
2805            {
2806                // Don't include this predicate if the projected type is
2807                // exactly the same as the projection. This can occur in
2808                // (somewhat dubious) code like this:
2809                //
2810                // impl<T> X for T where T: X { type Y = <T as X>::Y; }
2811            }
2812            _ => clauses.push(
2813                ty::Binder::bind_with_vars(
2814                    ty::ProjectionClause {
2815                        projection_term: ty::AliasTerm::new(
2816                            tcx,
2817                            ty::AliasTermKind::ProjectionTy { def_id: trait_ty.def_id },
2818                            rebased_args,
2819                        ),
2820                        term: normalize_impl_ty.into(),
2821                    },
2822                    bound_vars,
2823                )
2824                .upcast(tcx),
2825            ),
2826        };
2827    }
2828
2829    ty::ParamEnv::new(tcx, clauses)
2830}
2831
2832/// Manually check here that `async fn foo()` wasn't matched against `fn foo()`,
2833/// and extract a better error if so.
2834fn try_report_async_mismatch<'tcx>(
2835    tcx: TyCtxt<'tcx>,
2836    infcx: &InferCtxt<'tcx>,
2837    errors: &[FulfillmentError<'tcx>],
2838    trait_m: ty::AssocItem,
2839    impl_m: ty::AssocItem,
2840    impl_sig: ty::FnSig<'tcx>,
2841) -> Result<(), ErrorGuaranteed> {
2842    if !tcx.asyncness(trait_m.def_id).is_async() {
2843        return Ok(());
2844    }
2845
2846    let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id: async_future_def_id }, .. }) =
2847        *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2848    else {
2849        ::rustc_span::macros::bug_impl(None,
    format_args!("expected `async fn` to return an RPITIT"),
    Location::caller());bug!("expected `async fn` to return an RPITIT");
2850    };
2851
2852    for error in errors {
2853        if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2854            && def_id == async_future_def_id
2855            && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2856            && let Some(proj) = proj.no_bound_vars()
2857            && infcx.can_eq(
2858                error.root_obligation.param_env,
2859                proj.term.expect_type(),
2860                impl_sig.output(),
2861            )
2862        {
2863            // FIXME: We should suggest making the fn `async`, but extracting
2864            // the right span is a bit difficult.
2865            return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2866                span: tcx.def_span(impl_m.def_id),
2867                method_name: tcx.item_ident(impl_m.def_id),
2868                trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
2869            }));
2870        }
2871    }
2872
2873    Ok(())
2874}