Skip to main content

rustc_hir_analysis/check/
compare_impl_item.rs

1use core::ops::ControlFlow;
2use std::borrow::Cow;
3use std::cmp::Ordering;
4use std::iter;
5
6use hir::def_id::{DefId, DefIdMap, LocalDefId};
7use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
8use rustc_errors::codes::*;
9use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan, pluralize, struct_span_code_err};
10use rustc_hir::def::{DefKind, Res};
11use rustc_hir::intravisit::VisitorExt;
12use rustc_hir::{self as hir, AmbigArg, GenericParamKind, ImplItemKind, intravisit};
13use rustc_infer::infer::{self, BoundRegionConversionTime, InferCtxt, TyCtxtInferExt};
14use rustc_infer::traits::util;
15use rustc_middle::ty::error::{ExpectedFound, TypeError};
16use rustc_middle::ty::{
17    self, BottomUpFolder, GenericArgs, GenericParamDefKind, Generics, Ty, TyCtxt, TypeFoldable,
18    TypeFolder, TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
19    Unnormalized, Upcast,
20};
21use rustc_middle::{bug, span_bug};
22use rustc_span::{BytePos, DUMMY_SP, Span};
23use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
24use rustc_trait_selection::infer::InferCtxtExt;
25use rustc_trait_selection::regions::InferCtxtRegionExt;
26use rustc_trait_selection::traits::{
27    self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
28};
29use tracing::{debug, instrument};
30
31use super::potentially_plural_count;
32use crate::errors::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture};
33
34pub(super) mod refine;
35
36/// Call the query `tcx.compare_impl_item()` directly instead.
37pub(super) fn compare_impl_item(
38    tcx: TyCtxt<'_>,
39    impl_item_def_id: LocalDefId,
40) -> Result<(), ErrorGuaranteed> {
41    let impl_item = tcx.associated_item(impl_item_def_id);
42    let trait_item = tcx.associated_item(impl_item.expect_trait_impl()?);
43    let impl_trait_ref =
44        tcx.impl_trait_ref(impl_item.container_id(tcx)).instantiate_identity().skip_norm_wip();
45    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:45",
                        "rustc_hir_analysis::check::compare_impl_item",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                        ::tracing_core::__macro_support::Option::Some(45u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                        ::tracing_core::field::FieldSet::new(&["impl_trait_ref"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&impl_trait_ref)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?impl_trait_ref);
46
47    match impl_item.kind {
48        ty::AssocKind::Fn { .. } => compare_impl_method(tcx, impl_item, trait_item, impl_trait_ref),
49        ty::AssocKind::Type { .. } => compare_impl_ty(tcx, impl_item, trait_item, impl_trait_ref),
50        ty::AssocKind::Const { .. } => {
51            compare_impl_const(tcx, impl_item, trait_item, impl_trait_ref)
52        }
53    }
54}
55
56/// Checks that a method from an impl conforms to the signature of
57/// the same method as declared in the trait.
58///
59/// # Parameters
60///
61/// - `impl_m`: type of the method we are checking
62/// - `trait_m`: the method in the trait
63/// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
64#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("compare_impl_method",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(64u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["impl_m", "trait_m",
                                                    "impl_trait_ref"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_m)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_m)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
                                                            as &dyn 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_predicate_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_predicate_entailment(tcx, impl_m, trait_m, impl_trait_ref)?;
