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