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