73    Ok(())
74}
75
76/// Checks a bunch of different properties of the impl/trait methods for
77/// compatibility, such as asyncness, number of argument, self receiver kind,
78/// and number of early- and late-bound generics.
79fn check_method_is_structurally_compatible<'tcx>(
80    tcx: TyCtxt<'tcx>,
81    impl_m: ty::AssocItem,
82    trait_m: ty::AssocItem,
83    impl_trait_ref: ty::TraitRef<'tcx>,
84    delay: bool,
85) -> Result<(), ErrorGuaranteed> {
86    compare_self_type(tcx, impl_m, trait_m, impl_trait_ref, delay)?;
87    compare_number_of_generics(tcx, impl_m, trait_m, delay)?;
88    compare_generic_param_kinds(tcx, impl_m, trait_m, delay)?;
89    compare_number_of_method_arguments(tcx, impl_m, trait_m, delay)?;
90    compare_synthetic_generics(tcx, impl_m, trait_m, delay)?;
91    check_region_bounds_on_impl_item(tcx, impl_m, trait_m, delay)?;
92    Ok(())
93}
94
95/// This function is best explained by example. Consider a trait with its implementation:
96///
97/// ```rust
98/// trait Trait<'t, T> {
99///     // `trait_m`
100///     fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
101/// }
102///
103/// struct Foo;
104///
105/// impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
106///     // `impl_m`
107///     fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo { Foo }
108/// }
109/// ```
110///
111/// We wish to decide if those two method types are compatible.
112/// For this we have to show that, assuming the bounds of the impl hold, the
113/// bounds of `trait_m` imply the bounds of `impl_m`.
114///
115/// We start out with `trait_to_impl_args`, that maps the trait
116/// type parameters to impl type parameters. This is taken from the
117/// impl trait reference:
118///
119/// ```rust,ignore (pseudo-Rust)
120/// trait_to_impl_args = {'t => 'j, T => &'i U, Self => Foo}
121/// ```
122///
123/// We create a mapping `dummy_args` that maps from the impl type
124/// parameters to fresh types and regions. For type parameters,
125/// this is the identity transform, but we could as well use any
126/// placeholder types. For regions, we convert from bound to free
127/// regions (Note: but only early-bound regions, i.e., those
128/// declared on the impl or used in type parameter bounds).
129///
130/// ```rust,ignore (pseudo-Rust)
131/// impl_to_placeholder_args = {'i => 'i0, U => U0, N => N0 }
132/// ```
133///
134/// Now we can apply `placeholder_args` to the type of the impl method
135/// to yield a new function type in terms of our fresh, placeholder
136/// types:
137///
138/// ```rust,ignore (pseudo-Rust)
139/// <'b> fn(t: &'i0 U0, m: &'b N0) -> Foo
140/// ```
141///
142/// We now want to extract and instantiate the type of the *trait*
143/// method and compare it. To do so, we must create a compound
144/// instantiation by combining `trait_to_impl_args` and
145/// `impl_to_placeholder_args`, and also adding a mapping for the method
146/// type parameters. We extend the mapping to also include
147/// the method parameters.
148///
149/// ```rust,ignore (pseudo-Rust)
150/// trait_to_placeholder_args = { T => &'i0 U0, Self => Foo, M => N0 }
151/// ```
152///
153/// Applying this to the trait method type yields:
154///
155/// ```rust,ignore (pseudo-Rust)
156/// <'a> fn(t: &'i0 U0, m: &'a N0) -> Foo
157/// ```
158///
159/// This type is also the same but the name of the bound region (`'a`
160/// vs `'b`). However, the normal subtyping rules on fn types handle
161/// this kind of equivalency just fine.
162///
163/// We now use these generic parameters to ensure that all declared bounds
164/// are satisfied by the implementation's method.
165///
166/// We do this by creating a parameter environment which contains a
167/// generic parameter corresponding to `impl_to_placeholder_args`. We then build
168/// `trait_to_placeholder_args` and use it to convert the predicates contained
169/// in the `trait_m` generics to the placeholder form.
170///
171/// Finally we register each of these predicates as an obligation and check that
172/// they hold.
173#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("compare_method_predicate_entailment",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(173u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["impl_m", "trait_m"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_m)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_m)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
            compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
            check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
            compare_type_predicate_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))]
