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