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