2314fn compare_impl_ty<'tcx>(
2315    tcx: TyCtxt<'tcx>,
2316    impl_ty: ty::AssocItem,
2317    trait_ty: ty::AssocItem,
2318    impl_trait_ref: ty::TraitRef<'tcx>,
2319) -> Result<(), ErrorGuaranteed> {
2320    compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
2321    compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
2322    check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
2323    compare_type_predicate_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
2324    check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
2325}
2326
2327/// The equivalent of [compare_method_predicate_entailment], but for associated types
2328/// instead of associated functions.
2329#[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_predicate_entailment",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2329u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["impl_ty",
                                                    "trait_ty", "impl_trait_ref"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
                                                            as &dyn 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_predicates = tcx.predicates_of(impl_ty.def_id);
            let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
            let impl_ty_own_bounds =
                impl_ty_predicates.instantiate_own_identity();
            if impl_ty_own_bounds.len() == 0 { return Ok(()); }
            let impl_ty_def_id = impl_ty.def_id.expect_local();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2357",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2357u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["trait_to_impl_args"],
                                        ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&trait_to_impl_args)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let impl_predicates =
                tcx.predicates_of(impl_ty_predicates.parent.unwrap());
            let mut hybrid_preds =
                impl_predicates.instantiate_identity(tcx).predicates;
            hybrid_preds.extend(trait_ty_predicates.instantiate_own(tcx,
                        trait_to_impl_args).map(|(predicate, _)| predicate));
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2368",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2368u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["hybrid_preds"],
                                        ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&hybrid_preds)
                                                        as &dyn 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_preds.extend(tcx.const_conditions(impl_ty_predicates.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_preds =
                hybrid_preds.into_iter().map(Unnormalized::skip_norm_wip);
            let param_env =
                ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
            let param_env =
                traits::normalize_param_env_or_error(tcx, param_env,
                    normalize_cause);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2393",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2393u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["caller_bounds"],
                                        ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&param_env.caller_bounds())
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let infcx =
                tcx.infer_ctxt().build(TypingMode::non_body_analysis());
            let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
            for (predicate, span) in impl_ty_own_bounds {
                let cause = ObligationCause::misc(span, impl_ty_def_id);
                let predicate = ocx.normalize(&cause, param_env, predicate);
                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, predicate));
            }
            if is_conditionally_const {
                let impl_ty_own_const_conditions =
                    tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
                for (const_condition, span) in impl_ty_own_const_conditions {
                    let normalize_cause =
                        traits::ObligationCause::misc(span, impl_ty_def_id);
                    let const_condition =
                        ocx.normalize(&normalize_cause, param_env, const_condition);
                    let cause =
                        ObligationCause::new(span, impl_ty_def_id,
                            ObligationCauseCode::CompareImplItem {
                                impl_item_def_id: impl_ty_def_id,
                                trait_item_def_id: trait_ty.def_id,
                                kind: impl_ty.kind,
                            });
                    ocx.register_obligation(traits::Obligation::new(tcx, cause,
                            param_env,
                            const_condition.to_host_effect_clause(tcx,
                                ty::BoundConstness::Maybe)));
                }
            }
            let errors = ocx.evaluate_obligations_error_on_ambiguity();
            if !errors.is_empty() {
                let reported =
                    infcx.err_ctxt().report_fulfillment_errors(errors);
                return Err(reported);
            }
            ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env,
                [])
        }
    }
}#[instrument(level = "debug", skip(tcx))]
2330fn compare_type_predicate_entailment<'tcx>(
2331    tcx: TyCtxt<'tcx>,
2332    impl_ty: ty::AssocItem,
2333    trait_ty: ty::AssocItem,
2334    impl_trait_ref: ty::TraitRef<'tcx>,
2335) -> Result<(), ErrorGuaranteed> {
2336    let impl_def_id = impl_ty.container_id(tcx);
2337    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
2338        tcx,
2339        impl_def_id,
2340        impl_trait_ref.args,
2341    );
2342
2343    let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
2344    let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
2345
2346    let impl_ty_own_bounds = impl_ty_predicates.instantiate_own_identity();
2347    // If there are no bounds, then there are no const conditions, so no need to check that here.
2348    if impl_ty_own_bounds.len() == 0 {
2349        // Nothing to check.
2350        return Ok(());
2351    }
2352
2353    // This `DefId` should be used for the `body_id` field on each
2354    // `ObligationCause` (and the `FnCtxt`). This is what
2355    // `regionck_item` expects.
2356    let impl_ty_def_id = impl_ty.def_id.expect_local();
2357    debug!(?trait_to_impl_args);
2358
2359    // The predicates declared by the impl definition, the trait and the
2360    // associated type in the trait are assumed.
2361    let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
2362    let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2363    hybrid_preds.extend(
2364        trait_ty_predicates
2365            .instantiate_own(tcx, trait_to_impl_args)
2366            .map(|(predicate, _)| predicate),
2367    );
2368    debug!(?hybrid_preds);
2369
2370    let impl_ty_span = tcx.def_span(impl_ty_def_id);
2371    let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
2372
2373    let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
2374    if is_conditionally_const {
2375        // Augment the hybrid param-env with the const conditions
2376        // of the impl header and the trait assoc type.
2377        hybrid_preds.extend(
2378            tcx.const_conditions(impl_ty_predicates.parent.unwrap())
2379                .instantiate_identity(tcx)
2380                .into_iter()
2381                .chain(
2382                    tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
2383                )
2384                .map(|(trait_ref, _)| {
2385                    trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
2386                }),
2387        );
2388    }
2389
2390    let hybrid_preds = hybrid_preds.into_iter().map(Unnormalized::skip_norm_wip);
2391    let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
2392    let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
2393    debug!(caller_bounds=?param_env.caller_bounds());
2394
2395    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2396    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2397
2398    for (predicate, span) in impl_ty_own_bounds {
2399        let cause = ObligationCause::misc(span, impl_ty_def_id);
2400        let predicate = ocx.normalize(&cause, param_env, predicate);
2401
2402        let cause = ObligationCause::new(
2403            span,
2404            impl_ty_def_id,
2405            ObligationCauseCode::CompareImplItem {
2406                impl_item_def_id: impl_ty.def_id.expect_local(),
2407                trait_item_def_id: trait_ty.def_id,
2408                kind: impl_ty.kind,
2409            },
2410        );
2411        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2412    }
2413
2414    if is_conditionally_const {
2415        // Validate the const conditions of the impl associated type.
2416        let impl_ty_own_const_conditions =
2417            tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2418        for (const_condition, span) in impl_ty_own_const_conditions {
2419            let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2420            let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2421
2422            let cause = ObligationCause::new(
2423                span,
2424                impl_ty_def_id,
2425                ObligationCauseCode::CompareImplItem {
2426                    impl_item_def_id: impl_ty_def_id,
2427                    trait_item_def_id: trait_ty.def_id,
2428                    kind: impl_ty.kind,
2429                },
2430            );
2431            ocx.register_obligation(traits::Obligation::new(
2432                tcx,
2433                cause,
2434                param_env,
2435                const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2436            ));
2437        }
2438    }
2439
2440    // Check that all obligations are satisfied by the implementation's
2441    // version.
2442    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2443    if !errors.is_empty() {
2444        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2445        return Err(reported);
2446    }
2447
2448    // Finally, resolve all regions. This catches wily misuses of
2449    // lifetime parameters.
2450    ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2451}
2452
2453/// Validate that `ProjectionCandidate`s created for this associated type will
2454/// be valid.
2455///
2456/// Usually given
2457///
2458/// trait X { type Y: Copy } impl X for T { type Y = S; }
2459///
2460/// We are able to normalize `<T as X>::Y` to `S`, and so when we check the
2461/// impl is well-formed we have to prove `S: Copy`.
2462///
2463/// For default associated types the normalization is not possible (the value
2464/// from the impl could be overridden). We also can't normalize generic
2465/// associated types (yet) because they contain bound parameters.
2466#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_type_bounds",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2466u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["trait_ty",
                                                    "impl_ty", "impl_trait_ref"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            tcx.ensure_result().coherent_trait(impl_trait_ref.def_id)?;
            let param_env = tcx.param_env(impl_ty.def_id);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2478",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2478u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["param_env"],
                                        ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&param_env)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let container_id = impl_ty.container_id(tcx);
            let impl_ty_def_id = impl_ty.def_id.expect_local();
            let impl_ty_args =
                GenericArgs::identity_for_item(tcx, impl_ty.def_id);
            let rebased_args =
                impl_ty_args.rebase_onto(tcx, container_id,
                    impl_trait_ref.args);
            let infcx =
                tcx.infer_ctxt().build(TypingMode::non_body_analysis());
            let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
            let impl_ty_span =
                if impl_ty.is_impl_trait_in_trait() {
                    tcx.def_span(impl_ty_def_id)
                } else {
                    match tcx.hir_node_by_def_id(impl_ty_def_id) {
                        hir::Node::TraitItem(hir::TraitItem {
                            kind: hir::TraitItemKind::Type(_, Some(ty)), .. }) =>
                            ty.span,
                        hir::Node::ImplItem(hir::ImplItem {
                            kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
                        item =>
                            ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(impl_ty_def_id),
                                format_args!("cannot call `check_type_bounds` on item: {0:?}",
                                    item)),
                    }
                };
            let assumed_wf_types =
                ocx.assumed_wf_types_and_report_errors(param_env,
                        impl_ty_def_id)?;
            let normalize_cause =
                ObligationCause::new(impl_ty_span, impl_ty_def_id,
                    ObligationCauseCode::CheckAssociatedTypeBounds {
                        impl_item_def_id: impl_ty.def_id.expect_local(),
                        trait_item_def_id: trait_ty.def_id,
                    });
            let mk_cause =
                |span: Span|
                    {
                        let code =
                            ObligationCauseCode::WhereClause(trait_ty.def_id, span);
                        ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
                    };
            let mut obligations: Vec<_> =
                util::elaborate(tcx,
                        tcx.explicit_item_bounds(trait_ty.def_id).iter_instantiated_copied(tcx,
                                    rebased_args).map(Unnormalized::skip_norm_wip).map(|(concrete_ty_bound,
                                    span)|
                                {
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2527",
                                                            "rustc_hir_analysis::check::compare_impl_item",
                                                            ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(2527u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                                            ::tracing_core::field::FieldSet::new(&["concrete_ty_bound"],
                                                                ::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};
                                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                        ::tracing::__macro_support::Option::Some(&debug(&concrete_ty_bound)
                                                                                as &dyn Value))])
                                                });
                                        } else { ; }
                                    };
                                    traits::Obligation::new(tcx, mk_cause(span), param_env,
                                        concrete_ty_bound)
                                })).collect();
            if tcx.is_conditionally_const(impl_ty_def_id) {
                obligations.extend(util::elaborate(tcx,
                        tcx.explicit_implied_const_bounds(trait_ty.def_id).iter_instantiated_copied(tcx,
                                    rebased_args).map(Unnormalized::skip_norm_wip).map(|(c,
                                    span)|
                                {
                                    traits::Obligation::new(tcx, mk_cause(span), param_env,
                                        c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe))
                                })));
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2550",
                                    "rustc_hir_analysis::check::compare_impl_item",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2550u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
                                    ::tracing_core::field::FieldSet::new(&["item_bounds"],
                                        ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&obligations)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let normalize_param_env =
                param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
            for obligation in &mut obligations {
                match ocx.deeply_normalize(&normalize_cause,
                        normalize_param_env,
                        Unnormalized::new_wip(obligation.predicate)) {
                    Ok(pred) => obligation.predicate = pred,
                    Err(e) => {
                        return Err(infcx.err_ctxt().report_fulfillment_errors(e));
                    }
                }
            }
            ocx.register_obligations(obligations);
            let errors = ocx.evaluate_obligations_error_on_ambiguity();
            if !errors.is_empty() {
                let reported =
                    infcx.err_ctxt().report_fulfillment_errors(errors);
                return Err(reported);
            }
            ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env,
                assumed_wf_types)
        }
    }
}#[instrument(level = "debug", skip(tcx))]
2467pub(super) fn check_type_bounds<'tcx>(
2468    tcx: TyCtxt<'tcx>,
2469    trait_ty: ty::AssocItem,
2470    impl_ty: ty::AssocItem,
2471    impl_trait_ref: ty::TraitRef<'tcx>,
2472) -> Result<(), ErrorGuaranteed> {
2473    // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
2474    // other `Foo` impls are incoherent.
2475    tcx.ensure_result().coherent_trait(impl_trait_ref.def_id)?;
2476
2477    let param_env = tcx.param_env(impl_ty.def_id);
2478    debug!(?param_env);
2479
2480    let container_id = impl_ty.container_id(tcx);
2481    let impl_ty_def_id = impl_ty.def_id.expect_local();
2482    let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2483    let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2484
2485    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2486    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2487
2488    // A synthetic impl Trait for RPITIT desugaring or assoc type for effects desugaring has no HIR,
2489    // which we currently use to get the span for an impl's associated type. Instead, for these,
2490    // use the def_span for the synthesized  associated type.
2491    let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2492        tcx.def_span(impl_ty_def_id)
2493    } else {
2494        match tcx.hir_node_by_def_id(impl_ty_def_id) {
2495            hir::Node::TraitItem(hir::TraitItem {
2496                kind: hir::TraitItemKind::Type(_, Some(ty)),
2497                ..
2498            }) => ty.span,
2499            hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2500            item => span_bug!(
2501                tcx.def_span(impl_ty_def_id),
2502                "cannot call `check_type_bounds` on item: {item:?}",
2503            ),
2504        }
2505    };
2506    let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2507
2508    let normalize_cause = ObligationCause::new(
2509        impl_ty_span,
2510        impl_ty_def_id,
2511        ObligationCauseCode::CheckAssociatedTypeBounds {
2512            impl_item_def_id: impl_ty.def_id.expect_local(),
2513            trait_item_def_id: trait_ty.def_id,
2514        },
2515    );
2516    let mk_cause = |span: Span| {
2517        let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2518        ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2519    };
2520
2521    let mut obligations: Vec<_> = util::elaborate(
2522        tcx,
2523        tcx.explicit_item_bounds(trait_ty.def_id)
2524            .iter_instantiated_copied(tcx, rebased_args)
2525            .map(Unnormalized::skip_norm_wip)
2526            .map(|(concrete_ty_bound, span)| {
2527                debug!(?concrete_ty_bound);
2528                traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2529            }),
2530    )
2531    .collect();
2532
2533    // Only in a const implementation do we need to check that the `[const]` item bounds hold.
2534    if tcx.is_conditionally_const(impl_ty_def_id) {
2535        obligations.extend(util::elaborate(
2536            tcx,
2537            tcx.explicit_implied_const_bounds(trait_ty.def_id)
2538                .iter_instantiated_copied(tcx, rebased_args)
2539                .map(Unnormalized::skip_norm_wip)
2540                .map(|(c, span)| {
2541                    traits::Obligation::new(
2542                        tcx,
2543                        mk_cause(span),
2544                        param_env,
2545                        c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2546                    )
2547                }),
2548        ));
2549    }
2550    debug!(item_bounds=?obligations);
2551
2552    // Normalize predicates with the assumption that the GAT may always normalize
2553    // to its definition type. This should be the param-env we use to *prove* the
2554    // predicate too, but we don't do that because of performance issues.
2555    // See <https://github.com/rust-lang/rust/pull/117542#issue-1976337685>.
2556    let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2557    for obligation in &mut obligations {
2558        match ocx.deeply_normalize(
2559            &normalize_cause,
2560            normalize_param_env,
2561            Unnormalized::new_wip(obligation.predicate),
2562        ) {
2563            Ok(pred) => obligation.predicate = pred,
2564            Err(e) => {
2565                return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2566            }
2567        }
2568    }
2569
2570    // Check that all obligations are satisfied by the implementation's
2571    // version.
2572    ocx.register_obligations(obligations);
2573    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2574    if !errors.is_empty() {
2575        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2576        return Err(reported);
2577    }
2578
2579    // Finally, resolve all regions. This catches wily misuses of
2580    // lifetime parameters.
2581    ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2582}
2583
2584/// Install projection predicates that allow GATs to project to their own
2585/// definition types. This is not allowed in general in cases of default
2586/// associated types in trait definitions, or when specialization is involved,
2587/// but is needed when checking these definition types actually satisfy the
2588/// trait bounds of the GAT.
2589///
2590/// # How it works
2591///
2592/// ```ignore (example)
2593/// impl<A, B> Foo<u32> for (A, B) {
2594///     type Bar<C> = Wrapper<A, B, C>
2595/// }
2596/// ```
2597///
2598/// - `impl_trait_ref` would be `<(A, B) as Foo<u32>>`
2599/// - `normalize_impl_ty_args` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
2600/// - `normalize_impl_ty` would be `Wrapper<A, B, ^0.0>`
2601/// - `rebased_args` would be `[(A, B), u32, ^0.0]`, combining the args from
2602///    the *trait* with the generic associated type parameters (as bound vars).
2603///
2604/// A note regarding the use of bound vars here:
2605/// Imagine as an example
2606/// ```
2607/// trait Family {
2608///     type Member<C: Eq>;
2609/// }
2610///
2611/// impl Family for VecFamily {
2612///     type Member<C: Eq> = i32;
2613/// }
2614/// ```
2615/// Here, we would generate
2616/// ```ignore (pseudo-rust)
2617/// forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
2618/// ```
2619///
2620/// when we really would like to generate
2621/// ```ignore (pseudo-rust)
2622/// forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
2623/// ```
2624///
2625/// But, this is probably fine, because although the first clause can be used with types `C` that
2626/// do not implement `Eq`, for it to cause some kind of problem, there would have to be a
2627/// `VecFamily::Member<X>` for some type `X` where `!(X: Eq)`, that appears in the value of type
2628/// `Member<C: Eq> = ....` That type would fail a well-formedness check that we ought to be doing
2629/// elsewhere, which would check that any `<T as Family>::Member<X>` meets the bounds declared in
2630/// the trait (notably, that `X: Eq` and `T: Family`).
2631fn param_env_with_gat_bounds<'tcx>(
2632    tcx: TyCtxt<'tcx>,
2633    impl_ty: ty::AssocItem,
2634    impl_trait_ref: ty::TraitRef<'tcx>,
2635) -> ty::ParamEnv<'tcx> {
2636    let param_env = tcx.param_env(impl_ty.def_id);
2637    let container_id = impl_ty.container_id(tcx);
2638    let mut predicates = param_env.caller_bounds().to_vec();
2639
2640    // for RPITITs, we should install predicates that allow us to project all
2641    // of the RPITITs associated with the same body. This is because checking
2642    // the item bounds of RPITITs often involves nested RPITITs having to prove
2643    // bounds about themselves.
2644    let impl_tys_to_install = match impl_ty.kind {
2645        ty::AssocKind::Type {
2646            data:
2647                ty::AssocTypeData::Rpitit(
2648                    ty::ImplTraitInTraitData::Impl { fn_def_id }
2649                    | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2650                ),
2651        } => tcx
2652            .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2653            .iter()
2654            .map(|def_id| tcx.associated_item(*def_id))
2655            .collect(),
2656        _ => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [impl_ty]))vec![impl_ty],
2657    };
2658
2659    for impl_ty in impl_tys_to_install {
2660        let trait_ty = match impl_ty.container {
2661            ty::AssocContainer::InherentImpl => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
2662            ty::AssocContainer::Trait => impl_ty,
2663            ty::AssocContainer::TraitImpl(Err(_)) => continue,
2664            ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
2665                tcx.associated_item(trait_item_def_id)
2666            }
2667        };
2668
2669        let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind<'tcx>; 8]> =
2670            smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2671        // Extend the impl's identity args with late-bound GAT vars
2672        let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2673            .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2674                GenericParamDefKind::Type { .. } => {
2675                    let kind = ty::BoundTyKind::Param(param.def_id);
2676                    let bound_var = ty::BoundVariableKind::Ty(kind);
2677                    bound_vars.push(bound_var);
2678                    Ty::new_bound(
2679                        tcx,
2680                        ty::INNERMOST,
2681                        ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2682                    )
2683                    .into()
2684                }
2685                GenericParamDefKind::Lifetime => {
2686                    let kind = ty::BoundRegionKind::Named(param.def_id);
2687                    let bound_var = ty::BoundVariableKind::Region(kind);
2688                    bound_vars.push(bound_var);
2689                    ty::Region::new_bound(
2690                        tcx,
2691                        ty::INNERMOST,
2692                        ty::BoundRegion {
2693                            var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2694                            kind,
2695                        },
2696                    )
2697                    .into()
2698                }
2699                GenericParamDefKind::Const { .. } => {
2700                    let bound_var = ty::BoundVariableKind::Const;
2701                    bound_vars.push(bound_var);
2702                    ty::Const::new_bound(
2703                        tcx,
2704                        ty::INNERMOST,
2705                        ty::BoundConst::new(ty::BoundVar::from_usize(bound_vars.len() - 1)),
2706                    )
2707                    .into()
2708                }
2709            });
2710        // When checking something like
2711        //
2712        // trait X { type Y: PartialEq<<Self as X>::Y> }
2713        // impl X for T { default type Y = S; }
2714        //
2715        // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
2716        // we want <T as X>::Y to normalize to S. This is valid because we are
2717        // checking the default value specifically here. Add this equality to the
2718        // ParamEnv for normalization specifically.
2719        let normalize_impl_ty =
2720            tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args).skip_norm_wip();
2721        let rebased_args =
2722            normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2723        let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2724
2725        match normalize_impl_ty.kind() {
2726            &ty::Alias(ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
2727                if def_id == trait_ty.def_id && args == rebased_args =>
2728            {
2729                // Don't include this predicate if the projected type is
2730                // exactly the same as the projection. This can occur in
2731                // (somewhat dubious) code like this:
2732                //
2733                // impl<T> X for T where T: X { type Y = <T as X>::Y; }
2734            }
2735            _ => predicates.push(
2736                ty::Binder::bind_with_vars(
2737                    ty::ProjectionPredicate {
2738                        projection_term: ty::AliasTerm::new_from_def_id(
2739                            tcx,
2740                            trait_ty.def_id,
2741                            rebased_args,
2742                        ),
2743                        term: normalize_impl_ty.into(),
2744                    },
2745                    bound_vars,
2746                )
2747                .upcast(tcx),
2748            ),
2749        };
2750    }
2751
2752    ty::ParamEnv::new(tcx.mk_clauses(&predicates))
2753}
2754
2755/// Manually check here that `async fn foo()` wasn't matched against `fn foo()`,
2756/// and extract a better error if so.
2757fn try_report_async_mismatch<'tcx>(
2758    tcx: TyCtxt<'tcx>,
2759    infcx: &InferCtxt<'tcx>,
2760    errors: &[FulfillmentError<'tcx>],
2761    trait_m: ty::AssocItem,
2762    impl_m: ty::AssocItem,
2763    impl_sig: ty::FnSig<'tcx>,
2764) -> Result<(), ErrorGuaranteed> {
2765    if !tcx.asyncness(trait_m.def_id).is_async() {
2766        return Ok(());
2767    }
2768
2769    let ty::Alias(ty::AliasTy { kind: ty::Projection { def_id: async_future_def_id }, .. }) =
2770        *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2771    else {
2772        ::rustc_middle::util::bug::bug_fmt(format_args!("expected `async fn` to return an RPITIT"));bug!("expected `async fn` to return an RPITIT");
2773    };
2774
2775    for error in errors {
2776        if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2777            && def_id == async_future_def_id
2778            && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2779            && let Some(proj) = proj.no_bound_vars()
2780            && infcx.can_eq(
2781                error.root_obligation.param_env,
2782                proj.term.expect_type(),
2783                impl_sig.output(),
2784            )
2785        {
2786            // FIXME: We should suggest making the fn `async`, but extracting
2787            // the right span is a bit difficult.
2788            return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2789                span: tcx.def_span(impl_m.def_id),
2790                method_name: tcx.item_ident(impl_m.def_id),
2791                trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
2792            }));
2793        }
2794    }
2795
2796    Ok(())
2797}