rustc_hir_analysis/check/
compare_impl_item.rs

1use core::ops::ControlFlow;
2use std::borrow::Cow;
3use std::iter;
4
5use hir::def_id::{DefId, DefIdMap, LocalDefId};
6use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
7use rustc_errors::codes::*;
8use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan, pluralize, struct_span_code_err};
9use rustc_hir::def::{DefKind, Res};
10use rustc_hir::intravisit::VisitorExt;
11use rustc_hir::{self as hir, AmbigArg, GenericParamKind, ImplItemKind, intravisit};
12use rustc_infer::infer::{self, BoundRegionConversionTime, InferCtxt, TyCtxtInferExt};
13use rustc_infer::traits::util;
14use rustc_middle::ty::error::{ExpectedFound, TypeError};
15use rustc_middle::ty::{
16    self, BottomUpFolder, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFoldable, TypeFolder,
17    TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Upcast,
18};
19use rustc_middle::{bug, span_bug};
20use rustc_span::{DUMMY_SP, Span};
21use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
22use rustc_trait_selection::infer::InferCtxtExt;
23use rustc_trait_selection::regions::InferCtxtRegionExt;
24use rustc_trait_selection::traits::{
25    self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
26};
27use tracing::{debug, instrument};
28
29use super::potentially_plural_count;
30use crate::errors::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture};
31
32pub(super) mod refine;
33
34/// Call the query `tcx.compare_impl_item()` directly instead.
35pub(super) fn compare_impl_item(
36    tcx: TyCtxt<'_>,
37    impl_item_def_id: LocalDefId,
38) -> Result<(), ErrorGuaranteed> {
39    let impl_item = tcx.associated_item(impl_item_def_id);
40    let trait_item = tcx.associated_item(impl_item.expect_trait_impl()?);
41    let impl_trait_ref = tcx.impl_trait_ref(impl_item.container_id(tcx)).instantiate_identity();
42    debug!(?impl_trait_ref);
43
44    match impl_item.kind {
45        ty::AssocKind::Fn { .. } => compare_impl_method(tcx, impl_item, trait_item, impl_trait_ref),
46        ty::AssocKind::Type { .. } => compare_impl_ty(tcx, impl_item, trait_item, impl_trait_ref),
47        ty::AssocKind::Const { .. } => {
48            compare_impl_const(tcx, impl_item, trait_item, impl_trait_ref)
49        }
50    }
51}
52
53/// Checks that a method from an impl conforms to the signature of
54/// the same method as declared in the trait.
55///
56/// # Parameters
57///
58/// - `impl_m`: type of the method we are checking
59/// - `trait_m`: the method in the trait
60/// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
61#[instrument(level = "debug", skip(tcx))]
62fn compare_impl_method<'tcx>(
63    tcx: TyCtxt<'tcx>,
64    impl_m: ty::AssocItem,
65    trait_m: ty::AssocItem,
66    impl_trait_ref: ty::TraitRef<'tcx>,
67) -> Result<(), ErrorGuaranteed> {
68    check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, false)?;
69    compare_method_predicate_entailment(tcx, impl_m, trait_m, impl_trait_ref)?;
70    Ok(())
71}
72
73/// Checks a bunch of different properties of the impl/trait methods for
74/// compatibility, such as asyncness, number of argument, self receiver kind,
75/// and number of early- and late-bound generics.
76fn check_method_is_structurally_compatible<'tcx>(
77    tcx: TyCtxt<'tcx>,
78    impl_m: ty::AssocItem,
79    trait_m: ty::AssocItem,
80    impl_trait_ref: ty::TraitRef<'tcx>,
81    delay: bool,
82) -> Result<(), ErrorGuaranteed> {
83    compare_self_type(tcx, impl_m, trait_m, impl_trait_ref, delay)?;
84    compare_number_of_generics(tcx, impl_m, trait_m, delay)?;
85    compare_generic_param_kinds(tcx, impl_m, trait_m, delay)?;
86    compare_number_of_method_arguments(tcx, impl_m, trait_m, delay)?;
87    compare_synthetic_generics(tcx, impl_m, trait_m, delay)?;
88    check_region_bounds_on_impl_item(tcx, impl_m, trait_m, delay)?;
89    Ok(())
90}
91
92/// This function is best explained by example. Consider a trait with its implementation:
93///
94/// ```rust
95/// trait Trait<'t, T> {
96///     // `trait_m`
97///     fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
98/// }
99///
100/// struct Foo;
101///
102/// impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
103///     // `impl_m`
104///     fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo { Foo }
105/// }
106/// ```
107///
108/// We wish to decide if those two method types are compatible.
109/// For this we have to show that, assuming the bounds of the impl hold, the
110/// bounds of `trait_m` imply the bounds of `impl_m`.
111///
112/// We start out with `trait_to_impl_args`, that maps the trait
113/// type parameters to impl type parameters. This is taken from the
114/// impl trait reference:
115///
116/// ```rust,ignore (pseudo-Rust)
117/// trait_to_impl_args = {'t => 'j, T => &'i U, Self => Foo}
118/// ```
119///
120/// We create a mapping `dummy_args` that maps from the impl type
121/// parameters to fresh types and regions. For type parameters,
122/// this is the identity transform, but we could as well use any
123/// placeholder types. For regions, we convert from bound to free
124/// regions (Note: but only early-bound regions, i.e., those
125/// declared on the impl or used in type parameter bounds).
126///
127/// ```rust,ignore (pseudo-Rust)
128/// impl_to_placeholder_args = {'i => 'i0, U => U0, N => N0 }
129/// ```
130///
131/// Now we can apply `placeholder_args` to the type of the impl method
132/// to yield a new function type in terms of our fresh, placeholder
133/// types:
134///
135/// ```rust,ignore (pseudo-Rust)
136/// <'b> fn(t: &'i0 U0, m: &'b N0) -> Foo
137/// ```
138///
139/// We now want to extract and instantiate the type of the *trait*
140/// method and compare it. To do so, we must create a compound
141/// instantiation by combining `trait_to_impl_args` and
142/// `impl_to_placeholder_args`, and also adding a mapping for the method
143/// type parameters. We extend the mapping to also include
144/// the method parameters.
145///
146/// ```rust,ignore (pseudo-Rust)
147/// trait_to_placeholder_args = { T => &'i0 U0, Self => Foo, M => N0 }
148/// ```
149///
150/// Applying this to the trait method type yields:
151///
152/// ```rust,ignore (pseudo-Rust)
153/// <'a> fn(t: &'i0 U0, m: &'a N0) -> Foo
154/// ```
155///
156/// This type is also the same but the name of the bound region (`'a`
157/// vs `'b`). However, the normal subtyping rules on fn types handle
158/// this kind of equivalency just fine.
159///
160/// We now use these generic parameters to ensure that all declared bounds
161/// are satisfied by the implementation's method.
162///
163/// We do this by creating a parameter environment which contains a
164/// generic parameter corresponding to `impl_to_placeholder_args`. We then build
165/// `trait_to_placeholder_args` and use it to convert the predicates contained
166/// in the `trait_m` generics to the placeholder form.
167///
168/// Finally we register each of these predicates as an obligation and check that
169/// they hold.
170#[instrument(level = "debug", skip(tcx, impl_trait_ref))]
171fn compare_method_predicate_entailment<'tcx>(
172    tcx: TyCtxt<'tcx>,
173    impl_m: ty::AssocItem,
174    trait_m: ty::AssocItem,
175    impl_trait_ref: ty::TraitRef<'tcx>,
176) -> Result<(), ErrorGuaranteed> {
177    // This node-id should be used for the `body_id` field on each
178    // `ObligationCause` (and the `FnCtxt`).
179    //
180    // FIXME(@lcnr): remove that after removing `cause.body_id` from
181    // obligations.
182    let impl_m_def_id = impl_m.def_id.expect_local();
183    let impl_m_span = tcx.def_span(impl_m_def_id);
184    let cause = ObligationCause::new(
185        impl_m_span,
186        impl_m_def_id,
187        ObligationCauseCode::CompareImplItem {
188            impl_item_def_id: impl_m_def_id,
189            trait_item_def_id: trait_m.def_id,
190            kind: impl_m.kind,
191        },
192    );
193
194    // Create mapping from trait method to impl method.
195    let impl_def_id = impl_m.container_id(tcx);
196    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
197        tcx,
198        impl_m.container_id(tcx),
199        impl_trait_ref.args,
200    );
201    debug!(?trait_to_impl_args);
202
203    let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
204    let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
205
206    // This is the only tricky bit of the new way we check implementation methods
207    // We need to build a set of predicates where only the method-level bounds
208    // are from the trait and we assume all other bounds from the implementation
209    // to be previously satisfied.
210    //
211    // We then register the obligations from the impl_m and check to see
212    // if all constraints hold.
213    let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
214    let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
215    hybrid_preds.extend(
216        trait_m_predicates.instantiate_own(tcx, trait_to_impl_args).map(|(predicate, _)| predicate),
217    );
218
219    let is_conditionally_const = tcx.is_conditionally_const(impl_def_id);
220    if is_conditionally_const {
221        // Augment the hybrid param-env with the const conditions
222        // of the impl header and the trait method.
223        hybrid_preds.extend(
224            tcx.const_conditions(impl_def_id)
225                .instantiate_identity(tcx)
226                .into_iter()
227                .chain(
228                    tcx.const_conditions(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args),
229                )
230                .map(|(trait_ref, _)| {
231                    trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
232                }),
233        );
234    }
235
236    let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
237    let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
238    let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
239    debug!(caller_bounds=?param_env.caller_bounds());
240
241    let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
242    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
243
244    // Create obligations for each predicate declared by the impl
245    // definition in the context of the hybrid param-env. This makes
246    // sure that the impl's method's where clauses are not more
247    // restrictive than the trait's method (and the impl itself).
248    let impl_m_own_bounds = impl_m_predicates.instantiate_own_identity();
249    for (predicate, span) in impl_m_own_bounds {
250        let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
251        let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
252
253        let cause = ObligationCause::new(
254            span,
255            impl_m_def_id,
256            ObligationCauseCode::CompareImplItem {
257                impl_item_def_id: impl_m_def_id,
258                trait_item_def_id: trait_m.def_id,
259                kind: impl_m.kind,
260            },
261        );
262        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
263    }
264
265    // If we're within a const implementation, we need to make sure that the method
266    // does not assume stronger `[const]` bounds than the trait definition.
267    //
268    // This registers the `[const]` bounds of the impl method, which we will prove
269    // using the hybrid param-env that we earlier augmented with the const conditions
270    // from the impl header and trait method declaration.
271    if is_conditionally_const {
272        for (const_condition, span) in
273            tcx.const_conditions(impl_m.def_id).instantiate_own_identity()
274        {
275            let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
276            let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
277
278            let cause = ObligationCause::new(
279                span,
280                impl_m_def_id,
281                ObligationCauseCode::CompareImplItem {
282                    impl_item_def_id: impl_m_def_id,
283                    trait_item_def_id: trait_m.def_id,
284                    kind: impl_m.kind,
285                },
286            );
287            ocx.register_obligation(traits::Obligation::new(
288                tcx,
289                cause,
290                param_env,
291                const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
292            ));
293        }
294    }
295
296    // We now need to check that the signature of the impl method is
297    // compatible with that of the trait method. We do this by
298    // checking that `impl_fty <: trait_fty`.
299    //
300    // FIXME: We manually instantiate the trait method here as we need
301    // to manually compute its implied bounds. Otherwise this could just
302    // be `ocx.sub(impl_sig, trait_sig)`.
303
304    let mut wf_tys = FxIndexSet::default();
305
306    let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars(
307        impl_m_span,
308        BoundRegionConversionTime::HigherRankedType,
309        tcx.fn_sig(impl_m.def_id).instantiate_identity(),
310    );
311
312    let norm_cause = ObligationCause::misc(impl_m_span, impl_m_def_id);
313    let impl_sig = ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig);
314    debug!(?impl_sig);
315
316    let trait_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args);
317    let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
318
319    // Next, add all inputs and output as well-formed tys. Importantly,
320    // we have to do this before normalization, since the normalized ty may
321    // not contain the input parameters. See issue #87748.
322    wf_tys.extend(trait_sig.inputs_and_output.iter());
323    let trait_sig = ocx.normalize(&norm_cause, param_env, trait_sig);
324    // We also have to add the normalized trait signature
325    // as we don't normalize during implied bounds computation.
326    wf_tys.extend(trait_sig.inputs_and_output.iter());
327    debug!(?trait_sig);
328
329    // FIXME: We'd want to keep more accurate spans than "the method signature" when
330    // processing the comparison between the trait and impl fn, but we sadly lose them
331    // and point at the whole signature when a trait bound or specific input or output
332    // type would be more appropriate. In other places we have a `Vec<Span>`
333    // corresponding to their `Vec<Predicate>`, but we don't have that here.
334    // Fixing this would improve the output of test `issue-83765.rs`.
335    let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
336
337    if let Err(terr) = result {
338        debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
339
340        let emitted = report_trait_method_mismatch(
341            infcx,
342            cause,
343            param_env,
344            terr,
345            (trait_m, trait_sig),
346            (impl_m, impl_sig),
347            impl_trait_ref,
348        );
349        return Err(emitted);
350    }
351
352    if !(impl_sig, trait_sig).references_error() {
353        for ty in unnormalized_impl_sig.inputs_and_output {
354            ocx.register_obligation(traits::Obligation::new(
355                infcx.tcx,
356                cause.clone(),
357                param_env,
358                ty::ClauseKind::WellFormed(ty.into()),
359            ));
360        }
361    }
362
363    // Check that all obligations are satisfied by the implementation's
364    // version.
365    let errors = ocx.evaluate_obligations_error_on_ambiguity();
366    if !errors.is_empty() {
367        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
368        return Err(reported);
369    }
370
371    // Finally, resolve all regions. This catches wily misuses of
372    // lifetime parameters.
373    let errors = infcx.resolve_regions(impl_m_def_id, param_env, wf_tys);
374    if !errors.is_empty() {
375        return Err(infcx
376            .tainted_by_errors()
377            .unwrap_or_else(|| infcx.err_ctxt().report_region_errors(impl_m_def_id, &errors)));
378    }
379
380    Ok(())
381}
382
383struct RemapLateParam<'tcx> {
384    tcx: TyCtxt<'tcx>,
385    mapping: FxIndexMap<ty::LateParamRegionKind, ty::LateParamRegionKind>,
386}
387
388impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateParam<'tcx> {
389    fn cx(&self) -> TyCtxt<'tcx> {
390        self.tcx
391    }
392
393    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
394        if let ty::ReLateParam(fr) = r.kind() {
395            ty::Region::new_late_param(
396                self.tcx,
397                fr.scope,
398                self.mapping.get(&fr.kind).copied().unwrap_or(fr.kind),
399            )
400        } else {
401            r
402        }
403    }
404}
405
406/// Given a method def-id in an impl, compare the method signature of the impl
407/// against the trait that it's implementing. In doing so, infer the hidden types
408/// that this method's signature provides to satisfy each return-position `impl Trait`
409/// in the trait signature.
410///
411/// The method is also responsible for making sure that the hidden types for each
412/// RPITIT actually satisfy the bounds of the `impl Trait`, i.e. that if we infer
413/// `impl Trait = Foo`, that `Foo: Trait` holds.
414///
415/// For example, given the sample code:
416///
417/// ```
418/// use std::ops::Deref;
419///
420/// trait Foo {
421///     fn bar() -> impl Deref<Target = impl Sized>;
422///     //          ^- RPITIT #1        ^- RPITIT #2
423/// }
424///
425/// impl Foo for () {
426///     fn bar() -> Box<String> { Box::new(String::new()) }
427/// }
428/// ```
429///
430/// The hidden types for the RPITITs in `bar` would be inferred to:
431///     * `impl Deref` (RPITIT #1) = `Box<String>`
432///     * `impl Sized` (RPITIT #2) = `String`
433///
434/// The relationship between these two types is straightforward in this case, but
435/// may be more tenuously connected via other `impl`s and normalization rules for
436/// cases of more complicated nested RPITITs.
437#[instrument(skip(tcx), level = "debug", ret)]
438pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
439    tcx: TyCtxt<'tcx>,
440    impl_m_def_id: LocalDefId,
441) -> Result<&'tcx DefIdMap<ty::EarlyBinder<'tcx, Ty<'tcx>>>, ErrorGuaranteed> {
442    let impl_m = tcx.associated_item(impl_m_def_id.to_def_id());
443    let trait_m = tcx.associated_item(impl_m.expect_trait_impl()?);
444    let impl_trait_ref =
445        tcx.impl_trait_ref(tcx.parent(impl_m_def_id.to_def_id())).instantiate_identity();
446    // First, check a few of the same things as `compare_impl_method`,
447    // just so we don't ICE during instantiation later.
448    check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?;
449
450    let impl_m_hir_id = tcx.local_def_id_to_hir_id(impl_m_def_id);
451    let return_span = tcx.hir_fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
452    let cause = ObligationCause::new(
453        return_span,
454        impl_m_def_id,
455        ObligationCauseCode::CompareImplItem {
456            impl_item_def_id: impl_m_def_id,
457            trait_item_def_id: trait_m.def_id,
458            kind: impl_m.kind,
459        },
460    );
461
462    // Create mapping from trait to impl (i.e. impl trait header + impl method identity args).
463    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
464        tcx,
465        impl_m.container_id(tcx),
466        impl_trait_ref.args,
467    );
468
469    let hybrid_preds = tcx
470        .predicates_of(impl_m.container_id(tcx))
471        .instantiate_identity(tcx)
472        .into_iter()
473        .chain(tcx.predicates_of(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args))
474        .map(|(clause, _)| clause);
475    let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
476    let param_env = traits::normalize_param_env_or_error(
477        tcx,
478        param_env,
479        ObligationCause::misc(tcx.def_span(impl_m_def_id), impl_m_def_id),
480    );
481
482    let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
483    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
484
485    // Check that the where clauses of the impl are satisfied by the hybrid param env.
486    // You might ask -- what does this have to do with RPITIT inference? Nothing.
487    // We check these because if the where clauses of the signatures do not match
488    // up, then we don't want to give spurious other errors that point at the RPITITs.
489    // They're not necessary to check, though, because we already check them in
490    // `compare_method_predicate_entailment`.
491    let impl_m_own_bounds = tcx.predicates_of(impl_m_def_id).instantiate_own_identity();
492    for (predicate, span) in impl_m_own_bounds {
493        let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
494        let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
495
496        let cause = ObligationCause::new(
497            span,
498            impl_m_def_id,
499            ObligationCauseCode::CompareImplItem {
500                impl_item_def_id: impl_m_def_id,
501                trait_item_def_id: trait_m.def_id,
502                kind: impl_m.kind,
503            },
504        );
505        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
506    }
507
508    // Normalize the impl signature with fresh variables for lifetime inference.
509    let misc_cause = ObligationCause::misc(return_span, impl_m_def_id);
510    let impl_sig = ocx.normalize(
511        &misc_cause,
512        param_env,
513        infcx.instantiate_binder_with_fresh_vars(
514            return_span,
515            BoundRegionConversionTime::HigherRankedType,
516            tcx.fn_sig(impl_m.def_id).instantiate_identity(),
517        ),
518    );
519    impl_sig.error_reported()?;
520    let impl_return_ty = impl_sig.output();
521
522    // Normalize the trait signature with liberated bound vars, passing it through
523    // the ImplTraitInTraitCollector, which gathers all of the RPITITs and replaces
524    // them with inference variables.
525    // We will use these inference variables to collect the hidden types of RPITITs.
526    let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_def_id);
527    let unnormalized_trait_sig = tcx
528        .liberate_late_bound_regions(
529            impl_m.def_id,
530            tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args),
531        )
532        .fold_with(&mut collector);
533
534    let trait_sig = ocx.normalize(&misc_cause, param_env, unnormalized_trait_sig);
535    trait_sig.error_reported()?;
536    let trait_return_ty = trait_sig.output();
537
538    // RPITITs are allowed to use the implied predicates of the method that
539    // defines them. This is because we want code like:
540    // ```
541    // trait Foo {
542    //     fn test<'a, T>(_: &'a T) -> impl Sized;
543    // }
544    // impl Foo for () {
545    //     fn test<'a, T>(x: &'a T) -> &'a T { x }
546    // }
547    // ```
548    // .. to compile. However, since we use both the normalized and unnormalized
549    // inputs and outputs from the instantiated trait signature, we will end up
550    // seeing the hidden type of an RPIT in the signature itself. Naively, this
551    // means that we will use the hidden type to imply the hidden type's own
552    // well-formedness.
553    //
554    // To avoid this, we replace the infer vars used for hidden type inference
555    // with placeholders, which imply nothing about outlives bounds, and then
556    // prove below that the hidden types are well formed.
557    let universe = infcx.create_next_universe();
558    let mut idx = ty::BoundVar::ZERO;
559    let mapping: FxIndexMap<_, _> = collector
560        .types
561        .iter()
562        .map(|(_, &(ty, _))| {
563            assert!(
564                infcx.resolve_vars_if_possible(ty) == ty && ty.is_ty_var(),
565                "{ty:?} should not have been constrained via normalization",
566                ty = infcx.resolve_vars_if_possible(ty)
567            );
568            idx += 1;
569            (
570                ty,
571                Ty::new_placeholder(
572                    tcx,
573                    ty::Placeholder {
574                        universe,
575                        bound: ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
576                    },
577                ),
578            )
579        })
580        .collect();
581    let mut type_mapper = BottomUpFolder {
582        tcx,
583        ty_op: |ty| *mapping.get(&ty).unwrap_or(&ty),
584        lt_op: |lt| lt,
585        ct_op: |ct| ct,
586    };
587    let wf_tys = FxIndexSet::from_iter(
588        unnormalized_trait_sig
589            .inputs_and_output
590            .iter()
591            .chain(trait_sig.inputs_and_output.iter())
592            .map(|ty| ty.fold_with(&mut type_mapper)),
593    );
594
595    match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
596        Ok(()) => {}
597        Err(terr) => {
598            let mut diag = struct_span_code_err!(
599                tcx.dcx(),
600                cause.span,
601                E0053,
602                "method `{}` has an incompatible return type for trait",
603                trait_m.name()
604            );
605            infcx.err_ctxt().note_type_err(
606                &mut diag,
607                &cause,
608                tcx.hir_get_if_local(impl_m.def_id)
609                    .and_then(|node| node.fn_decl())
610                    .map(|decl| (decl.output.span(), Cow::from("return type in trait"), false)),
611                Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
612                    expected: trait_return_ty.into(),
613                    found: impl_return_ty.into(),
614                }))),
615                terr,
616                false,
617                None,
618            );
619            return Err(diag.emit());
620        }
621    }
622
623    debug!(?trait_sig, ?impl_sig, "equating function signatures");
624
625    // Unify the whole function signature. We need to do this to fully infer
626    // the lifetimes of the return type, but do this after unifying just the
627    // return types, since we want to avoid duplicating errors from
628    // `compare_method_predicate_entailment`.
629    match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
630        Ok(()) => {}
631        Err(terr) => {
632            // This function gets called during `compare_method_predicate_entailment` when normalizing a
633            // signature that contains RPITIT. When the method signatures don't match, we have to
634            // emit an error now because `compare_method_predicate_entailment` will not report the error
635            // when normalization fails.
636            let emitted = report_trait_method_mismatch(
637                infcx,
638                cause,
639                param_env,
640                terr,
641                (trait_m, trait_sig),
642                (impl_m, impl_sig),
643                impl_trait_ref,
644            );
645            return Err(emitted);
646        }
647    }
648
649    if !unnormalized_trait_sig.output().references_error() && collector.types.is_empty() {
650        tcx.dcx().delayed_bug(
651            "expect >0 RPITITs in call to `collect_return_position_impl_trait_in_trait_tys`",
652        );
653    }
654
655    // FIXME: This has the same issue as #108544, but since this isn't breaking
656    // existing code, I'm not particularly inclined to do the same hack as above
657    // where we process wf obligations manually. This can be fixed in a forward-
658    // compatible way later.
659    let collected_types = collector.types;
660    for (_, &(ty, _)) in &collected_types {
661        ocx.register_obligation(traits::Obligation::new(
662            tcx,
663            misc_cause.clone(),
664            param_env,
665            ty::ClauseKind::WellFormed(ty.into()),
666        ));
667    }
668
669    // Check that all obligations are satisfied by the implementation's
670    // RPITs.
671    let errors = ocx.evaluate_obligations_error_on_ambiguity();
672    if !errors.is_empty() {
673        if let Err(guar) = try_report_async_mismatch(tcx, infcx, &errors, trait_m, impl_m, impl_sig)
674        {
675            return Err(guar);
676        }
677
678        let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
679        return Err(guar);
680    }
681
682    // Finally, resolve all regions. This catches wily misuses of
683    // lifetime parameters.
684    ocx.resolve_regions_and_report_errors(impl_m_def_id, param_env, wf_tys)?;
685
686    let mut remapped_types = DefIdMap::default();
687    for (def_id, (ty, args)) in collected_types {
688        match infcx.fully_resolve(ty) {
689            Ok(ty) => {
690                // `ty` contains free regions that we created earlier while liberating the
691                // trait fn signature. However, projection normalization expects `ty` to
692                // contains `def_id`'s early-bound regions.
693                let id_args = GenericArgs::identity_for_item(tcx, def_id);
694                debug!(?id_args, ?args);
695                let map: FxIndexMap<_, _> = std::iter::zip(args, id_args)
696                    .skip(tcx.generics_of(trait_m.def_id).count())
697                    .filter_map(|(a, b)| Some((a.as_region()?, b.as_region()?)))
698                    .collect();
699                debug!(?map);
700
701                // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound
702                // region args that are synthesized during AST lowering. These are args
703                // that are appended to the parent args (trait and trait method). However,
704                // we're trying to infer the uninstantiated type value of the RPITIT inside
705                // the *impl*, so we can later use the impl's method args to normalize
706                // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`).
707                //
708                // Due to the design of RPITITs, during AST lowering, we have no idea that
709                // an impl method corresponds to a trait method with RPITITs in it. Therefore,
710                // we don't have a list of early-bound region args for the RPITIT in the impl.
711                // Since early region parameters are index-based, we can't just rebase these
712                // (trait method) early-bound region args onto the impl, and there's no
713                // guarantee that the indices from the trait args and impl args line up.
714                // So to fix this, we subtract the number of trait args and add the number of
715                // impl args to *renumber* these early-bound regions to their corresponding
716                // indices in the impl's generic parameters list.
717                //
718                // Also, we only need to account for a difference in trait and impl args,
719                // since we previously enforce that the trait method and impl method have the
720                // same generics.
721                let num_trait_args = impl_trait_ref.args.len();
722                let num_impl_args = tcx.generics_of(impl_m.container_id(tcx)).own_params.len();
723                let ty = match ty.try_fold_with(&mut RemapHiddenTyRegions {
724                    tcx,
725                    map,
726                    num_trait_args,
727                    num_impl_args,
728                    def_id,
729                    impl_m_def_id: impl_m.def_id,
730                    ty,
731                    return_span,
732                }) {
733                    Ok(ty) => ty,
734                    Err(guar) => Ty::new_error(tcx, guar),
735                };
736                remapped_types.insert(def_id, ty::EarlyBinder::bind(ty));
737            }
738            Err(err) => {
739                // This code path is not reached in any tests, but may be
740                // reachable. If this is triggered, it should be converted to
741                // `span_delayed_bug` and the triggering case turned into a
742                // test.
743                tcx.dcx()
744                    .span_bug(return_span, format!("could not fully resolve: {ty} => {err:?}"));
745            }
746        }
747    }
748
749    // We may not collect all RPITITs that we see in the HIR for a trait signature
750    // because an RPITIT was located within a missing item. Like if we have a sig
751    // returning `-> Missing<impl Sized>`, that gets converted to `-> {type error}`,
752    // and when walking through the signature we end up never collecting the def id
753    // of the `impl Sized`. Insert that here, so we don't ICE later.
754    for assoc_item in tcx.associated_types_for_impl_traits_in_associated_fn(trait_m.def_id) {
755        if !remapped_types.contains_key(assoc_item) {
756            remapped_types.insert(
757                *assoc_item,
758                ty::EarlyBinder::bind(Ty::new_error_with_message(
759                    tcx,
760                    return_span,
761                    "missing synthetic item for RPITIT",
762                )),
763            );
764        }
765    }
766
767    Ok(&*tcx.arena.alloc(remapped_types))
768}
769
770struct ImplTraitInTraitCollector<'a, 'tcx, E> {
771    ocx: &'a ObligationCtxt<'a, 'tcx, E>,
772    types: FxIndexMap<DefId, (Ty<'tcx>, ty::GenericArgsRef<'tcx>)>,
773    span: Span,
774    param_env: ty::ParamEnv<'tcx>,
775    body_id: LocalDefId,
776}
777
778impl<'a, 'tcx, E> ImplTraitInTraitCollector<'a, 'tcx, E>
779where
780    E: 'tcx,
781{
782    fn new(
783        ocx: &'a ObligationCtxt<'a, 'tcx, E>,
784        span: Span,
785        param_env: ty::ParamEnv<'tcx>,
786        body_id: LocalDefId,
787    ) -> Self {
788        ImplTraitInTraitCollector { ocx, types: FxIndexMap::default(), span, param_env, body_id }
789    }
790}
791
792impl<'tcx, E> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx, E>
793where
794    E: 'tcx,
795{
796    fn cx(&self) -> TyCtxt<'tcx> {
797        self.ocx.infcx.tcx
798    }
799
800    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
801        if let ty::Alias(ty::Projection, proj) = ty.kind()
802            && self.cx().is_impl_trait_in_trait(proj.def_id)
803        {
804            if let Some((ty, _)) = self.types.get(&proj.def_id) {
805                return *ty;
806            }
807            //FIXME(RPITIT): Deny nested RPITIT in args too
808            if proj.args.has_escaping_bound_vars() {
809                bug!("FIXME(RPITIT): error here");
810            }
811            // Replace with infer var
812            let infer_ty = self.ocx.infcx.next_ty_var(self.span);
813            self.types.insert(proj.def_id, (infer_ty, proj.args));
814            // Recurse into bounds
815            for (pred, pred_span) in self
816                .cx()
817                .explicit_item_bounds(proj.def_id)
818                .iter_instantiated_copied(self.cx(), proj.args)
819            {
820                let pred = pred.fold_with(self);
821                let pred = self.ocx.normalize(
822                    &ObligationCause::misc(self.span, self.body_id),
823                    self.param_env,
824                    pred,
825                );
826
827                self.ocx.register_obligation(traits::Obligation::new(
828                    self.cx(),
829                    ObligationCause::new(
830                        self.span,
831                        self.body_id,
832                        ObligationCauseCode::WhereClause(proj.def_id, pred_span),
833                    ),
834                    self.param_env,
835                    pred,
836                ));
837            }
838            infer_ty
839        } else {
840            ty.super_fold_with(self)
841        }
842    }
843}
844
845struct RemapHiddenTyRegions<'tcx> {
846    tcx: TyCtxt<'tcx>,
847    /// Map from early/late params of the impl to identity regions of the RPITIT (GAT)
848    /// in the trait.
849    map: FxIndexMap<ty::Region<'tcx>, ty::Region<'tcx>>,
850    num_trait_args: usize,
851    num_impl_args: usize,
852    /// Def id of the RPITIT (GAT) in the *trait*.
853    def_id: DefId,
854    /// Def id of the impl method which owns the opaque hidden type we're remapping.
855    impl_m_def_id: DefId,
856    /// The hidden type we're remapping. Useful for diagnostics.
857    ty: Ty<'tcx>,
858    /// Span of the return type. Useful for diagnostics.
859    return_span: Span,
860}
861
862impl<'tcx> ty::FallibleTypeFolder<TyCtxt<'tcx>> for RemapHiddenTyRegions<'tcx> {
863    type Error = ErrorGuaranteed;
864
865    fn cx(&self) -> TyCtxt<'tcx> {
866        self.tcx
867    }
868
869    fn try_fold_region(
870        &mut self,
871        region: ty::Region<'tcx>,
872    ) -> Result<ty::Region<'tcx>, Self::Error> {
873        match region.kind() {
874            // Never remap bound regions or `'static`
875            ty::ReBound(..) | ty::ReStatic | ty::ReError(_) => return Ok(region),
876            // We always remap liberated late-bound regions from the function.
877            ty::ReLateParam(_) => {}
878            // Remap early-bound regions as long as they don't come from the `impl` itself,
879            // in which case we don't really need to renumber them.
880            ty::ReEarlyParam(ebr) => {
881                if ebr.index as usize >= self.num_impl_args {
882                    // Remap
883                } else {
884                    return Ok(region);
885                }
886            }
887            ty::ReVar(_) | ty::RePlaceholder(_) | ty::ReErased => unreachable!(
888                "should not have leaked vars or placeholders into hidden type of RPITIT"
889            ),
890        }
891
892        let e = if let Some(id_region) = self.map.get(&region) {
893            if let ty::ReEarlyParam(e) = id_region.kind() {
894                e
895            } else {
896                bug!(
897                    "expected to map region {region} to early-bound identity region, but got {id_region}"
898                );
899            }
900        } else {
901            let guar = match region.opt_param_def_id(self.tcx, self.impl_m_def_id) {
902                Some(def_id) => {
903                    let return_span = if let ty::Alias(ty::Opaque, opaque_ty) = self.ty.kind() {
904                        self.tcx.def_span(opaque_ty.def_id)
905                    } else {
906                        self.return_span
907                    };
908                    self.tcx
909                        .dcx()
910                        .struct_span_err(
911                            return_span,
912                            "return type captures more lifetimes than trait definition",
913                        )
914                        .with_span_label(self.tcx.def_span(def_id), "this lifetime was captured")
915                        .with_span_note(
916                            self.tcx.def_span(self.def_id),
917                            "hidden type must only reference lifetimes captured by this impl trait",
918                        )
919                        .with_note(format!("hidden type inferred to be `{}`", self.ty))
920                        .emit()
921                }
922                None => {
923                    // This code path is not reached in any tests, but may be
924                    // reachable. If this is triggered, it should be converted
925                    // to `delayed_bug` and the triggering case turned into a
926                    // test.
927                    self.tcx.dcx().bug("should've been able to remap region");
928                }
929            };
930            return Err(guar);
931        };
932
933        Ok(ty::Region::new_early_param(
934            self.tcx,
935            ty::EarlyParamRegion {
936                name: e.name,
937                index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32,
938            },
939        ))
940    }
941}
942
943/// Gets the string for an explicit self declaration, e.g. "self", "&self",
944/// etc.
945fn get_self_string<'tcx, P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> String
946where
947    P: Fn(Ty<'tcx>) -> bool,
948{
949    if is_self_ty(self_arg_ty) {
950        "self".to_owned()
951    } else if let ty::Ref(_, ty, mutbl) = self_arg_ty.kind()
952        && is_self_ty(*ty)
953    {
954        match mutbl {
955            hir::Mutability::Not => "&self".to_owned(),
956            hir::Mutability::Mut => "&mut self".to_owned(),
957        }
958    } else {
959        format!("self: {self_arg_ty}")
960    }
961}
962
963fn report_trait_method_mismatch<'tcx>(
964    infcx: &InferCtxt<'tcx>,
965    mut cause: ObligationCause<'tcx>,
966    param_env: ty::ParamEnv<'tcx>,
967    terr: TypeError<'tcx>,
968    (trait_m, trait_sig): (ty::AssocItem, ty::FnSig<'tcx>),
969    (impl_m, impl_sig): (ty::AssocItem, ty::FnSig<'tcx>),
970    impl_trait_ref: ty::TraitRef<'tcx>,
971) -> ErrorGuaranteed {
972    let tcx = infcx.tcx;
973    let (impl_err_span, trait_err_span) =
974        extract_spans_for_error_reporting(infcx, terr, &cause, impl_m, trait_m);
975
976    let mut diag = struct_span_code_err!(
977        tcx.dcx(),
978        impl_err_span,
979        E0053,
980        "method `{}` has an incompatible type for trait",
981        trait_m.name()
982    );
983    match &terr {
984        TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
985            if trait_m.is_method() =>
986        {
987            let ty = trait_sig.inputs()[0];
988            let sugg = get_self_string(ty, |ty| ty == impl_trait_ref.self_ty());
989
990            // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
991            // span points only at the type `Box<Self`>, but we want to cover the whole
992            // argument pattern and type.
993            let (sig, body) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
994            let span = tcx
995                .hir_body_param_idents(body)
996                .zip(sig.decl.inputs.iter())
997                .map(|(param_ident, ty)| {
998                    if let Some(param_ident) = param_ident {
999                        param_ident.span.to(ty.span)
1000                    } else {
1001                        ty.span
1002                    }
1003                })
1004                .next()
1005                .unwrap_or(impl_err_span);
1006
1007            diag.span_suggestion_verbose(
1008                span,
1009                "change the self-receiver type to match the trait",
1010                sugg,
1011                Applicability::MachineApplicable,
1012            );
1013        }
1014        TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
1015            if trait_sig.inputs().len() == *i {
1016                // Suggestion to change output type. We do not suggest in `async` functions
1017                // to avoid complex logic or incorrect output.
1018                if let ImplItemKind::Fn(sig, _) =
1019                    &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).kind
1020                    && !sig.header.asyncness.is_async()
1021                {
1022                    let msg = "change the output type to match the trait";
1023                    let ap = Applicability::MachineApplicable;
1024                    match sig.decl.output {
1025                        hir::FnRetTy::DefaultReturn(sp) => {
1026                            let sugg = format!(" -> {}", trait_sig.output());
1027                            diag.span_suggestion_verbose(sp, msg, sugg, ap);
1028                        }
1029                        hir::FnRetTy::Return(hir_ty) => {
1030                            let sugg = trait_sig.output();
1031                            diag.span_suggestion_verbose(hir_ty.span, msg, sugg, ap);
1032                        }
1033                    };
1034                };
1035            } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
1036                diag.span_suggestion_verbose(
1037                    impl_err_span,
1038                    "change the parameter type to match the trait",
1039                    trait_ty,
1040                    Applicability::MachineApplicable,
1041                );
1042            }
1043        }
1044        _ => {}
1045    }
1046
1047    cause.span = impl_err_span;
1048    infcx.err_ctxt().note_type_err(
1049        &mut diag,
1050        &cause,
1051        trait_err_span.map(|sp| (sp, Cow::from("type in trait"), false)),
1052        Some(param_env.and(infer::ValuePairs::PolySigs(ExpectedFound {
1053            expected: ty::Binder::dummy(trait_sig),
1054            found: ty::Binder::dummy(impl_sig),
1055        }))),
1056        terr,
1057        false,
1058        None,
1059    );
1060
1061    diag.emit()
1062}
1063
1064fn check_region_bounds_on_impl_item<'tcx>(
1065    tcx: TyCtxt<'tcx>,
1066    impl_m: ty::AssocItem,
1067    trait_m: ty::AssocItem,
1068    delay: bool,
1069) -> Result<(), ErrorGuaranteed> {
1070    let impl_generics = tcx.generics_of(impl_m.def_id);
1071    let impl_params = impl_generics.own_counts().lifetimes;
1072
1073    let trait_generics = tcx.generics_of(trait_m.def_id);
1074    let trait_params = trait_generics.own_counts().lifetimes;
1075
1076    debug!(?trait_generics, ?impl_generics);
1077
1078    // Must have same number of early-bound lifetime parameters.
1079    // Unfortunately, if the user screws up the bounds, then this
1080    // will change classification between early and late. E.g.,
1081    // if in trait we have `<'a,'b:'a>`, and in impl we just have
1082    // `<'a,'b>`, then we have 2 early-bound lifetime parameters
1083    // in trait but 0 in the impl. But if we report "expected 2
1084    // but found 0" it's confusing, because it looks like there
1085    // are zero. Since I don't quite know how to phrase things at
1086    // the moment, give a kind of vague error message.
1087    if trait_params == impl_params {
1088        return Ok(());
1089    }
1090
1091    if !delay && let Some(guar) = check_region_late_boundedness(tcx, impl_m, trait_m) {
1092        return Err(guar);
1093    }
1094
1095    let span = tcx
1096        .hir_get_generics(impl_m.def_id.expect_local())
1097        .expect("expected impl item to have generics or else we can't compare them")
1098        .span;
1099
1100    let mut generics_span = None;
1101    let mut bounds_span = vec![];
1102    let mut where_span = None;
1103
1104    if let Some(trait_node) = tcx.hir_get_if_local(trait_m.def_id)
1105        && let Some(trait_generics) = trait_node.generics()
1106    {
1107        generics_span = Some(trait_generics.span);
1108        // FIXME: we could potentially look at the impl's bounds to not point at bounds that
1109        // *are* present in the impl.
1110        for p in trait_generics.predicates {
1111            match p.kind {
1112                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1113                    bounds,
1114                    ..
1115                })
1116                | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1117                    bounds,
1118                    ..
1119                }) => {
1120                    for b in *bounds {
1121                        if let hir::GenericBound::Outlives(lt) = b {
1122                            bounds_span.push(lt.ident.span);
1123                        }
1124                    }
1125                }
1126                _ => {}
1127            }
1128        }
1129        if let Some(impl_node) = tcx.hir_get_if_local(impl_m.def_id)
1130            && let Some(impl_generics) = impl_node.generics()
1131        {
1132            let mut impl_bounds = 0;
1133            for p in impl_generics.predicates {
1134                match p.kind {
1135                    hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1136                        bounds,
1137                        ..
1138                    })
1139                    | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1140                        bounds,
1141                        ..
1142                    }) => {
1143                        for b in *bounds {
1144                            if let hir::GenericBound::Outlives(_) = b {
1145                                impl_bounds += 1;
1146                            }
1147                        }
1148                    }
1149                    _ => {}
1150                }
1151            }
1152            if impl_bounds == bounds_span.len() {
1153                bounds_span = vec![];
1154            } else if impl_generics.has_where_clause_predicates {
1155                where_span = Some(impl_generics.where_clause_span);
1156            }
1157        }
1158    }
1159
1160    let reported = tcx
1161        .dcx()
1162        .create_err(LifetimesOrBoundsMismatchOnTrait {
1163            span,
1164            item_kind: impl_m.descr(),
1165            ident: impl_m.ident(tcx),
1166            generics_span,
1167            bounds_span,
1168            where_span,
1169        })
1170        .emit_unless_delay(delay);
1171
1172    Err(reported)
1173}
1174
1175#[allow(unused)]
1176enum LateEarlyMismatch<'tcx> {
1177    EarlyInImpl(DefId, DefId, ty::Region<'tcx>),
1178    LateInImpl(DefId, DefId, ty::Region<'tcx>),
1179}
1180
1181fn check_region_late_boundedness<'tcx>(
1182    tcx: TyCtxt<'tcx>,
1183    impl_m: ty::AssocItem,
1184    trait_m: ty::AssocItem,
1185) -> Option<ErrorGuaranteed> {
1186    if !impl_m.is_fn() {
1187        return None;
1188    }
1189
1190    let (infcx, param_env) = tcx
1191        .infer_ctxt()
1192        .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, impl_m.def_id));
1193
1194    let impl_m_args = infcx.fresh_args_for_item(DUMMY_SP, impl_m.def_id);
1195    let impl_m_sig = tcx.fn_sig(impl_m.def_id).instantiate(tcx, impl_m_args);
1196    let impl_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, impl_m_sig);
1197
1198    let trait_m_args = infcx.fresh_args_for_item(DUMMY_SP, trait_m.def_id);
1199    let trait_m_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_args);
1200    let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_m_sig);
1201
1202    let ocx = ObligationCtxt::new(&infcx);
1203
1204    // Equate the signatures so that we can infer whether a late-bound param was present where
1205    // an early-bound param was expected, since we replace the late-bound lifetimes with
1206    // `ReLateParam`, and early-bound lifetimes with infer vars, so the early-bound args will
1207    // resolve to `ReLateParam` if there is a mismatch.
1208    let Ok(()) = ocx.eq(
1209        &ObligationCause::dummy(),
1210        param_env,
1211        ty::Binder::dummy(trait_m_sig),
1212        ty::Binder::dummy(impl_m_sig),
1213    ) else {
1214        return None;
1215    };
1216
1217    let errors = ocx.try_evaluate_obligations();
1218    if !errors.is_empty() {
1219        return None;
1220    }
1221
1222    let mut mismatched = vec![];
1223
1224    let impl_generics = tcx.generics_of(impl_m.def_id);
1225    for (id_arg, arg) in
1226        std::iter::zip(ty::GenericArgs::identity_for_item(tcx, impl_m.def_id), impl_m_args)
1227    {
1228        if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1229            && let ty::ReVar(vid) = r.kind()
1230            && let r = infcx
1231                .inner
1232                .borrow_mut()
1233                .unwrap_region_constraints()
1234                .opportunistic_resolve_var(tcx, vid)
1235            && let ty::ReLateParam(ty::LateParamRegion {
1236                kind: ty::LateParamRegionKind::Named(trait_param_def_id),
1237                ..
1238            }) = r.kind()
1239            && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1240        {
1241            mismatched.push(LateEarlyMismatch::EarlyInImpl(
1242                impl_generics.region_param(ebr, tcx).def_id,
1243                trait_param_def_id,
1244                id_arg.expect_region(),
1245            ));
1246        }
1247    }
1248
1249    let trait_generics = tcx.generics_of(trait_m.def_id);
1250    for (id_arg, arg) in
1251        std::iter::zip(ty::GenericArgs::identity_for_item(tcx, trait_m.def_id), trait_m_args)
1252    {
1253        if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1254            && let ty::ReVar(vid) = r.kind()
1255            && let r = infcx
1256                .inner
1257                .borrow_mut()
1258                .unwrap_region_constraints()
1259                .opportunistic_resolve_var(tcx, vid)
1260            && let ty::ReLateParam(ty::LateParamRegion {
1261                kind: ty::LateParamRegionKind::Named(impl_param_def_id),
1262                ..
1263            }) = r.kind()
1264            && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1265        {
1266            mismatched.push(LateEarlyMismatch::LateInImpl(
1267                impl_param_def_id,
1268                trait_generics.region_param(ebr, tcx).def_id,
1269                id_arg.expect_region(),
1270            ));
1271        }
1272    }
1273
1274    if mismatched.is_empty() {
1275        return None;
1276    }
1277
1278    let spans: Vec<_> = mismatched
1279        .iter()
1280        .map(|param| {
1281            let (LateEarlyMismatch::EarlyInImpl(impl_param_def_id, ..)
1282            | LateEarlyMismatch::LateInImpl(impl_param_def_id, ..)) = param;
1283            tcx.def_span(impl_param_def_id)
1284        })
1285        .collect();
1286
1287    let mut diag = tcx
1288        .dcx()
1289        .struct_span_err(spans, "lifetime parameters do not match the trait definition")
1290        .with_note("lifetime parameters differ in whether they are early- or late-bound")
1291        .with_code(E0195);
1292    for mismatch in mismatched {
1293        match mismatch {
1294            LateEarlyMismatch::EarlyInImpl(
1295                impl_param_def_id,
1296                trait_param_def_id,
1297                early_bound_region,
1298            ) => {
1299                let mut multispan = MultiSpan::from_spans(vec![
1300                    tcx.def_span(impl_param_def_id),
1301                    tcx.def_span(trait_param_def_id),
1302                ]);
1303                multispan
1304                    .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1305                multispan
1306                    .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1307                multispan.push_span_label(
1308                    tcx.def_span(impl_param_def_id),
1309                    format!("`{}` is early-bound", tcx.item_name(impl_param_def_id)),
1310                );
1311                multispan.push_span_label(
1312                    tcx.def_span(trait_param_def_id),
1313                    format!("`{}` is late-bound", tcx.item_name(trait_param_def_id)),
1314                );
1315                if let Some(span) =
1316                    find_region_in_predicates(tcx, impl_m.def_id, early_bound_region)
1317                {
1318                    multispan.push_span_label(
1319                        span,
1320                        format!(
1321                            "this lifetime bound makes `{}` early-bound",
1322                            tcx.item_name(impl_param_def_id)
1323                        ),
1324                    );
1325                }
1326                diag.span_note(
1327                    multispan,
1328                    format!(
1329                        "`{}` differs between the trait and impl",
1330                        tcx.item_name(impl_param_def_id)
1331                    ),
1332                );
1333            }
1334            LateEarlyMismatch::LateInImpl(
1335                impl_param_def_id,
1336                trait_param_def_id,
1337                early_bound_region,
1338            ) => {
1339                let mut multispan = MultiSpan::from_spans(vec![
1340                    tcx.def_span(impl_param_def_id),
1341                    tcx.def_span(trait_param_def_id),
1342                ]);
1343                multispan
1344                    .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1345                multispan
1346                    .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1347                multispan.push_span_label(
1348                    tcx.def_span(impl_param_def_id),
1349                    format!("`{}` is late-bound", tcx.item_name(impl_param_def_id)),
1350                );
1351                multispan.push_span_label(
1352                    tcx.def_span(trait_param_def_id),
1353                    format!("`{}` is early-bound", tcx.item_name(trait_param_def_id)),
1354                );
1355                if let Some(span) =
1356                    find_region_in_predicates(tcx, trait_m.def_id, early_bound_region)
1357                {
1358                    multispan.push_span_label(
1359                        span,
1360                        format!(
1361                            "this lifetime bound makes `{}` early-bound",
1362                            tcx.item_name(trait_param_def_id)
1363                        ),
1364                    );
1365                }
1366                diag.span_note(
1367                    multispan,
1368                    format!(
1369                        "`{}` differs between the trait and impl",
1370                        tcx.item_name(impl_param_def_id)
1371                    ),
1372                );
1373            }
1374        }
1375    }
1376
1377    Some(diag.emit())
1378}
1379
1380fn find_region_in_predicates<'tcx>(
1381    tcx: TyCtxt<'tcx>,
1382    def_id: DefId,
1383    early_bound_region: ty::Region<'tcx>,
1384) -> Option<Span> {
1385    for (pred, span) in tcx.explicit_predicates_of(def_id).instantiate_identity(tcx) {
1386        if pred.visit_with(&mut FindRegion(early_bound_region)).is_break() {
1387            return Some(span);
1388        }
1389    }
1390
1391    struct FindRegion<'tcx>(ty::Region<'tcx>);
1392    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindRegion<'tcx> {
1393        type Result = ControlFlow<()>;
1394        fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
1395            if r == self.0 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
1396        }
1397    }
1398
1399    None
1400}
1401
1402#[instrument(level = "debug", skip(infcx))]
1403fn extract_spans_for_error_reporting<'tcx>(
1404    infcx: &infer::InferCtxt<'tcx>,
1405    terr: TypeError<'_>,
1406    cause: &ObligationCause<'tcx>,
1407    impl_m: ty::AssocItem,
1408    trait_m: ty::AssocItem,
1409) -> (Span, Option<Span>) {
1410    let tcx = infcx.tcx;
1411    let mut impl_args = {
1412        let (sig, _) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1413        sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1414    };
1415
1416    let trait_args = trait_m.def_id.as_local().map(|def_id| {
1417        let (sig, _) = tcx.hir_expect_trait_item(def_id).expect_fn();
1418        sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1419    });
1420
1421    match terr {
1422        TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1423            (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1424        }
1425        _ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
1426    }
1427}
1428
1429fn compare_self_type<'tcx>(
1430    tcx: TyCtxt<'tcx>,
1431    impl_m: ty::AssocItem,
1432    trait_m: ty::AssocItem,
1433    impl_trait_ref: ty::TraitRef<'tcx>,
1434    delay: bool,
1435) -> Result<(), ErrorGuaranteed> {
1436    // Try to give more informative error messages about self typing
1437    // mismatches. Note that any mismatch will also be detected
1438    // below, where we construct a canonical function type that
1439    // includes the self parameter as a normal parameter. It's just
1440    // that the error messages you get out of this code are a bit more
1441    // inscrutable, particularly for cases where one method has no
1442    // self.
1443
1444    let self_string = |method: ty::AssocItem| {
1445        let untransformed_self_ty = match method.container {
1446            ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1447                impl_trait_ref.self_ty()
1448            }
1449            ty::AssocContainer::Trait => tcx.types.self_param,
1450        };
1451        let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().input(0);
1452        let (infcx, param_env) = tcx
1453            .infer_ctxt()
1454            .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, method.def_id));
1455        let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1456        let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
1457        get_self_string(self_arg_ty, can_eq_self)
1458    };
1459
1460    match (trait_m.is_method(), impl_m.is_method()) {
1461        (false, false) | (true, true) => {}
1462
1463        (false, true) => {
1464            let self_descr = self_string(impl_m);
1465            let impl_m_span = tcx.def_span(impl_m.def_id);
1466            let mut err = struct_span_code_err!(
1467                tcx.dcx(),
1468                impl_m_span,
1469                E0185,
1470                "method `{}` has a `{}` declaration in the impl, but not in the trait",
1471                trait_m.name(),
1472                self_descr
1473            );
1474            err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
1475            if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1476                err.span_label(span, format!("trait method declared without `{self_descr}`"));
1477            } else {
1478                err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1479            }
1480            return Err(err.emit_unless_delay(delay));
1481        }
1482
1483        (true, false) => {
1484            let self_descr = self_string(trait_m);
1485            let impl_m_span = tcx.def_span(impl_m.def_id);
1486            let mut err = struct_span_code_err!(
1487                tcx.dcx(),
1488                impl_m_span,
1489                E0186,
1490                "method `{}` has a `{}` declaration in the trait, but not in the impl",
1491                trait_m.name(),
1492                self_descr
1493            );
1494            err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
1495            if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1496                err.span_label(span, format!("`{self_descr}` used in trait"));
1497            } else {
1498                err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1499            }
1500
1501            return Err(err.emit_unless_delay(delay));
1502        }
1503    }
1504
1505    Ok(())
1506}
1507
1508/// Checks that the number of generics on a given assoc item in a trait impl is the same
1509/// as the number of generics on the respective assoc item in the trait definition.
1510///
1511/// For example this code emits the errors in the following code:
1512/// ```rust,compile_fail
1513/// trait Trait {
1514///     fn foo();
1515///     type Assoc<T>;
1516/// }
1517///
1518/// impl Trait for () {
1519///     fn foo<T>() {}
1520///     //~^ error
1521///     type Assoc = u32;
1522///     //~^ error
1523/// }
1524/// ```
1525///
1526/// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
1527/// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
1528/// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
1529fn compare_number_of_generics<'tcx>(
1530    tcx: TyCtxt<'tcx>,
1531    impl_: ty::AssocItem,
1532    trait_: ty::AssocItem,
1533    delay: bool,
1534) -> Result<(), ErrorGuaranteed> {
1535    let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1536    let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1537
1538    // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
1539    // in `compare_generic_param_kinds` which will give a nicer error message than something like:
1540    // "expected 1 type parameter, found 0 type parameters"
1541    if (trait_own_counts.types + trait_own_counts.consts)
1542        == (impl_own_counts.types + impl_own_counts.consts)
1543    {
1544        return Ok(());
1545    }
1546
1547    // We never need to emit a separate error for RPITITs, since if an RPITIT
1548    // has mismatched type or const generic arguments, then the method that it's
1549    // inheriting the generics from will also have mismatched arguments, and
1550    // we'll report an error for that instead. Delay a bug for safety, though.
1551    if trait_.is_impl_trait_in_trait() {
1552        // FIXME: no tests trigger this. If you find example code that does
1553        // trigger this, please add it to the test suite.
1554        tcx.dcx()
1555            .bug("errors comparing numbers of generics of trait/impl functions were not emitted");
1556    }
1557
1558    let matchings = [
1559        ("type", trait_own_counts.types, impl_own_counts.types),
1560        ("const", trait_own_counts.consts, impl_own_counts.consts),
1561    ];
1562
1563    let item_kind = impl_.descr();
1564
1565    let mut err_occurred = None;
1566    for (kind, trait_count, impl_count) in matchings {
1567        if impl_count != trait_count {
1568            let arg_spans = |item: &ty::AssocItem, generics: &hir::Generics<'_>| {
1569                let mut spans = generics
1570                    .params
1571                    .iter()
1572                    .filter(|p| match p.kind {
1573                        hir::GenericParamKind::Lifetime {
1574                            kind: hir::LifetimeParamKind::Elided(_),
1575                        } => {
1576                            // A fn can have an arbitrary number of extra elided lifetimes for the
1577                            // same signature.
1578                            !item.is_fn()
1579                        }
1580                        _ => true,
1581                    })
1582                    .map(|p| p.span)
1583                    .collect::<Vec<Span>>();
1584                if spans.is_empty() {
1585                    spans = vec![generics.span]
1586                }
1587                spans
1588            };
1589            let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1590                let trait_item = tcx.hir_expect_trait_item(def_id);
1591                let arg_spans: Vec<Span> = arg_spans(&trait_, trait_item.generics);
1592                let impl_trait_spans: Vec<Span> = trait_item
1593                    .generics
1594                    .params
1595                    .iter()
1596                    .filter_map(|p| match p.kind {
1597                        GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1598                        _ => None,
1599                    })
1600                    .collect();
1601                (Some(arg_spans), impl_trait_spans)
1602            } else {
1603                let trait_span = tcx.hir_span_if_local(trait_.def_id);
1604                (trait_span.map(|s| vec![s]), vec![])
1605            };
1606
1607            let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
1608            let impl_item_impl_trait_spans: Vec<Span> = impl_item
1609                .generics
1610                .params
1611                .iter()
1612                .filter_map(|p| match p.kind {
1613                    GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1614                    _ => None,
1615                })
1616                .collect();
1617            let spans = arg_spans(&impl_, impl_item.generics);
1618            let span = spans.first().copied();
1619
1620            let mut err = tcx.dcx().struct_span_err(
1621                spans,
1622                format!(
1623                    "{} `{}` has {} {kind} parameter{} but its trait \
1624                     declaration has {} {kind} parameter{}",
1625                    item_kind,
1626                    trait_.name(),
1627                    impl_count,
1628                    pluralize!(impl_count),
1629                    trait_count,
1630                    pluralize!(trait_count),
1631                    kind = kind,
1632                ),
1633            );
1634            err.code(E0049);
1635
1636            let msg =
1637                format!("expected {trait_count} {kind} parameter{}", pluralize!(trait_count),);
1638            if let Some(spans) = trait_spans {
1639                let mut spans = spans.iter();
1640                if let Some(span) = spans.next() {
1641                    err.span_label(*span, msg);
1642                }
1643                for span in spans {
1644                    err.span_label(*span, "");
1645                }
1646            } else {
1647                err.span_label(tcx.def_span(trait_.def_id), msg);
1648            }
1649
1650            if let Some(span) = span {
1651                err.span_label(
1652                    span,
1653                    format!("found {} {} parameter{}", impl_count, kind, pluralize!(impl_count),),
1654                );
1655            }
1656
1657            for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1658                err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1659            }
1660
1661            let reported = err.emit_unless_delay(delay);
1662            err_occurred = Some(reported);
1663        }
1664    }
1665
1666    if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1667}
1668
1669fn compare_number_of_method_arguments<'tcx>(
1670    tcx: TyCtxt<'tcx>,
1671    impl_m: ty::AssocItem,
1672    trait_m: ty::AssocItem,
1673    delay: bool,
1674) -> Result<(), ErrorGuaranteed> {
1675    let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1676    let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1677    let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
1678    let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1679
1680    if trait_number_args != impl_number_args {
1681        let trait_span = trait_m
1682            .def_id
1683            .as_local()
1684            .and_then(|def_id| {
1685                let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
1686                let pos = trait_number_args.saturating_sub(1);
1687                trait_m_sig.decl.inputs.get(pos).map(|arg| {
1688                    if pos == 0 {
1689                        arg.span
1690                    } else {
1691                        arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1692                    }
1693                })
1694            })
1695            .or_else(|| tcx.hir_span_if_local(trait_m.def_id));
1696
1697        let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1698        let pos = impl_number_args.saturating_sub(1);
1699        let impl_span = impl_m_sig
1700            .decl
1701            .inputs
1702            .get(pos)
1703            .map(|arg| {
1704                if pos == 0 {
1705                    arg.span
1706                } else {
1707                    arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1708                }
1709            })
1710            .unwrap_or_else(|| tcx.def_span(impl_m.def_id));
1711
1712        let mut err = struct_span_code_err!(
1713            tcx.dcx(),
1714            impl_span,
1715            E0050,
1716            "method `{}` has {} but the declaration in trait `{}` has {}",
1717            trait_m.name(),
1718            potentially_plural_count(impl_number_args, "parameter"),
1719            tcx.def_path_str(trait_m.def_id),
1720            trait_number_args
1721        );
1722
1723        if let Some(trait_span) = trait_span {
1724            err.span_label(
1725                trait_span,
1726                format!(
1727                    "trait requires {}",
1728                    potentially_plural_count(trait_number_args, "parameter")
1729                ),
1730            );
1731        } else {
1732            err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1733        }
1734
1735        err.span_label(
1736            impl_span,
1737            format!(
1738                "expected {}, found {}",
1739                potentially_plural_count(trait_number_args, "parameter"),
1740                impl_number_args
1741            ),
1742        );
1743
1744        return Err(err.emit_unless_delay(delay));
1745    }
1746
1747    Ok(())
1748}
1749
1750fn compare_synthetic_generics<'tcx>(
1751    tcx: TyCtxt<'tcx>,
1752    impl_m: ty::AssocItem,
1753    trait_m: ty::AssocItem,
1754    delay: bool,
1755) -> Result<(), ErrorGuaranteed> {
1756    // FIXME(chrisvittal) Clean up this function, list of FIXME items:
1757    //     1. Better messages for the span labels
1758    //     2. Explanation as to what is going on
1759    // If we get here, we already have the same number of generics, so the zip will
1760    // be okay.
1761    let mut error_found = None;
1762    let impl_m_generics = tcx.generics_of(impl_m.def_id);
1763    let trait_m_generics = tcx.generics_of(trait_m.def_id);
1764    let impl_m_type_params =
1765        impl_m_generics.own_params.iter().filter_map(|param| match param.kind {
1766            GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1767            GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1768        });
1769    let trait_m_type_params =
1770        trait_m_generics.own_params.iter().filter_map(|param| match param.kind {
1771            GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1772            GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1773        });
1774    for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1775        iter::zip(impl_m_type_params, trait_m_type_params)
1776    {
1777        if impl_synthetic != trait_synthetic {
1778            let impl_def_id = impl_def_id.expect_local();
1779            let impl_span = tcx.def_span(impl_def_id);
1780            let trait_span = tcx.def_span(trait_def_id);
1781            let mut err = struct_span_code_err!(
1782                tcx.dcx(),
1783                impl_span,
1784                E0643,
1785                "method `{}` has incompatible signature for trait",
1786                trait_m.name()
1787            );
1788            err.span_label(trait_span, "declaration in trait here");
1789            if impl_synthetic {
1790                // The case where the impl method uses `impl Trait` but the trait method uses
1791                // explicit generics
1792                err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1793                let _: Option<_> = try {
1794                    // try taking the name from the trait impl
1795                    // FIXME: this is obviously suboptimal since the name can already be used
1796                    // as another generic argument
1797                    let new_name = tcx.opt_item_name(trait_def_id)?;
1798                    let trait_m = trait_m.def_id.as_local()?;
1799                    let trait_m = tcx.hir_expect_trait_item(trait_m);
1800
1801                    let impl_m = impl_m.def_id.as_local()?;
1802                    let impl_m = tcx.hir_expect_impl_item(impl_m);
1803
1804                    // in case there are no generics, take the spot between the function name
1805                    // and the opening paren of the argument list
1806                    let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1807                    // in case there are generics, just replace them
1808                    let generics_span = impl_m.generics.span.substitute_dummy(new_generics_span);
1809                    // replace with the generics from the trait
1810                    let new_generics =
1811                        tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1812
1813                    err.multipart_suggestion(
1814                        "try changing the `impl Trait` argument to a generic parameter",
1815                        vec![
1816                            // replace `impl Trait` with `T`
1817                            (impl_span, new_name.to_string()),
1818                            // replace impl method generics with trait method generics
1819                            // This isn't quite right, as users might have changed the names
1820                            // of the generics, but it works for the common case
1821                            (generics_span, new_generics),
1822                        ],
1823                        Applicability::MaybeIncorrect,
1824                    );
1825                };
1826            } else {
1827                // The case where the trait method uses `impl Trait`, but the impl method uses
1828                // explicit generics.
1829                err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1830                let _: Option<_> = try {
1831                    let impl_m = impl_m.def_id.as_local()?;
1832                    let impl_m = tcx.hir_expect_impl_item(impl_m);
1833                    let (sig, _) = impl_m.expect_fn();
1834                    let input_tys = sig.decl.inputs;
1835
1836                    struct Visitor(hir::def_id::LocalDefId);
1837                    impl<'v> intravisit::Visitor<'v> for Visitor {
1838                        type Result = ControlFlow<Span>;
1839                        fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) -> Self::Result {
1840                            if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
1841                                && let Res::Def(DefKind::TyParam, def_id) = path.res
1842                                && def_id == self.0.to_def_id()
1843                            {
1844                                ControlFlow::Break(ty.span)
1845                            } else {
1846                                intravisit::walk_ty(self, ty)
1847                            }
1848                        }
1849                    }
1850
1851                    let span = input_tys
1852                        .iter()
1853                        .find_map(|ty| Visitor(impl_def_id).visit_ty_unambig(ty).break_value())?;
1854
1855                    let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
1856                    let bounds = bounds.first()?.span().to(bounds.last()?.span());
1857                    let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
1858
1859                    err.multipart_suggestion(
1860                        "try removing the generic parameter and using `impl Trait` instead",
1861                        vec![
1862                            // delete generic parameters
1863                            (impl_m.generics.span, String::new()),
1864                            // replace param usage with `impl Trait`
1865                            (span, format!("impl {bounds}")),
1866                        ],
1867                        Applicability::MaybeIncorrect,
1868                    );
1869                };
1870            }
1871            error_found = Some(err.emit_unless_delay(delay));
1872        }
1873    }
1874    if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
1875}
1876
1877/// Checks that all parameters in the generics of a given assoc item in a trait impl have
1878/// the same kind as the respective generic parameter in the trait def.
1879///
1880/// For example all 4 errors in the following code are emitted here:
1881/// ```rust,ignore (pseudo-Rust)
1882/// trait Foo {
1883///     fn foo<const N: u8>();
1884///     type Bar<const N: u8>;
1885///     fn baz<const N: u32>();
1886///     type Blah<T>;
1887/// }
1888///
1889/// impl Foo for () {
1890///     fn foo<const N: u64>() {}
1891///     //~^ error
1892///     type Bar<const N: u64> = ();
1893///     //~^ error
1894///     fn baz<T>() {}
1895///     //~^ error
1896///     type Blah<const N: i64> = u32;
1897///     //~^ error
1898/// }
1899/// ```
1900///
1901/// This function does not handle lifetime parameters
1902fn compare_generic_param_kinds<'tcx>(
1903    tcx: TyCtxt<'tcx>,
1904    impl_item: ty::AssocItem,
1905    trait_item: ty::AssocItem,
1906    delay: bool,
1907) -> Result<(), ErrorGuaranteed> {
1908    assert_eq!(impl_item.as_tag(), trait_item.as_tag());
1909
1910    let ty_const_params_of = |def_id| {
1911        tcx.generics_of(def_id).own_params.iter().filter(|param| {
1912            matches!(
1913                param.kind,
1914                GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1915            )
1916        })
1917    };
1918
1919    for (param_impl, param_trait) in
1920        iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1921    {
1922        use GenericParamDefKind::*;
1923        if match (&param_impl.kind, &param_trait.kind) {
1924            (Const { .. }, Const { .. })
1925                if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1926            {
1927                true
1928            }
1929            (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1930            // this is exhaustive so that anyone adding new generic param kinds knows
1931            // to make sure this error is reported for them.
1932            (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1933            (Lifetime { .. }, _) | (_, Lifetime { .. }) => {
1934                bug!("lifetime params are expected to be filtered by `ty_const_params_of`")
1935            }
1936        } {
1937            let param_impl_span = tcx.def_span(param_impl.def_id);
1938            let param_trait_span = tcx.def_span(param_trait.def_id);
1939
1940            let mut err = struct_span_code_err!(
1941                tcx.dcx(),
1942                param_impl_span,
1943                E0053,
1944                "{} `{}` has an incompatible generic parameter for trait `{}`",
1945                impl_item.descr(),
1946                trait_item.name(),
1947                &tcx.def_path_str(tcx.parent(trait_item.def_id))
1948            );
1949
1950            let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
1951                Const { .. } => {
1952                    format!(
1953                        "{} const parameter of type `{}`",
1954                        prefix,
1955                        tcx.type_of(param.def_id).instantiate_identity()
1956                    )
1957                }
1958                Type { .. } => format!("{prefix} type parameter"),
1959                Lifetime { .. } => span_bug!(
1960                    tcx.def_span(param.def_id),
1961                    "lifetime params are expected to be filtered by `ty_const_params_of`"
1962                ),
1963            };
1964
1965            let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
1966            err.span_label(trait_header_span, "");
1967            err.span_label(param_trait_span, make_param_message("expected", param_trait));
1968
1969            let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1970            err.span_label(impl_header_span, "");
1971            err.span_label(param_impl_span, make_param_message("found", param_impl));
1972
1973            let reported = err.emit_unless_delay(delay);
1974            return Err(reported);
1975        }
1976    }
1977
1978    Ok(())
1979}
1980
1981fn compare_impl_const<'tcx>(
1982    tcx: TyCtxt<'tcx>,
1983    impl_const_item: ty::AssocItem,
1984    trait_const_item: ty::AssocItem,
1985    impl_trait_ref: ty::TraitRef<'tcx>,
1986) -> Result<(), ErrorGuaranteed> {
1987    compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
1988    compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
1989    check_region_bounds_on_impl_item(tcx, impl_const_item, trait_const_item, false)?;
1990    compare_const_predicate_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
1991}
1992
1993/// The equivalent of [compare_method_predicate_entailment], but for associated constants
1994/// instead of associated functions.
1995// FIXME(generic_const_items): If possible extract the common parts of `compare_{type,const}_predicate_entailment`.
1996#[instrument(level = "debug", skip(tcx))]
1997fn compare_const_predicate_entailment<'tcx>(
1998    tcx: TyCtxt<'tcx>,
1999    impl_ct: ty::AssocItem,
2000    trait_ct: ty::AssocItem,
2001    impl_trait_ref: ty::TraitRef<'tcx>,
2002) -> Result<(), ErrorGuaranteed> {
2003    let impl_ct_def_id = impl_ct.def_id.expect_local();
2004    let impl_ct_span = tcx.def_span(impl_ct_def_id);
2005
2006    // The below is for the most part highly similar to the procedure
2007    // for methods above. It is simpler in many respects, especially
2008    // because we shouldn't really have to deal with lifetimes or
2009    // predicates. In fact some of this should probably be put into
2010    // shared functions because of DRY violations...
2011    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id).rebase_onto(
2012        tcx,
2013        impl_ct.container_id(tcx),
2014        impl_trait_ref.args,
2015    );
2016
2017    // Create a parameter environment that represents the implementation's
2018    // associated const.
2019    let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
2020
2021    let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
2022    let code = ObligationCauseCode::CompareImplItem {
2023        impl_item_def_id: impl_ct_def_id,
2024        trait_item_def_id: trait_ct.def_id,
2025        kind: impl_ct.kind,
2026    };
2027    let mut cause = ObligationCause::new(impl_ct_span, impl_ct_def_id, code.clone());
2028
2029    let impl_ct_predicates = tcx.predicates_of(impl_ct.def_id);
2030    let trait_ct_predicates = tcx.predicates_of(trait_ct.def_id);
2031
2032    // The predicates declared by the impl definition, the trait and the
2033    // associated const in the trait are assumed.
2034    let impl_predicates = tcx.predicates_of(impl_ct_predicates.parent.unwrap());
2035    let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2036    hybrid_preds.extend(
2037        trait_ct_predicates
2038            .instantiate_own(tcx, trait_to_impl_args)
2039            .map(|(predicate, _)| predicate),
2040    );
2041
2042    let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
2043    let param_env = traits::normalize_param_env_or_error(
2044        tcx,
2045        param_env,
2046        ObligationCause::misc(impl_ct_span, impl_ct_def_id),
2047    );
2048
2049    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2050    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2051
2052    let impl_ct_own_bounds = impl_ct_predicates.instantiate_own_identity();
2053    for (predicate, span) in impl_ct_own_bounds {
2054        let cause = ObligationCause::misc(span, impl_ct_def_id);
2055        let predicate = ocx.normalize(&cause, param_env, predicate);
2056
2057        let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
2058        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2059    }
2060
2061    // There is no "body" here, so just pass dummy id.
2062    let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
2063    debug!(?impl_ty);
2064
2065    let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
2066    debug!(?trait_ty);
2067
2068    let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
2069
2070    if let Err(terr) = err {
2071        debug!(?impl_ty, ?trait_ty);
2072
2073        // Locate the Span containing just the type of the offending impl
2074        let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
2075        cause.span = ty.span;
2076
2077        let mut diag = struct_span_code_err!(
2078            tcx.dcx(),
2079            cause.span,
2080            E0326,
2081            "implemented const `{}` has an incompatible type for trait",
2082            trait_ct.name()
2083        );
2084
2085        let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
2086            // Add a label to the Span containing just the type of the const
2087            let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
2088            ty.span
2089        });
2090
2091        infcx.err_ctxt().note_type_err(
2092            &mut diag,
2093            &cause,
2094            trait_c_span.map(|span| (span, Cow::from("type in trait"), false)),
2095            Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2096                expected: trait_ty.into(),
2097                found: impl_ty.into(),
2098            }))),
2099            terr,
2100            false,
2101            None,
2102        );
2103        return Err(diag.emit());
2104    };
2105
2106    // Check that all obligations are satisfied by the implementation's
2107    // version.
2108    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2109    if !errors.is_empty() {
2110        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2111    }
2112
2113    ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env, [])
2114}
2115
2116#[instrument(level = "debug", skip(tcx))]
2117fn compare_impl_ty<'tcx>(
2118    tcx: TyCtxt<'tcx>,
2119    impl_ty: ty::AssocItem,
2120    trait_ty: ty::AssocItem,
2121    impl_trait_ref: ty::TraitRef<'tcx>,
2122) -> Result<(), ErrorGuaranteed> {
2123    compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
2124    compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
2125    check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
2126    compare_type_predicate_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
2127    check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
2128}
2129
2130/// The equivalent of [compare_method_predicate_entailment], but for associated types
2131/// instead of associated functions.
2132#[instrument(level = "debug", skip(tcx))]
2133fn compare_type_predicate_entailment<'tcx>(
2134    tcx: TyCtxt<'tcx>,
2135    impl_ty: ty::AssocItem,
2136    trait_ty: ty::AssocItem,
2137    impl_trait_ref: ty::TraitRef<'tcx>,
2138) -> Result<(), ErrorGuaranteed> {
2139    let impl_def_id = impl_ty.container_id(tcx);
2140    let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
2141        tcx,
2142        impl_def_id,
2143        impl_trait_ref.args,
2144    );
2145
2146    let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
2147    let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
2148
2149    let impl_ty_own_bounds = impl_ty_predicates.instantiate_own_identity();
2150    // If there are no bounds, then there are no const conditions, so no need to check that here.
2151    if impl_ty_own_bounds.len() == 0 {
2152        // Nothing to check.
2153        return Ok(());
2154    }
2155
2156    // This `DefId` should be used for the `body_id` field on each
2157    // `ObligationCause` (and the `FnCtxt`). This is what
2158    // `regionck_item` expects.
2159    let impl_ty_def_id = impl_ty.def_id.expect_local();
2160    debug!(?trait_to_impl_args);
2161
2162    // The predicates declared by the impl definition, the trait and the
2163    // associated type in the trait are assumed.
2164    let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
2165    let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2166    hybrid_preds.extend(
2167        trait_ty_predicates
2168            .instantiate_own(tcx, trait_to_impl_args)
2169            .map(|(predicate, _)| predicate),
2170    );
2171    debug!(?hybrid_preds);
2172
2173    let impl_ty_span = tcx.def_span(impl_ty_def_id);
2174    let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
2175
2176    let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
2177    if is_conditionally_const {
2178        // Augment the hybrid param-env with the const conditions
2179        // of the impl header and the trait assoc type.
2180        hybrid_preds.extend(
2181            tcx.const_conditions(impl_ty_predicates.parent.unwrap())
2182                .instantiate_identity(tcx)
2183                .into_iter()
2184                .chain(
2185                    tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
2186                )
2187                .map(|(trait_ref, _)| {
2188                    trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
2189                }),
2190        );
2191    }
2192
2193    let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
2194    let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
2195    debug!(caller_bounds=?param_env.caller_bounds());
2196
2197    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2198    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2199
2200    for (predicate, span) in impl_ty_own_bounds {
2201        let cause = ObligationCause::misc(span, impl_ty_def_id);
2202        let predicate = ocx.normalize(&cause, param_env, predicate);
2203
2204        let cause = ObligationCause::new(
2205            span,
2206            impl_ty_def_id,
2207            ObligationCauseCode::CompareImplItem {
2208                impl_item_def_id: impl_ty.def_id.expect_local(),
2209                trait_item_def_id: trait_ty.def_id,
2210                kind: impl_ty.kind,
2211            },
2212        );
2213        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2214    }
2215
2216    if is_conditionally_const {
2217        // Validate the const conditions of the impl associated type.
2218        let impl_ty_own_const_conditions =
2219            tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2220        for (const_condition, span) in impl_ty_own_const_conditions {
2221            let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2222            let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2223
2224            let cause = ObligationCause::new(
2225                span,
2226                impl_ty_def_id,
2227                ObligationCauseCode::CompareImplItem {
2228                    impl_item_def_id: impl_ty_def_id,
2229                    trait_item_def_id: trait_ty.def_id,
2230                    kind: impl_ty.kind,
2231                },
2232            );
2233            ocx.register_obligation(traits::Obligation::new(
2234                tcx,
2235                cause,
2236                param_env,
2237                const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2238            ));
2239        }
2240    }
2241
2242    // Check that all obligations are satisfied by the implementation's
2243    // version.
2244    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2245    if !errors.is_empty() {
2246        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2247        return Err(reported);
2248    }
2249
2250    // Finally, resolve all regions. This catches wily misuses of
2251    // lifetime parameters.
2252    ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2253}
2254
2255/// Validate that `ProjectionCandidate`s created for this associated type will
2256/// be valid.
2257///
2258/// Usually given
2259///
2260/// trait X { type Y: Copy } impl X for T { type Y = S; }
2261///
2262/// We are able to normalize `<T as X>::Y` to `S`, and so when we check the
2263/// impl is well-formed we have to prove `S: Copy`.
2264///
2265/// For default associated types the normalization is not possible (the value
2266/// from the impl could be overridden). We also can't normalize generic
2267/// associated types (yet) because they contain bound parameters.
2268#[instrument(level = "debug", skip(tcx))]
2269pub(super) fn check_type_bounds<'tcx>(
2270    tcx: TyCtxt<'tcx>,
2271    trait_ty: ty::AssocItem,
2272    impl_ty: ty::AssocItem,
2273    impl_trait_ref: ty::TraitRef<'tcx>,
2274) -> Result<(), ErrorGuaranteed> {
2275    // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
2276    // other `Foo` impls are incoherent.
2277    tcx.ensure_ok().coherent_trait(impl_trait_ref.def_id)?;
2278
2279    let param_env = tcx.param_env(impl_ty.def_id);
2280    debug!(?param_env);
2281
2282    let container_id = impl_ty.container_id(tcx);
2283    let impl_ty_def_id = impl_ty.def_id.expect_local();
2284    let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2285    let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2286
2287    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2288    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2289
2290    // A synthetic impl Trait for RPITIT desugaring or assoc type for effects desugaring has no HIR,
2291    // which we currently use to get the span for an impl's associated type. Instead, for these,
2292    // use the def_span for the synthesized  associated type.
2293    let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2294        tcx.def_span(impl_ty_def_id)
2295    } else {
2296        match tcx.hir_node_by_def_id(impl_ty_def_id) {
2297            hir::Node::TraitItem(hir::TraitItem {
2298                kind: hir::TraitItemKind::Type(_, Some(ty)),
2299                ..
2300            }) => ty.span,
2301            hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2302            item => span_bug!(
2303                tcx.def_span(impl_ty_def_id),
2304                "cannot call `check_type_bounds` on item: {item:?}",
2305            ),
2306        }
2307    };
2308    let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2309
2310    let normalize_cause = ObligationCause::new(
2311        impl_ty_span,
2312        impl_ty_def_id,
2313        ObligationCauseCode::CheckAssociatedTypeBounds {
2314            impl_item_def_id: impl_ty.def_id.expect_local(),
2315            trait_item_def_id: trait_ty.def_id,
2316        },
2317    );
2318    let mk_cause = |span: Span| {
2319        let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2320        ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2321    };
2322
2323    let mut obligations: Vec<_> = util::elaborate(
2324        tcx,
2325        tcx.explicit_item_bounds(trait_ty.def_id).iter_instantiated_copied(tcx, rebased_args).map(
2326            |(concrete_ty_bound, span)| {
2327                debug!(?concrete_ty_bound);
2328                traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2329            },
2330        ),
2331    )
2332    .collect();
2333
2334    // Only in a const implementation do we need to check that the `[const]` item bounds hold.
2335    if tcx.is_conditionally_const(impl_ty_def_id) {
2336        obligations.extend(util::elaborate(
2337            tcx,
2338            tcx.explicit_implied_const_bounds(trait_ty.def_id)
2339                .iter_instantiated_copied(tcx, rebased_args)
2340                .map(|(c, span)| {
2341                    traits::Obligation::new(
2342                        tcx,
2343                        mk_cause(span),
2344                        param_env,
2345                        c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2346                    )
2347                }),
2348        ));
2349    }
2350    debug!(item_bounds=?obligations);
2351
2352    // Normalize predicates with the assumption that the GAT may always normalize
2353    // to its definition type. This should be the param-env we use to *prove* the
2354    // predicate too, but we don't do that because of performance issues.
2355    // See <https://github.com/rust-lang/rust/pull/117542#issue-1976337685>.
2356    let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2357    for obligation in &mut obligations {
2358        match ocx.deeply_normalize(&normalize_cause, normalize_param_env, obligation.predicate) {
2359            Ok(pred) => obligation.predicate = pred,
2360            Err(e) => {
2361                return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2362            }
2363        }
2364    }
2365
2366    // Check that all obligations are satisfied by the implementation's
2367    // version.
2368    ocx.register_obligations(obligations);
2369    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2370    if !errors.is_empty() {
2371        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2372        return Err(reported);
2373    }
2374
2375    // Finally, resolve all regions. This catches wily misuses of
2376    // lifetime parameters.
2377    ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2378}
2379
2380/// Install projection predicates that allow GATs to project to their own
2381/// definition types. This is not allowed in general in cases of default
2382/// associated types in trait definitions, or when specialization is involved,
2383/// but is needed when checking these definition types actually satisfy the
2384/// trait bounds of the GAT.
2385///
2386/// # How it works
2387///
2388/// ```ignore (example)
2389/// impl<A, B> Foo<u32> for (A, B) {
2390///     type Bar<C> = Wrapper<A, B, C>
2391/// }
2392/// ```
2393///
2394/// - `impl_trait_ref` would be `<(A, B) as Foo<u32>>`
2395/// - `normalize_impl_ty_args` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
2396/// - `normalize_impl_ty` would be `Wrapper<A, B, ^0.0>`
2397/// - `rebased_args` would be `[(A, B), u32, ^0.0]`, combining the args from
2398///    the *trait* with the generic associated type parameters (as bound vars).
2399///
2400/// A note regarding the use of bound vars here:
2401/// Imagine as an example
2402/// ```
2403/// trait Family {
2404///     type Member<C: Eq>;
2405/// }
2406///
2407/// impl Family for VecFamily {
2408///     type Member<C: Eq> = i32;
2409/// }
2410/// ```
2411/// Here, we would generate
2412/// ```ignore (pseudo-rust)
2413/// forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
2414/// ```
2415///
2416/// when we really would like to generate
2417/// ```ignore (pseudo-rust)
2418/// forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
2419/// ```
2420///
2421/// But, this is probably fine, because although the first clause can be used with types `C` that
2422/// do not implement `Eq`, for it to cause some kind of problem, there would have to be a
2423/// `VecFamily::Member<X>` for some type `X` where `!(X: Eq)`, that appears in the value of type
2424/// `Member<C: Eq> = ....` That type would fail a well-formedness check that we ought to be doing
2425/// elsewhere, which would check that any `<T as Family>::Member<X>` meets the bounds declared in
2426/// the trait (notably, that `X: Eq` and `T: Family`).
2427fn param_env_with_gat_bounds<'tcx>(
2428    tcx: TyCtxt<'tcx>,
2429    impl_ty: ty::AssocItem,
2430    impl_trait_ref: ty::TraitRef<'tcx>,
2431) -> ty::ParamEnv<'tcx> {
2432    let param_env = tcx.param_env(impl_ty.def_id);
2433    let container_id = impl_ty.container_id(tcx);
2434    let mut predicates = param_env.caller_bounds().to_vec();
2435
2436    // for RPITITs, we should install predicates that allow us to project all
2437    // of the RPITITs associated with the same body. This is because checking
2438    // the item bounds of RPITITs often involves nested RPITITs having to prove
2439    // bounds about themselves.
2440    let impl_tys_to_install = match impl_ty.kind {
2441        ty::AssocKind::Type {
2442            data:
2443                ty::AssocTypeData::Rpitit(
2444                    ty::ImplTraitInTraitData::Impl { fn_def_id }
2445                    | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2446                ),
2447        } => tcx
2448            .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2449            .iter()
2450            .map(|def_id| tcx.associated_item(*def_id))
2451            .collect(),
2452        _ => vec![impl_ty],
2453    };
2454
2455    for impl_ty in impl_tys_to_install {
2456        let trait_ty = match impl_ty.container {
2457            ty::AssocContainer::InherentImpl => bug!(),
2458            ty::AssocContainer::Trait => impl_ty,
2459            ty::AssocContainer::TraitImpl(Err(_)) => continue,
2460            ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
2461                tcx.associated_item(trait_item_def_id)
2462            }
2463        };
2464
2465        let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
2466            smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2467        // Extend the impl's identity args with late-bound GAT vars
2468        let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2469            .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2470                GenericParamDefKind::Type { .. } => {
2471                    let kind = ty::BoundTyKind::Param(param.def_id);
2472                    let bound_var = ty::BoundVariableKind::Ty(kind);
2473                    bound_vars.push(bound_var);
2474                    Ty::new_bound(
2475                        tcx,
2476                        ty::INNERMOST,
2477                        ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2478                    )
2479                    .into()
2480                }
2481                GenericParamDefKind::Lifetime => {
2482                    let kind = ty::BoundRegionKind::Named(param.def_id);
2483                    let bound_var = ty::BoundVariableKind::Region(kind);
2484                    bound_vars.push(bound_var);
2485                    ty::Region::new_bound(
2486                        tcx,
2487                        ty::INNERMOST,
2488                        ty::BoundRegion {
2489                            var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2490                            kind,
2491                        },
2492                    )
2493                    .into()
2494                }
2495                GenericParamDefKind::Const { .. } => {
2496                    let bound_var = ty::BoundVariableKind::Const;
2497                    bound_vars.push(bound_var);
2498                    ty::Const::new_bound(
2499                        tcx,
2500                        ty::INNERMOST,
2501                        ty::BoundConst { var: ty::BoundVar::from_usize(bound_vars.len() - 1) },
2502                    )
2503                    .into()
2504                }
2505            });
2506        // When checking something like
2507        //
2508        // trait X { type Y: PartialEq<<Self as X>::Y> }
2509        // impl X for T { default type Y = S; }
2510        //
2511        // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
2512        // we want <T as X>::Y to normalize to S. This is valid because we are
2513        // checking the default value specifically here. Add this equality to the
2514        // ParamEnv for normalization specifically.
2515        let normalize_impl_ty =
2516            tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args);
2517        let rebased_args =
2518            normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2519        let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2520
2521        match normalize_impl_ty.kind() {
2522            ty::Alias(ty::Projection, proj)
2523                if proj.def_id == trait_ty.def_id && proj.args == rebased_args =>
2524            {
2525                // Don't include this predicate if the projected type is
2526                // exactly the same as the projection. This can occur in
2527                // (somewhat dubious) code like this:
2528                //
2529                // impl<T> X for T where T: X { type Y = <T as X>::Y; }
2530            }
2531            _ => predicates.push(
2532                ty::Binder::bind_with_vars(
2533                    ty::ProjectionPredicate {
2534                        projection_term: ty::AliasTerm::new_from_args(
2535                            tcx,
2536                            trait_ty.def_id,
2537                            rebased_args,
2538                        ),
2539                        term: normalize_impl_ty.into(),
2540                    },
2541                    bound_vars,
2542                )
2543                .upcast(tcx),
2544            ),
2545        };
2546    }
2547
2548    ty::ParamEnv::new(tcx.mk_clauses(&predicates))
2549}
2550
2551/// Manually check here that `async fn foo()` wasn't matched against `fn foo()`,
2552/// and extract a better error if so.
2553fn try_report_async_mismatch<'tcx>(
2554    tcx: TyCtxt<'tcx>,
2555    infcx: &InferCtxt<'tcx>,
2556    errors: &[FulfillmentError<'tcx>],
2557    trait_m: ty::AssocItem,
2558    impl_m: ty::AssocItem,
2559    impl_sig: ty::FnSig<'tcx>,
2560) -> Result<(), ErrorGuaranteed> {
2561    if !tcx.asyncness(trait_m.def_id).is_async() {
2562        return Ok(());
2563    }
2564
2565    let ty::Alias(ty::Projection, ty::AliasTy { def_id: async_future_def_id, .. }) =
2566        *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2567    else {
2568        bug!("expected `async fn` to return an RPITIT");
2569    };
2570
2571    for error in errors {
2572        if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2573            && def_id == async_future_def_id
2574            && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2575            && let Some(proj) = proj.no_bound_vars()
2576            && infcx.can_eq(
2577                error.root_obligation.param_env,
2578                proj.term.expect_type(),
2579                impl_sig.output(),
2580            )
2581        {
2582            // FIXME: We should suggest making the fn `async`, but extracting
2583            // the right span is a bit difficult.
2584            return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2585                span: tcx.def_span(impl_m.def_id),
2586                method_name: tcx.item_ident(impl_m.def_id),
2587                trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
2588            }));
2589        }
2590    }
2591
2592    Ok(())
2593}