]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/check/compare_impl_item.rs
Replacing bound vars is actually instantiating a binder
[rust.git] / compiler / rustc_hir_analysis / src / check / compare_impl_item.rs
1 use super::potentially_plural_count;
2 use crate::errors::LifetimesOrBoundsMismatchOnTrait;
3 use hir::def_id::{DefId, LocalDefId};
4 use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
5 use rustc_errors::{
6     pluralize, struct_span_err, Applicability, DiagnosticId, ErrorGuaranteed, MultiSpan,
7 };
8 use rustc_hir as hir;
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::intravisit;
11 use rustc_hir::{GenericParamKind, ImplItemKind};
12 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
13 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
14 use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt};
15 use rustc_infer::traits::util;
16 use rustc_middle::ty::error::{ExpectedFound, TypeError};
17 use rustc_middle::ty::util::ExplicitSelf;
18 use rustc_middle::ty::{
19     self, DefIdTree, InternalSubsts, Ty, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable,
20 };
21 use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt};
22 use rustc_span::Span;
23 use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt;
24 use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _;
25 use rustc_trait_selection::traits::{
26     self, ObligationCause, ObligationCauseCode, ObligationCtxt, Reveal,
27 };
28 use std::iter;
29
30 /// Checks that a method from an impl conforms to the signature of
31 /// the same method as declared in the trait.
32 ///
33 /// # Parameters
34 ///
35 /// - `impl_m`: type of the method we are checking
36 /// - `impl_m_span`: span to use for reporting errors
37 /// - `trait_m`: the method in the trait
38 /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
39 pub(super) fn compare_impl_method<'tcx>(
40     tcx: TyCtxt<'tcx>,
41     impl_m: &ty::AssocItem,
42     trait_m: &ty::AssocItem,
43     impl_trait_ref: ty::TraitRef<'tcx>,
44     trait_item_span: Option<Span>,
45 ) {
46     debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref);
47
48     let impl_m_span = tcx.def_span(impl_m.def_id);
49
50     let _: Result<_, ErrorGuaranteed> = try {
51         compare_self_type(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)?;
52         compare_number_of_generics(tcx, impl_m, trait_m, trait_item_span, false)?;
53         compare_generic_param_kinds(tcx, impl_m, trait_m, false)?;
54         compare_number_of_method_arguments(tcx, impl_m, impl_m_span, trait_m, trait_item_span)?;
55         compare_synthetic_generics(tcx, impl_m, trait_m)?;
56         compare_asyncness(tcx, impl_m, impl_m_span, trait_m, trait_item_span)?;
57         compare_method_predicate_entailment(
58             tcx,
59             impl_m,
60             impl_m_span,
61             trait_m,
62             impl_trait_ref,
63             CheckImpliedWfMode::Check,
64         )?;
65     };
66 }
67
68 /// This function is best explained by example. Consider a trait:
69 ///
70 ///     trait Trait<'t, T> {
71 ///         // `trait_m`
72 ///         fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
73 ///     }
74 ///
75 /// And an impl:
76 ///
77 ///     impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
78 ///          // `impl_m`
79 ///          fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo;
80 ///     }
81 ///
82 /// We wish to decide if those two method types are compatible.
83 /// For this we have to show that, assuming the bounds of the impl hold, the
84 /// bounds of `trait_m` imply the bounds of `impl_m`.
85 ///
86 /// We start out with `trait_to_impl_substs`, that maps the trait
87 /// type parameters to impl type parameters. This is taken from the
88 /// impl trait reference:
89 ///
90 ///     trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
91 ///
92 /// We create a mapping `dummy_substs` that maps from the impl type
93 /// parameters to fresh types and regions. For type parameters,
94 /// this is the identity transform, but we could as well use any
95 /// placeholder types. For regions, we convert from bound to free
96 /// regions (Note: but only early-bound regions, i.e., those
97 /// declared on the impl or used in type parameter bounds).
98 ///
99 ///     impl_to_placeholder_substs = {'i => 'i0, U => U0, N => N0 }
100 ///
101 /// Now we can apply `placeholder_substs` to the type of the impl method
102 /// to yield a new function type in terms of our fresh, placeholder
103 /// types:
104 ///
105 ///     <'b> fn(t: &'i0 U0, m: &'b) -> Foo
106 ///
107 /// We now want to extract and substitute the type of the *trait*
108 /// method and compare it. To do so, we must create a compound
109 /// substitution by combining `trait_to_impl_substs` and
110 /// `impl_to_placeholder_substs`, and also adding a mapping for the method
111 /// type parameters. We extend the mapping to also include
112 /// the method parameters.
113 ///
114 ///     trait_to_placeholder_substs = { T => &'i0 U0, Self => Foo, M => N0 }
115 ///
116 /// Applying this to the trait method type yields:
117 ///
118 ///     <'a> fn(t: &'i0 U0, m: &'a) -> Foo
119 ///
120 /// This type is also the same but the name of the bound region (`'a`
121 /// vs `'b`). However, the normal subtyping rules on fn types handle
122 /// this kind of equivalency just fine.
123 ///
124 /// We now use these substitutions to ensure that all declared bounds are
125 /// satisfied by the implementation's method.
126 ///
127 /// We do this by creating a parameter environment which contains a
128 /// substitution corresponding to `impl_to_placeholder_substs`. We then build
129 /// `trait_to_placeholder_substs` and use it to convert the predicates contained
130 /// in the `trait_m` generics to the placeholder form.
131 ///
132 /// Finally we register each of these predicates as an obligation and check that
133 /// they hold.
134 #[instrument(level = "debug", skip(tcx, impl_m_span, impl_trait_ref))]
135 fn compare_method_predicate_entailment<'tcx>(
136     tcx: TyCtxt<'tcx>,
137     impl_m: &ty::AssocItem,
138     impl_m_span: Span,
139     trait_m: &ty::AssocItem,
140     impl_trait_ref: ty::TraitRef<'tcx>,
141     check_implied_wf: CheckImpliedWfMode,
142 ) -> Result<(), ErrorGuaranteed> {
143     let trait_to_impl_substs = impl_trait_ref.substs;
144
145     // This node-id should be used for the `body_id` field on each
146     // `ObligationCause` (and the `FnCtxt`).
147     //
148     // FIXME(@lcnr): remove that after removing `cause.body_id` from
149     // obligations.
150     let impl_m_def_id = impl_m.def_id.expect_local();
151     let cause = ObligationCause::new(
152         impl_m_span,
153         impl_m_def_id,
154         ObligationCauseCode::CompareImplItemObligation {
155             impl_item_def_id: impl_m_def_id,
156             trait_item_def_id: trait_m.def_id,
157             kind: impl_m.kind,
158         },
159     );
160
161     // Create mapping from impl to placeholder.
162     let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
163
164     // Create mapping from trait to placeholder.
165     let trait_to_placeholder_substs =
166         impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
167     debug!("compare_impl_method: trait_to_placeholder_substs={:?}", trait_to_placeholder_substs);
168
169     let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
170     let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
171
172     // Check region bounds.
173     check_region_bounds_on_impl_item(tcx, impl_m, trait_m, false)?;
174
175     // Create obligations for each predicate declared by the impl
176     // definition in the context of the trait's parameter
177     // environment. We can't just use `impl_env.caller_bounds`,
178     // however, because we want to replace all late-bound regions with
179     // region variables.
180     let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
181     let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
182
183     debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
184
185     // This is the only tricky bit of the new way we check implementation methods
186     // We need to build a set of predicates where only the method-level bounds
187     // are from the trait and we assume all other bounds from the implementation
188     // to be previously satisfied.
189     //
190     // We then register the obligations from the impl_m and check to see
191     // if all constraints hold.
192     hybrid_preds.predicates.extend(
193         trait_m_predicates
194             .instantiate_own(tcx, trait_to_placeholder_substs)
195             .map(|(predicate, _)| predicate),
196     );
197
198     // Construct trait parameter environment and then shift it into the placeholder viewpoint.
199     // The key step here is to update the caller_bounds's predicates to be
200     // the new hybrid bounds we computed.
201     let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
202     let param_env = ty::ParamEnv::new(
203         tcx.intern_predicates(&hybrid_preds.predicates),
204         Reveal::UserFacing,
205         hir::Constness::NotConst,
206     );
207     let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
208
209     let infcx = &tcx.infer_ctxt().build();
210     let ocx = ObligationCtxt::new(infcx);
211
212     debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds());
213
214     let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs);
215     for (predicate, span) in impl_m_own_bounds {
216         let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
217         let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
218
219         let cause = ObligationCause::new(
220             span,
221             impl_m_def_id,
222             ObligationCauseCode::CompareImplItemObligation {
223                 impl_item_def_id: impl_m_def_id,
224                 trait_item_def_id: trait_m.def_id,
225                 kind: impl_m.kind,
226             },
227         );
228         ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
229     }
230
231     // We now need to check that the signature of the impl method is
232     // compatible with that of the trait method. We do this by
233     // checking that `impl_fty <: trait_fty`.
234     //
235     // FIXME. Unfortunately, this doesn't quite work right now because
236     // associated type normalization is not integrated into subtype
237     // checks. For the comparison to be valid, we need to
238     // normalize the associated types in the impl/trait methods
239     // first. However, because function types bind regions, just
240     // calling `normalize_associated_types_in` would have no effect on
241     // any associated types appearing in the fn arguments or return
242     // type.
243
244     // Compute placeholder form of impl and trait method tys.
245     let tcx = infcx.tcx;
246
247     let mut wf_tys = FxIndexSet::default();
248
249     let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars(
250         impl_m_span,
251         infer::HigherRankedType,
252         tcx.fn_sig(impl_m.def_id).subst_identity(),
253     );
254     let unnormalized_impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(unnormalized_impl_sig));
255
256     let norm_cause = ObligationCause::misc(impl_m_span, impl_m_def_id);
257     let impl_sig = ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig);
258     debug!("compare_impl_method: impl_fty={:?}", impl_sig);
259
260     let trait_sig = tcx.fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs);
261     let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
262
263     // Next, add all inputs and output as well-formed tys. Importantly,
264     // we have to do this before normalization, since the normalized ty may
265     // not contain the input parameters. See issue #87748.
266     wf_tys.extend(trait_sig.inputs_and_output.iter());
267     let trait_sig = ocx.normalize(&norm_cause, param_env, trait_sig);
268     // We also have to add the normalized trait signature
269     // as we don't normalize during implied bounds computation.
270     wf_tys.extend(trait_sig.inputs_and_output.iter());
271     let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));
272
273     debug!("compare_impl_method: trait_fty={:?}", trait_fty);
274
275     // FIXME: We'd want to keep more accurate spans than "the method signature" when
276     // processing the comparison between the trait and impl fn, but we sadly lose them
277     // and point at the whole signature when a trait bound or specific input or output
278     // type would be more appropriate. In other places we have a `Vec<Span>`
279     // corresponding to their `Vec<Predicate>`, but we don't have that here.
280     // Fixing this would improve the output of test `issue-83765.rs`.
281     let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
282
283     if let Err(terr) = result {
284         debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
285
286         let emitted = report_trait_method_mismatch(
287             &infcx,
288             cause,
289             terr,
290             (trait_m, trait_sig),
291             (impl_m, impl_sig),
292             impl_trait_ref,
293         );
294         return Err(emitted);
295     }
296
297     if check_implied_wf == CheckImpliedWfMode::Check {
298         // We need to check that the impl's args are well-formed given
299         // the hybrid param-env (impl + trait method where-clauses).
300         ocx.register_obligation(traits::Obligation::new(
301             infcx.tcx,
302             ObligationCause::dummy(),
303             param_env,
304             ty::Binder::dummy(ty::PredicateKind::WellFormed(unnormalized_impl_fty.into())),
305         ));
306     }
307
308     // Check that all obligations are satisfied by the implementation's
309     // version.
310     let errors = ocx.select_all_or_error();
311     if !errors.is_empty() {
312         match check_implied_wf {
313             CheckImpliedWfMode::Check => {
314                 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m_def_id);
315                 return compare_method_predicate_entailment(
316                     tcx,
317                     impl_m,
318                     impl_m_span,
319                     trait_m,
320                     impl_trait_ref,
321                     CheckImpliedWfMode::Skip,
322                 )
323                 .map(|()| {
324                     // If the skip-mode was successful, emit a lint.
325                     emit_implied_wf_lint(infcx.tcx, impl_m, impl_m_hir_id, vec![]);
326                 });
327             }
328             CheckImpliedWfMode::Skip => {
329                 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
330                 return Err(reported);
331             }
332         }
333     }
334
335     // Finally, resolve all regions. This catches wily misuses of
336     // lifetime parameters.
337     let outlives_env = OutlivesEnvironment::with_bounds(
338         param_env,
339         Some(infcx),
340         infcx.implied_bounds_tys(param_env, impl_m_def_id, wf_tys.clone()),
341     );
342     infcx.process_registered_region_obligations(
343         outlives_env.region_bound_pairs(),
344         outlives_env.param_env,
345     );
346     let errors = infcx.resolve_regions(&outlives_env);
347     if !errors.is_empty() {
348         // FIXME(compiler-errors): This can be simplified when IMPLIED_BOUNDS_ENTAILMENT
349         // becomes a hard error (i.e. ideally we'd just call `resolve_regions_and_report_errors`
350         let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m_def_id);
351         match check_implied_wf {
352             CheckImpliedWfMode::Check => {
353                 return compare_method_predicate_entailment(
354                     tcx,
355                     impl_m,
356                     impl_m_span,
357                     trait_m,
358                     impl_trait_ref,
359                     CheckImpliedWfMode::Skip,
360                 )
361                 .map(|()| {
362                     let bad_args = extract_bad_args_for_implies_lint(
363                         tcx,
364                         &errors,
365                         (trait_m, trait_sig),
366                         // Unnormalized impl sig corresponds to the HIR types written
367                         (impl_m, unnormalized_impl_sig),
368                         impl_m_hir_id,
369                     );
370                     // If the skip-mode was successful, emit a lint.
371                     emit_implied_wf_lint(tcx, impl_m, impl_m_hir_id, bad_args);
372                 });
373             }
374             CheckImpliedWfMode::Skip => {
375                 if infcx.tainted_by_errors().is_none() {
376                     infcx.err_ctxt().report_region_errors(impl_m_def_id, &errors);
377                 }
378                 return Err(tcx
379                     .sess
380                     .delay_span_bug(rustc_span::DUMMY_SP, "error should have been emitted"));
381             }
382         }
383     }
384
385     Ok(())
386 }
387
388 fn extract_bad_args_for_implies_lint<'tcx>(
389     tcx: TyCtxt<'tcx>,
390     errors: &[infer::RegionResolutionError<'tcx>],
391     (trait_m, trait_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
392     (impl_m, impl_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
393     hir_id: hir::HirId,
394 ) -> Vec<(Span, Option<String>)> {
395     let mut blame_generics = vec![];
396     for error in errors {
397         // Look for the subregion origin that contains an input/output type
398         let origin = match error {
399             infer::RegionResolutionError::ConcreteFailure(o, ..) => o,
400             infer::RegionResolutionError::GenericBoundFailure(o, ..) => o,
401             infer::RegionResolutionError::SubSupConflict(_, _, o, ..) => o,
402             infer::RegionResolutionError::UpperBoundUniverseConflict(.., o, _) => o,
403         };
404         // Extract (possible) input/output types from origin
405         match origin {
406             infer::SubregionOrigin::Subtype(trace) => {
407                 if let Some((a, b)) = trace.values.ty() {
408                     blame_generics.extend([a, b]);
409                 }
410             }
411             infer::SubregionOrigin::RelateParamBound(_, ty, _) => blame_generics.push(*ty),
412             infer::SubregionOrigin::ReferenceOutlivesReferent(ty, _) => blame_generics.push(*ty),
413             _ => {}
414         }
415     }
416
417     let fn_decl = tcx.hir().fn_decl_by_hir_id(hir_id).unwrap();
418     let opt_ret_ty = match fn_decl.output {
419         hir::FnRetTy::DefaultReturn(_) => None,
420         hir::FnRetTy::Return(ty) => Some(ty),
421     };
422
423     // Map late-bound regions from trait to impl, so the names are right.
424     let mapping = std::iter::zip(
425         tcx.fn_sig(trait_m.def_id).skip_binder().bound_vars(),
426         tcx.fn_sig(impl_m.def_id).skip_binder().bound_vars(),
427     )
428     .filter_map(|(impl_bv, trait_bv)| {
429         if let ty::BoundVariableKind::Region(impl_bv) = impl_bv
430             && let ty::BoundVariableKind::Region(trait_bv) = trait_bv
431         {
432             Some((impl_bv, trait_bv))
433         } else {
434             None
435         }
436     })
437     .collect();
438
439     // For each arg, see if it was in the "blame" of any of the region errors.
440     // If so, then try to produce a suggestion to replace the argument type with
441     // one from the trait.
442     let mut bad_args = vec![];
443     for (idx, (ty, hir_ty)) in
444         std::iter::zip(impl_sig.inputs_and_output, fn_decl.inputs.iter().chain(opt_ret_ty))
445             .enumerate()
446     {
447         let expected_ty = trait_sig.inputs_and_output[idx]
448             .fold_with(&mut RemapLateBound { tcx, mapping: &mapping });
449         if blame_generics.iter().any(|blame| ty.contains(*blame)) {
450             let expected_ty_sugg = expected_ty.to_string();
451             bad_args.push((
452                 hir_ty.span,
453                 // Only suggest something if it actually changed.
454                 (expected_ty_sugg != ty.to_string()).then_some(expected_ty_sugg),
455             ));
456         }
457     }
458
459     bad_args
460 }
461
462 struct RemapLateBound<'a, 'tcx> {
463     tcx: TyCtxt<'tcx>,
464     mapping: &'a FxHashMap<ty::BoundRegionKind, ty::BoundRegionKind>,
465 }
466
467 impl<'tcx> TypeFolder<'tcx> for RemapLateBound<'_, 'tcx> {
468     fn tcx(&self) -> TyCtxt<'tcx> {
469         self.tcx
470     }
471
472     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
473         if let ty::ReFree(fr) = *r {
474             self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
475                 bound_region: self
476                     .mapping
477                     .get(&fr.bound_region)
478                     .copied()
479                     .unwrap_or(fr.bound_region),
480                 ..fr
481             }))
482         } else {
483             r
484         }
485     }
486 }
487
488 fn emit_implied_wf_lint<'tcx>(
489     tcx: TyCtxt<'tcx>,
490     impl_m: &ty::AssocItem,
491     hir_id: hir::HirId,
492     bad_args: Vec<(Span, Option<String>)>,
493 ) {
494     let span: MultiSpan = if bad_args.is_empty() {
495         tcx.def_span(impl_m.def_id).into()
496     } else {
497         bad_args.iter().map(|(span, _)| *span).collect::<Vec<_>>().into()
498     };
499     tcx.struct_span_lint_hir(
500         rustc_session::lint::builtin::IMPLIED_BOUNDS_ENTAILMENT,
501         hir_id,
502         span,
503         "impl method assumes more implied bounds than the corresponding trait method",
504         |lint| {
505             let bad_args: Vec<_> =
506                 bad_args.into_iter().filter_map(|(span, sugg)| Some((span, sugg?))).collect();
507             if !bad_args.is_empty() {
508                 lint.multipart_suggestion(
509                     format!(
510                         "replace {} type{} to make the impl signature compatible",
511                         pluralize!("this", bad_args.len()),
512                         pluralize!(bad_args.len())
513                     ),
514                     bad_args,
515                     Applicability::MaybeIncorrect,
516                 );
517             }
518             lint
519         },
520     );
521 }
522
523 #[derive(Debug, PartialEq, Eq)]
524 enum CheckImpliedWfMode {
525     /// Checks implied well-formedness of the impl method. If it fails, we will
526     /// re-check with `Skip`, and emit a lint if it succeeds.
527     Check,
528     /// Skips checking implied well-formedness of the impl method, but will emit
529     /// a lint if the `compare_method_predicate_entailment` succeeded. This means that
530     /// the reason that we had failed earlier during `Check` was due to the impl
531     /// having stronger requirements than the trait.
532     Skip,
533 }
534
535 fn compare_asyncness<'tcx>(
536     tcx: TyCtxt<'tcx>,
537     impl_m: &ty::AssocItem,
538     impl_m_span: Span,
539     trait_m: &ty::AssocItem,
540     trait_item_span: Option<Span>,
541 ) -> Result<(), ErrorGuaranteed> {
542     if tcx.asyncness(trait_m.def_id) == hir::IsAsync::Async {
543         match tcx.fn_sig(impl_m.def_id).skip_binder().skip_binder().output().kind() {
544             ty::Alias(ty::Opaque, ..) => {
545                 // allow both `async fn foo()` and `fn foo() -> impl Future`
546             }
547             ty::Error(_) => {
548                 // We don't know if it's ok, but at least it's already an error.
549             }
550             _ => {
551                 return Err(tcx.sess.emit_err(crate::errors::AsyncTraitImplShouldBeAsync {
552                     span: impl_m_span,
553                     method_name: trait_m.name,
554                     trait_item_span,
555                 }));
556             }
557         };
558     }
559
560     Ok(())
561 }
562
563 /// Given a method def-id in an impl, compare the method signature of the impl
564 /// against the trait that it's implementing. In doing so, infer the hidden types
565 /// that this method's signature provides to satisfy each return-position `impl Trait`
566 /// in the trait signature.
567 ///
568 /// The method is also responsible for making sure that the hidden types for each
569 /// RPITIT actually satisfy the bounds of the `impl Trait`, i.e. that if we infer
570 /// `impl Trait = Foo`, that `Foo: Trait` holds.
571 ///
572 /// For example, given the sample code:
573 ///
574 /// ```
575 /// #![feature(return_position_impl_trait_in_trait)]
576 ///
577 /// use std::ops::Deref;
578 ///
579 /// trait Foo {
580 ///     fn bar() -> impl Deref<Target = impl Sized>;
581 ///              // ^- RPITIT #1        ^- RPITIT #2
582 /// }
583 ///
584 /// impl Foo for () {
585 ///     fn bar() -> Box<String> { Box::new(String::new()) }
586 /// }
587 /// ```
588 ///
589 /// The hidden types for the RPITITs in `bar` would be inferred to:
590 ///     * `impl Deref` (RPITIT #1) = `Box<String>`
591 ///     * `impl Sized` (RPITIT #2) = `String`
592 ///
593 /// The relationship between these two types is straightforward in this case, but
594 /// may be more tenuously connected via other `impl`s and normalization rules for
595 /// cases of more complicated nested RPITITs.
596 #[instrument(skip(tcx), level = "debug", ret)]
597 pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
598     tcx: TyCtxt<'tcx>,
599     def_id: DefId,
600 ) -> Result<&'tcx FxHashMap<DefId, Ty<'tcx>>, ErrorGuaranteed> {
601     let impl_m = tcx.opt_associated_item(def_id).unwrap();
602     let trait_m = tcx.opt_associated_item(impl_m.trait_item_def_id.unwrap()).unwrap();
603     let impl_trait_ref =
604         tcx.impl_trait_ref(impl_m.impl_container(tcx).unwrap()).unwrap().subst_identity();
605     let param_env = tcx.param_env(def_id);
606
607     // First, check a few of the same things as `compare_impl_method`,
608     // just so we don't ICE during substitution later.
609     compare_number_of_generics(tcx, impl_m, trait_m, tcx.hir().span_if_local(impl_m.def_id), true)?;
610     compare_generic_param_kinds(tcx, impl_m, trait_m, true)?;
611     check_region_bounds_on_impl_item(tcx, impl_m, trait_m, true)?;
612
613     let trait_to_impl_substs = impl_trait_ref.substs;
614
615     let impl_m_def_id = impl_m.def_id.expect_local();
616     let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m_def_id);
617     let return_span = tcx.hir().fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
618     let cause = ObligationCause::new(
619         return_span,
620         impl_m_def_id,
621         ObligationCauseCode::CompareImplItemObligation {
622             impl_item_def_id: impl_m_def_id,
623             trait_item_def_id: trait_m.def_id,
624             kind: impl_m.kind,
625         },
626     );
627
628     // Create mapping from impl to placeholder.
629     let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
630
631     // Create mapping from trait to placeholder.
632     let trait_to_placeholder_substs =
633         impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
634
635     let infcx = &tcx.infer_ctxt().build();
636     let ocx = ObligationCtxt::new(infcx);
637
638     // Normalize the impl signature with fresh variables for lifetime inference.
639     let norm_cause = ObligationCause::misc(return_span, impl_m_def_id);
640     let impl_sig = ocx.normalize(
641         &norm_cause,
642         param_env,
643         infcx.instantiate_binder_with_fresh_vars(
644             return_span,
645             infer::HigherRankedType,
646             tcx.fn_sig(impl_m.def_id).subst_identity(),
647         ),
648     );
649     impl_sig.error_reported()?;
650     let impl_return_ty = impl_sig.output();
651
652     // Normalize the trait signature with liberated bound vars, passing it through
653     // the ImplTraitInTraitCollector, which gathers all of the RPITITs and replaces
654     // them with inference variables.
655     // We will use these inference variables to collect the hidden types of RPITITs.
656     let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_def_id);
657     let unnormalized_trait_sig = tcx
658         .liberate_late_bound_regions(
659             impl_m.def_id,
660             tcx.fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs),
661         )
662         .fold_with(&mut collector);
663     let trait_sig = ocx.normalize(&norm_cause, param_env, unnormalized_trait_sig);
664     trait_sig.error_reported()?;
665     let trait_return_ty = trait_sig.output();
666
667     let wf_tys = FxIndexSet::from_iter(
668         unnormalized_trait_sig.inputs_and_output.iter().chain(trait_sig.inputs_and_output.iter()),
669     );
670
671     match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
672         Ok(()) => {}
673         Err(terr) => {
674             let mut diag = struct_span_err!(
675                 tcx.sess,
676                 cause.span(),
677                 E0053,
678                 "method `{}` has an incompatible return type for trait",
679                 trait_m.name
680             );
681             let hir = tcx.hir();
682             infcx.err_ctxt().note_type_err(
683                 &mut diag,
684                 &cause,
685                 hir.get_if_local(impl_m.def_id)
686                     .and_then(|node| node.fn_decl())
687                     .map(|decl| (decl.output.span(), "return type in trait".to_owned())),
688                 Some(infer::ValuePairs::Terms(ExpectedFound {
689                     expected: trait_return_ty.into(),
690                     found: impl_return_ty.into(),
691                 })),
692                 terr,
693                 false,
694                 false,
695             );
696             return Err(diag.emit());
697         }
698     }
699
700     debug!(?trait_sig, ?impl_sig, "equating function signatures");
701
702     // Unify the whole function signature. We need to do this to fully infer
703     // the lifetimes of the return type, but do this after unifying just the
704     // return types, since we want to avoid duplicating errors from
705     // `compare_method_predicate_entailment`.
706     match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
707         Ok(()) => {}
708         Err(terr) => {
709             // This function gets called during `compare_method_predicate_entailment` when normalizing a
710             // signature that contains RPITIT. When the method signatures don't match, we have to
711             // emit an error now because `compare_method_predicate_entailment` will not report the error
712             // when normalization fails.
713             let emitted = report_trait_method_mismatch(
714                 infcx,
715                 cause,
716                 terr,
717                 (trait_m, trait_sig),
718                 (impl_m, impl_sig),
719                 impl_trait_ref,
720             );
721             return Err(emitted);
722         }
723     }
724
725     // Check that all obligations are satisfied by the implementation's
726     // RPITs.
727     let errors = ocx.select_all_or_error();
728     if !errors.is_empty() {
729         let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
730         return Err(reported);
731     }
732
733     // Finally, resolve all regions. This catches wily misuses of
734     // lifetime parameters.
735     let outlives_environment = OutlivesEnvironment::with_bounds(
736         param_env,
737         Some(infcx),
738         infcx.implied_bounds_tys(param_env, impl_m_def_id, wf_tys),
739     );
740     infcx
741         .err_ctxt()
742         .check_region_obligations_and_report_errors(impl_m_def_id, &outlives_environment)?;
743
744     let mut collected_tys = FxHashMap::default();
745     for (def_id, (ty, substs)) in collector.types {
746         match infcx.fully_resolve(ty) {
747             Ok(ty) => {
748                 // `ty` contains free regions that we created earlier while liberating the
749                 // trait fn signature. However, projection normalization expects `ty` to
750                 // contains `def_id`'s early-bound regions.
751                 let id_substs = InternalSubsts::identity_for_item(tcx, def_id);
752                 debug!(?id_substs, ?substs);
753                 let map: FxHashMap<ty::GenericArg<'tcx>, ty::GenericArg<'tcx>> =
754                     std::iter::zip(substs, id_substs).collect();
755                 debug!(?map);
756
757                 // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound
758                 // region substs that are synthesized during AST lowering. These are substs
759                 // that are appended to the parent substs (trait and trait method). However,
760                 // we're trying to infer the unsubstituted type value of the RPITIT inside
761                 // the *impl*, so we can later use the impl's method substs to normalize
762                 // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`).
763                 //
764                 // Due to the design of RPITITs, during AST lowering, we have no idea that
765                 // an impl method corresponds to a trait method with RPITITs in it. Therefore,
766                 // we don't have a list of early-bound region substs for the RPITIT in the impl.
767                 // Since early region parameters are index-based, we can't just rebase these
768                 // (trait method) early-bound region substs onto the impl, and there's no
769                 // guarantee that the indices from the trait substs and impl substs line up.
770                 // So to fix this, we subtract the number of trait substs and add the number of
771                 // impl substs to *renumber* these early-bound regions to their corresponding
772                 // indices in the impl's substitutions list.
773                 //
774                 // Also, we only need to account for a difference in trait and impl substs,
775                 // since we previously enforce that the trait method and impl method have the
776                 // same generics.
777                 let num_trait_substs = trait_to_impl_substs.len();
778                 let num_impl_substs = tcx.generics_of(impl_m.container_id(tcx)).params.len();
779                 let ty = tcx.fold_regions(ty, |region, _| {
780                     match region.kind() {
781                         // Remap all free regions, which correspond to late-bound regions in the function.
782                         ty::ReFree(_) => {}
783                         // Remap early-bound regions as long as they don't come from the `impl` itself.
784                         ty::ReEarlyBound(ebr) if tcx.parent(ebr.def_id) != impl_m.container_id(tcx) => {}
785                         _ => return region,
786                     }
787                     let Some(ty::ReEarlyBound(e)) = map.get(&region.into()).map(|r| r.expect_region().kind())
788                     else {
789                         tcx
790                             .sess
791                             .delay_span_bug(
792                                 return_span,
793                                 "expected ReFree to map to ReEarlyBound"
794                             );
795                         return tcx.lifetimes.re_static;
796                     };
797                     tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
798                         def_id: e.def_id,
799                         name: e.name,
800                         index: (e.index as usize - num_trait_substs + num_impl_substs) as u32,
801                     }))
802                 });
803                 debug!(%ty);
804                 collected_tys.insert(def_id, ty);
805             }
806             Err(err) => {
807                 let reported = tcx.sess.delay_span_bug(
808                     return_span,
809                     format!("could not fully resolve: {ty} => {err:?}"),
810                 );
811                 collected_tys.insert(def_id, tcx.ty_error_with_guaranteed(reported));
812             }
813         }
814     }
815
816     Ok(&*tcx.arena.alloc(collected_tys))
817 }
818
819 struct ImplTraitInTraitCollector<'a, 'tcx> {
820     ocx: &'a ObligationCtxt<'a, 'tcx>,
821     types: FxHashMap<DefId, (Ty<'tcx>, ty::SubstsRef<'tcx>)>,
822     span: Span,
823     param_env: ty::ParamEnv<'tcx>,
824     body_id: LocalDefId,
825 }
826
827 impl<'a, 'tcx> ImplTraitInTraitCollector<'a, 'tcx> {
828     fn new(
829         ocx: &'a ObligationCtxt<'a, 'tcx>,
830         span: Span,
831         param_env: ty::ParamEnv<'tcx>,
832         body_id: LocalDefId,
833     ) -> Self {
834         ImplTraitInTraitCollector { ocx, types: FxHashMap::default(), span, param_env, body_id }
835     }
836 }
837
838 impl<'tcx> TypeFolder<'tcx> for ImplTraitInTraitCollector<'_, 'tcx> {
839     fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
840         self.ocx.infcx.tcx
841     }
842
843     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
844         if let ty::Alias(ty::Projection, proj) = ty.kind()
845             && self.tcx().def_kind(proj.def_id) == DefKind::ImplTraitPlaceholder
846         {
847             if let Some((ty, _)) = self.types.get(&proj.def_id) {
848                 return *ty;
849             }
850             //FIXME(RPITIT): Deny nested RPITIT in substs too
851             if proj.substs.has_escaping_bound_vars() {
852                 bug!("FIXME(RPITIT): error here");
853             }
854             // Replace with infer var
855             let infer_ty = self.ocx.infcx.next_ty_var(TypeVariableOrigin {
856                 span: self.span,
857                 kind: TypeVariableOriginKind::MiscVariable,
858             });
859             self.types.insert(proj.def_id, (infer_ty, proj.substs));
860             // Recurse into bounds
861             for (pred, pred_span) in self.tcx().bound_explicit_item_bounds(proj.def_id).subst_iter_copied(self.tcx(), proj.substs) {
862                 let pred = pred.fold_with(self);
863                 let pred = self.ocx.normalize(
864                     &ObligationCause::misc(self.span, self.body_id),
865                     self.param_env,
866                     pred,
867                 );
868
869                 self.ocx.register_obligation(traits::Obligation::new(
870                     self.tcx(),
871                     ObligationCause::new(
872                         self.span,
873                         self.body_id,
874                         ObligationCauseCode::BindingObligation(proj.def_id, pred_span),
875                     ),
876                     self.param_env,
877                     pred,
878                 ));
879             }
880             infer_ty
881         } else {
882             ty.super_fold_with(self)
883         }
884     }
885 }
886
887 fn report_trait_method_mismatch<'tcx>(
888     infcx: &InferCtxt<'tcx>,
889     mut cause: ObligationCause<'tcx>,
890     terr: TypeError<'tcx>,
891     (trait_m, trait_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
892     (impl_m, impl_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
893     impl_trait_ref: ty::TraitRef<'tcx>,
894 ) -> ErrorGuaranteed {
895     let tcx = infcx.tcx;
896     let (impl_err_span, trait_err_span) =
897         extract_spans_for_error_reporting(&infcx, terr, &cause, impl_m, trait_m);
898
899     let mut diag = struct_span_err!(
900         tcx.sess,
901         impl_err_span,
902         E0053,
903         "method `{}` has an incompatible type for trait",
904         trait_m.name
905     );
906     match &terr {
907         TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
908             if trait_m.fn_has_self_parameter =>
909         {
910             let ty = trait_sig.inputs()[0];
911             let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty()) {
912                 ExplicitSelf::ByValue => "self".to_owned(),
913                 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
914                 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
915                 _ => format!("self: {ty}"),
916             };
917
918             // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
919             // span points only at the type `Box<Self`>, but we want to cover the whole
920             // argument pattern and type.
921             let (sig, body) = tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
922             let span = tcx
923                 .hir()
924                 .body_param_names(body)
925                 .zip(sig.decl.inputs.iter())
926                 .map(|(param, ty)| param.span.to(ty.span))
927                 .next()
928                 .unwrap_or(impl_err_span);
929
930             diag.span_suggestion(
931                 span,
932                 "change the self-receiver type to match the trait",
933                 sugg,
934                 Applicability::MachineApplicable,
935             );
936         }
937         TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
938             if trait_sig.inputs().len() == *i {
939                 // Suggestion to change output type. We do not suggest in `async` functions
940                 // to avoid complex logic or incorrect output.
941                 if let ImplItemKind::Fn(sig, _) = &tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind
942                     && !sig.header.asyncness.is_async()
943                 {
944                     let msg = "change the output type to match the trait";
945                     let ap = Applicability::MachineApplicable;
946                     match sig.decl.output {
947                         hir::FnRetTy::DefaultReturn(sp) => {
948                             let sugg = format!("-> {} ", trait_sig.output());
949                             diag.span_suggestion_verbose(sp, msg, sugg, ap);
950                         }
951                         hir::FnRetTy::Return(hir_ty) => {
952                             let sugg = trait_sig.output();
953                             diag.span_suggestion(hir_ty.span, msg, sugg, ap);
954                         }
955                     };
956                 };
957             } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
958                 diag.span_suggestion(
959                     impl_err_span,
960                     "change the parameter type to match the trait",
961                     trait_ty,
962                     Applicability::MachineApplicable,
963                 );
964             }
965         }
966         _ => {}
967     }
968
969     cause.span = impl_err_span;
970     infcx.err_ctxt().note_type_err(
971         &mut diag,
972         &cause,
973         trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
974         Some(infer::ValuePairs::Sigs(ExpectedFound { expected: trait_sig, found: impl_sig })),
975         terr,
976         false,
977         false,
978     );
979
980     return diag.emit();
981 }
982
983 fn check_region_bounds_on_impl_item<'tcx>(
984     tcx: TyCtxt<'tcx>,
985     impl_m: &ty::AssocItem,
986     trait_m: &ty::AssocItem,
987     delay: bool,
988 ) -> Result<(), ErrorGuaranteed> {
989     let impl_generics = tcx.generics_of(impl_m.def_id);
990     let impl_params = impl_generics.own_counts().lifetimes;
991
992     let trait_generics = tcx.generics_of(trait_m.def_id);
993     let trait_params = trait_generics.own_counts().lifetimes;
994
995     debug!(
996         "check_region_bounds_on_impl_item: \
997             trait_generics={:?} \
998             impl_generics={:?}",
999         trait_generics, impl_generics
1000     );
1001
1002     // Must have same number of early-bound lifetime parameters.
1003     // Unfortunately, if the user screws up the bounds, then this
1004     // will change classification between early and late. E.g.,
1005     // if in trait we have `<'a,'b:'a>`, and in impl we just have
1006     // `<'a,'b>`, then we have 2 early-bound lifetime parameters
1007     // in trait but 0 in the impl. But if we report "expected 2
1008     // but found 0" it's confusing, because it looks like there
1009     // are zero. Since I don't quite know how to phrase things at
1010     // the moment, give a kind of vague error message.
1011     if trait_params != impl_params {
1012         let span = tcx
1013             .hir()
1014             .get_generics(impl_m.def_id.expect_local())
1015             .expect("expected impl item to have generics or else we can't compare them")
1016             .span;
1017
1018         let mut generics_span = None;
1019         let mut bounds_span = vec![];
1020         let mut where_span = None;
1021         if let Some(trait_node) = tcx.hir().get_if_local(trait_m.def_id)
1022             && let Some(trait_generics) = trait_node.generics()
1023         {
1024             generics_span = Some(trait_generics.span);
1025             // FIXME: we could potentially look at the impl's bounds to not point at bounds that
1026             // *are* present in the impl.
1027             for p in trait_generics.predicates {
1028                 if let hir::WherePredicate::BoundPredicate(pred) = p {
1029                     for b in pred.bounds {
1030                         if let hir::GenericBound::Outlives(lt) = b {
1031                             bounds_span.push(lt.ident.span);
1032                         }
1033                     }
1034                 }
1035             }
1036             if let Some(impl_node) = tcx.hir().get_if_local(impl_m.def_id)
1037                 && let Some(impl_generics) = impl_node.generics()
1038             {
1039                 let mut impl_bounds = 0;
1040                 for p in impl_generics.predicates {
1041                     if let hir::WherePredicate::BoundPredicate(pred) = p {
1042                         for b in pred.bounds {
1043                             if let hir::GenericBound::Outlives(_) = b {
1044                                 impl_bounds += 1;
1045                             }
1046                         }
1047                     }
1048                 }
1049                 if impl_bounds == bounds_span.len() {
1050                     bounds_span = vec![];
1051                 } else if impl_generics.has_where_clause_predicates {
1052                     where_span = Some(impl_generics.where_clause_span);
1053                 }
1054             }
1055         }
1056         let reported = tcx
1057             .sess
1058             .create_err(LifetimesOrBoundsMismatchOnTrait {
1059                 span,
1060                 item_kind: assoc_item_kind_str(impl_m),
1061                 ident: impl_m.ident(tcx),
1062                 generics_span,
1063                 bounds_span,
1064                 where_span,
1065             })
1066             .emit_unless(delay);
1067         return Err(reported);
1068     }
1069
1070     Ok(())
1071 }
1072
1073 #[instrument(level = "debug", skip(infcx))]
1074 fn extract_spans_for_error_reporting<'tcx>(
1075     infcx: &infer::InferCtxt<'tcx>,
1076     terr: TypeError<'_>,
1077     cause: &ObligationCause<'tcx>,
1078     impl_m: &ty::AssocItem,
1079     trait_m: &ty::AssocItem,
1080 ) -> (Span, Option<Span>) {
1081     let tcx = infcx.tcx;
1082     let mut impl_args = {
1083         let (sig, _) = tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1084         sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1085     };
1086
1087     let trait_args = trait_m.def_id.as_local().map(|def_id| {
1088         let (sig, _) = tcx.hir().expect_trait_item(def_id).expect_fn();
1089         sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1090     });
1091
1092     match terr {
1093         TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1094             (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1095         }
1096         _ => (cause.span(), tcx.hir().span_if_local(trait_m.def_id)),
1097     }
1098 }
1099
1100 fn compare_self_type<'tcx>(
1101     tcx: TyCtxt<'tcx>,
1102     impl_m: &ty::AssocItem,
1103     impl_m_span: Span,
1104     trait_m: &ty::AssocItem,
1105     impl_trait_ref: ty::TraitRef<'tcx>,
1106 ) -> Result<(), ErrorGuaranteed> {
1107     // Try to give more informative error messages about self typing
1108     // mismatches. Note that any mismatch will also be detected
1109     // below, where we construct a canonical function type that
1110     // includes the self parameter as a normal parameter. It's just
1111     // that the error messages you get out of this code are a bit more
1112     // inscrutable, particularly for cases where one method has no
1113     // self.
1114
1115     let self_string = |method: &ty::AssocItem| {
1116         let untransformed_self_ty = match method.container {
1117             ty::ImplContainer => impl_trait_ref.self_ty(),
1118             ty::TraitContainer => tcx.types.self_param,
1119         };
1120         let self_arg_ty = tcx.fn_sig(method.def_id).subst_identity().input(0);
1121         let param_env = ty::ParamEnv::reveal_all();
1122
1123         let infcx = tcx.infer_ctxt().build();
1124         let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1125         let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
1126         match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
1127             ExplicitSelf::ByValue => "self".to_owned(),
1128             ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
1129             ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
1130             _ => format!("self: {self_arg_ty}"),
1131         }
1132     };
1133
1134     match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
1135         (false, false) | (true, true) => {}
1136
1137         (false, true) => {
1138             let self_descr = self_string(impl_m);
1139             let mut err = struct_span_err!(
1140                 tcx.sess,
1141                 impl_m_span,
1142                 E0185,
1143                 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1144                 trait_m.name,
1145                 self_descr
1146             );
1147             err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
1148             if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1149                 err.span_label(span, format!("trait method declared without `{self_descr}`"));
1150             } else {
1151                 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1152             }
1153             return Err(err.emit());
1154         }
1155
1156         (true, false) => {
1157             let self_descr = self_string(trait_m);
1158             let mut err = struct_span_err!(
1159                 tcx.sess,
1160                 impl_m_span,
1161                 E0186,
1162                 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1163                 trait_m.name,
1164                 self_descr
1165             );
1166             err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
1167             if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1168                 err.span_label(span, format!("`{self_descr}` used in trait"));
1169             } else {
1170                 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1171             }
1172
1173             return Err(err.emit());
1174         }
1175     }
1176
1177     Ok(())
1178 }
1179
1180 /// Checks that the number of generics on a given assoc item in a trait impl is the same
1181 /// as the number of generics on the respective assoc item in the trait definition.
1182 ///
1183 /// For example this code emits the errors in the following code:
1184 /// ```
1185 /// trait Trait {
1186 ///     fn foo();
1187 ///     type Assoc<T>;
1188 /// }
1189 ///
1190 /// impl Trait for () {
1191 ///     fn foo<T>() {}
1192 ///     //~^ error
1193 ///     type Assoc = u32;
1194 ///     //~^ error
1195 /// }
1196 /// ```
1197 ///
1198 /// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
1199 /// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
1200 /// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
1201 fn compare_number_of_generics<'tcx>(
1202     tcx: TyCtxt<'tcx>,
1203     impl_: &ty::AssocItem,
1204     trait_: &ty::AssocItem,
1205     trait_span: Option<Span>,
1206     delay: bool,
1207 ) -> Result<(), ErrorGuaranteed> {
1208     let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1209     let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1210
1211     // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
1212     // in `compare_generic_param_kinds` which will give a nicer error message than something like:
1213     // "expected 1 type parameter, found 0 type parameters"
1214     if (trait_own_counts.types + trait_own_counts.consts)
1215         == (impl_own_counts.types + impl_own_counts.consts)
1216     {
1217         return Ok(());
1218     }
1219
1220     let matchings = [
1221         ("type", trait_own_counts.types, impl_own_counts.types),
1222         ("const", trait_own_counts.consts, impl_own_counts.consts),
1223     ];
1224
1225     let item_kind = assoc_item_kind_str(impl_);
1226
1227     let mut err_occurred = None;
1228     for (kind, trait_count, impl_count) in matchings {
1229         if impl_count != trait_count {
1230             let arg_spans = |kind: ty::AssocKind, generics: &hir::Generics<'_>| {
1231                 let mut spans = generics
1232                     .params
1233                     .iter()
1234                     .filter(|p| match p.kind {
1235                         hir::GenericParamKind::Lifetime {
1236                             kind: hir::LifetimeParamKind::Elided,
1237                         } => {
1238                             // A fn can have an arbitrary number of extra elided lifetimes for the
1239                             // same signature.
1240                             !matches!(kind, ty::AssocKind::Fn)
1241                         }
1242                         _ => true,
1243                     })
1244                     .map(|p| p.span)
1245                     .collect::<Vec<Span>>();
1246                 if spans.is_empty() {
1247                     spans = vec![generics.span]
1248                 }
1249                 spans
1250             };
1251             let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1252                 let trait_item = tcx.hir().expect_trait_item(def_id);
1253                 let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics);
1254                 let impl_trait_spans: Vec<Span> = trait_item
1255                     .generics
1256                     .params
1257                     .iter()
1258                     .filter_map(|p| match p.kind {
1259                         GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1260                         _ => None,
1261                     })
1262                     .collect();
1263                 (Some(arg_spans), impl_trait_spans)
1264             } else {
1265                 (trait_span.map(|s| vec![s]), vec![])
1266             };
1267
1268             let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local());
1269             let impl_item_impl_trait_spans: Vec<Span> = impl_item
1270                 .generics
1271                 .params
1272                 .iter()
1273                 .filter_map(|p| match p.kind {
1274                     GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1275                     _ => None,
1276                 })
1277                 .collect();
1278             let spans = arg_spans(impl_.kind, impl_item.generics);
1279             let span = spans.first().copied();
1280
1281             let mut err = tcx.sess.struct_span_err_with_code(
1282                 spans,
1283                 &format!(
1284                     "{} `{}` has {} {kind} parameter{} but its trait \
1285                      declaration has {} {kind} parameter{}",
1286                     item_kind,
1287                     trait_.name,
1288                     impl_count,
1289                     pluralize!(impl_count),
1290                     trait_count,
1291                     pluralize!(trait_count),
1292                     kind = kind,
1293                 ),
1294                 DiagnosticId::Error("E0049".into()),
1295             );
1296
1297             let mut suffix = None;
1298
1299             if let Some(spans) = trait_spans {
1300                 let mut spans = spans.iter();
1301                 if let Some(span) = spans.next() {
1302                     err.span_label(
1303                         *span,
1304                         format!(
1305                             "expected {} {} parameter{}",
1306                             trait_count,
1307                             kind,
1308                             pluralize!(trait_count),
1309                         ),
1310                     );
1311                 }
1312                 for span in spans {
1313                     err.span_label(*span, "");
1314                 }
1315             } else {
1316                 suffix = Some(format!(", expected {trait_count}"));
1317             }
1318
1319             if let Some(span) = span {
1320                 err.span_label(
1321                     span,
1322                     format!(
1323                         "found {} {} parameter{}{}",
1324                         impl_count,
1325                         kind,
1326                         pluralize!(impl_count),
1327                         suffix.unwrap_or_else(String::new),
1328                     ),
1329                 );
1330             }
1331
1332             for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1333                 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1334             }
1335
1336             let reported = err.emit_unless(delay);
1337             err_occurred = Some(reported);
1338         }
1339     }
1340
1341     if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1342 }
1343
1344 fn compare_number_of_method_arguments<'tcx>(
1345     tcx: TyCtxt<'tcx>,
1346     impl_m: &ty::AssocItem,
1347     impl_m_span: Span,
1348     trait_m: &ty::AssocItem,
1349     trait_item_span: Option<Span>,
1350 ) -> Result<(), ErrorGuaranteed> {
1351     let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1352     let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1353     let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
1354     let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1355
1356     if trait_number_args != impl_number_args {
1357         let trait_span = trait_m
1358             .def_id
1359             .as_local()
1360             .and_then(|def_id| {
1361                 let (trait_m_sig, _) = &tcx.hir().expect_trait_item(def_id).expect_fn();
1362                 let pos = trait_number_args.saturating_sub(1);
1363                 trait_m_sig.decl.inputs.get(pos).map(|arg| {
1364                     if pos == 0 {
1365                         arg.span
1366                     } else {
1367                         arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1368                     }
1369                 })
1370             })
1371             .or(trait_item_span);
1372
1373         let (impl_m_sig, _) = &tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1374         let pos = impl_number_args.saturating_sub(1);
1375         let impl_span = impl_m_sig
1376             .decl
1377             .inputs
1378             .get(pos)
1379             .map(|arg| {
1380                 if pos == 0 {
1381                     arg.span
1382                 } else {
1383                     arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1384                 }
1385             })
1386             .unwrap_or(impl_m_span);
1387
1388         let mut err = struct_span_err!(
1389             tcx.sess,
1390             impl_span,
1391             E0050,
1392             "method `{}` has {} but the declaration in trait `{}` has {}",
1393             trait_m.name,
1394             potentially_plural_count(impl_number_args, "parameter"),
1395             tcx.def_path_str(trait_m.def_id),
1396             trait_number_args
1397         );
1398
1399         if let Some(trait_span) = trait_span {
1400             err.span_label(
1401                 trait_span,
1402                 format!(
1403                     "trait requires {}",
1404                     potentially_plural_count(trait_number_args, "parameter")
1405                 ),
1406             );
1407         } else {
1408             err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1409         }
1410
1411         err.span_label(
1412             impl_span,
1413             format!(
1414                 "expected {}, found {}",
1415                 potentially_plural_count(trait_number_args, "parameter"),
1416                 impl_number_args
1417             ),
1418         );
1419
1420         return Err(err.emit());
1421     }
1422
1423     Ok(())
1424 }
1425
1426 fn compare_synthetic_generics<'tcx>(
1427     tcx: TyCtxt<'tcx>,
1428     impl_m: &ty::AssocItem,
1429     trait_m: &ty::AssocItem,
1430 ) -> Result<(), ErrorGuaranteed> {
1431     // FIXME(chrisvittal) Clean up this function, list of FIXME items:
1432     //     1. Better messages for the span labels
1433     //     2. Explanation as to what is going on
1434     // If we get here, we already have the same number of generics, so the zip will
1435     // be okay.
1436     let mut error_found = None;
1437     let impl_m_generics = tcx.generics_of(impl_m.def_id);
1438     let trait_m_generics = tcx.generics_of(trait_m.def_id);
1439     let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
1440         GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1441         GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1442     });
1443     let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
1444         GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1445         GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1446     });
1447     for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1448         iter::zip(impl_m_type_params, trait_m_type_params)
1449     {
1450         if impl_synthetic != trait_synthetic {
1451             let impl_def_id = impl_def_id.expect_local();
1452             let impl_span = tcx.def_span(impl_def_id);
1453             let trait_span = tcx.def_span(trait_def_id);
1454             let mut err = struct_span_err!(
1455                 tcx.sess,
1456                 impl_span,
1457                 E0643,
1458                 "method `{}` has incompatible signature for trait",
1459                 trait_m.name
1460             );
1461             err.span_label(trait_span, "declaration in trait here");
1462             match (impl_synthetic, trait_synthetic) {
1463                 // The case where the impl method uses `impl Trait` but the trait method uses
1464                 // explicit generics
1465                 (true, false) => {
1466                     err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1467                     let _: Option<_> = try {
1468                         // try taking the name from the trait impl
1469                         // FIXME: this is obviously suboptimal since the name can already be used
1470                         // as another generic argument
1471                         let new_name = tcx.opt_item_name(trait_def_id)?;
1472                         let trait_m = trait_m.def_id.as_local()?;
1473                         let trait_m = tcx.hir().expect_trait_item(trait_m);
1474
1475                         let impl_m = impl_m.def_id.as_local()?;
1476                         let impl_m = tcx.hir().expect_impl_item(impl_m);
1477
1478                         // in case there are no generics, take the spot between the function name
1479                         // and the opening paren of the argument list
1480                         let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1481                         // in case there are generics, just replace them
1482                         let generics_span =
1483                             impl_m.generics.span.substitute_dummy(new_generics_span);
1484                         // replace with the generics from the trait
1485                         let new_generics =
1486                             tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1487
1488                         err.multipart_suggestion(
1489                             "try changing the `impl Trait` argument to a generic parameter",
1490                             vec![
1491                                 // replace `impl Trait` with `T`
1492                                 (impl_span, new_name.to_string()),
1493                                 // replace impl method generics with trait method generics
1494                                 // This isn't quite right, as users might have changed the names
1495                                 // of the generics, but it works for the common case
1496                                 (generics_span, new_generics),
1497                             ],
1498                             Applicability::MaybeIncorrect,
1499                         );
1500                     };
1501                 }
1502                 // The case where the trait method uses `impl Trait`, but the impl method uses
1503                 // explicit generics.
1504                 (false, true) => {
1505                     err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1506                     let _: Option<_> = try {
1507                         let impl_m = impl_m.def_id.as_local()?;
1508                         let impl_m = tcx.hir().expect_impl_item(impl_m);
1509                         let (sig, _) = impl_m.expect_fn();
1510                         let input_tys = sig.decl.inputs;
1511
1512                         struct Visitor(Option<Span>, hir::def_id::LocalDefId);
1513                         impl<'v> intravisit::Visitor<'v> for Visitor {
1514                             fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
1515                                 intravisit::walk_ty(self, ty);
1516                                 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
1517                                     && let Res::Def(DefKind::TyParam, def_id) = path.res
1518                                     && def_id == self.1.to_def_id()
1519                                 {
1520                                     self.0 = Some(ty.span);
1521                                 }
1522                             }
1523                         }
1524
1525                         let mut visitor = Visitor(None, impl_def_id);
1526                         for ty in input_tys {
1527                             intravisit::Visitor::visit_ty(&mut visitor, ty);
1528                         }
1529                         let span = visitor.0?;
1530
1531                         let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
1532                         let bounds = bounds.first()?.span().to(bounds.last()?.span());
1533                         let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
1534
1535                         err.multipart_suggestion(
1536                             "try removing the generic parameter and using `impl Trait` instead",
1537                             vec![
1538                                 // delete generic parameters
1539                                 (impl_m.generics.span, String::new()),
1540                                 // replace param usage with `impl Trait`
1541                                 (span, format!("impl {bounds}")),
1542                             ],
1543                             Applicability::MaybeIncorrect,
1544                         );
1545                     };
1546                 }
1547                 _ => unreachable!(),
1548             }
1549             error_found = Some(err.emit());
1550         }
1551     }
1552     if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
1553 }
1554
1555 /// Checks that all parameters in the generics of a given assoc item in a trait impl have
1556 /// the same kind as the respective generic parameter in the trait def.
1557 ///
1558 /// For example all 4 errors in the following code are emitted here:
1559 /// ```
1560 /// trait Foo {
1561 ///     fn foo<const N: u8>();
1562 ///     type bar<const N: u8>;
1563 ///     fn baz<const N: u32>();
1564 ///     type blah<T>;
1565 /// }
1566 ///
1567 /// impl Foo for () {
1568 ///     fn foo<const N: u64>() {}
1569 ///     //~^ error
1570 ///     type bar<const N: u64> {}
1571 ///     //~^ error
1572 ///     fn baz<T>() {}
1573 ///     //~^ error
1574 ///     type blah<const N: i64> = u32;
1575 ///     //~^ error
1576 /// }
1577 /// ```
1578 ///
1579 /// This function does not handle lifetime parameters
1580 fn compare_generic_param_kinds<'tcx>(
1581     tcx: TyCtxt<'tcx>,
1582     impl_item: &ty::AssocItem,
1583     trait_item: &ty::AssocItem,
1584     delay: bool,
1585 ) -> Result<(), ErrorGuaranteed> {
1586     assert_eq!(impl_item.kind, trait_item.kind);
1587
1588     let ty_const_params_of = |def_id| {
1589         tcx.generics_of(def_id).params.iter().filter(|param| {
1590             matches!(
1591                 param.kind,
1592                 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1593             )
1594         })
1595     };
1596
1597     for (param_impl, param_trait) in
1598         iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1599     {
1600         use GenericParamDefKind::*;
1601         if match (&param_impl.kind, &param_trait.kind) {
1602             (Const { .. }, Const { .. })
1603                 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1604             {
1605                 true
1606             }
1607             (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1608             // this is exhaustive so that anyone adding new generic param kinds knows
1609             // to make sure this error is reported for them.
1610             (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1611             (Lifetime { .. }, _) | (_, Lifetime { .. }) => unreachable!(),
1612         } {
1613             let param_impl_span = tcx.def_span(param_impl.def_id);
1614             let param_trait_span = tcx.def_span(param_trait.def_id);
1615
1616             let mut err = struct_span_err!(
1617                 tcx.sess,
1618                 param_impl_span,
1619                 E0053,
1620                 "{} `{}` has an incompatible generic parameter for trait `{}`",
1621                 assoc_item_kind_str(&impl_item),
1622                 trait_item.name,
1623                 &tcx.def_path_str(tcx.parent(trait_item.def_id))
1624             );
1625
1626             let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
1627                 Const { .. } => {
1628                     format!("{} const parameter of type `{}`", prefix, tcx.type_of(param.def_id))
1629                 }
1630                 Type { .. } => format!("{} type parameter", prefix),
1631                 Lifetime { .. } => unreachable!(),
1632             };
1633
1634             let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
1635             err.span_label(trait_header_span, "");
1636             err.span_label(param_trait_span, make_param_message("expected", param_trait));
1637
1638             let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1639             err.span_label(impl_header_span, "");
1640             err.span_label(param_impl_span, make_param_message("found", param_impl));
1641
1642             let reported = err.emit_unless(delay);
1643             return Err(reported);
1644         }
1645     }
1646
1647     Ok(())
1648 }
1649
1650 /// Use `tcx.compare_impl_const` instead
1651 pub(super) fn compare_impl_const_raw(
1652     tcx: TyCtxt<'_>,
1653     (impl_const_item_def, trait_const_item_def): (LocalDefId, DefId),
1654 ) -> Result<(), ErrorGuaranteed> {
1655     let impl_const_item = tcx.associated_item(impl_const_item_def);
1656     let trait_const_item = tcx.associated_item(trait_const_item_def);
1657     let impl_trait_ref =
1658         tcx.impl_trait_ref(impl_const_item.container_id(tcx)).unwrap().subst_identity();
1659     debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
1660
1661     let impl_c_span = tcx.def_span(impl_const_item_def.to_def_id());
1662
1663     let infcx = tcx.infer_ctxt().build();
1664     let param_env = tcx.param_env(impl_const_item_def.to_def_id());
1665     let ocx = ObligationCtxt::new(&infcx);
1666
1667     // The below is for the most part highly similar to the procedure
1668     // for methods above. It is simpler in many respects, especially
1669     // because we shouldn't really have to deal with lifetimes or
1670     // predicates. In fact some of this should probably be put into
1671     // shared functions because of DRY violations...
1672     let trait_to_impl_substs = impl_trait_ref.substs;
1673
1674     // Create a parameter environment that represents the implementation's
1675     // method.
1676     // Compute placeholder form of impl and trait const tys.
1677     let impl_ty = tcx.type_of(impl_const_item_def.to_def_id());
1678     let trait_ty = tcx.bound_type_of(trait_const_item_def).subst(tcx, trait_to_impl_substs);
1679     let mut cause = ObligationCause::new(
1680         impl_c_span,
1681         impl_const_item_def,
1682         ObligationCauseCode::CompareImplItemObligation {
1683             impl_item_def_id: impl_const_item_def,
1684             trait_item_def_id: trait_const_item_def,
1685             kind: impl_const_item.kind,
1686         },
1687     );
1688
1689     // There is no "body" here, so just pass dummy id.
1690     let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
1691
1692     debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1693
1694     let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
1695
1696     debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1697
1698     let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
1699
1700     if let Err(terr) = err {
1701         debug!(
1702             "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1703             impl_ty, trait_ty
1704         );
1705
1706         // Locate the Span containing just the type of the offending impl
1707         let (ty, _) = tcx.hir().expect_impl_item(impl_const_item_def).expect_const();
1708         cause.span = ty.span;
1709
1710         let mut diag = struct_span_err!(
1711             tcx.sess,
1712             cause.span,
1713             E0326,
1714             "implemented const `{}` has an incompatible type for trait",
1715             trait_const_item.name
1716         );
1717
1718         let trait_c_span = trait_const_item_def.as_local().map(|trait_c_def_id| {
1719             // Add a label to the Span containing just the type of the const
1720             let (ty, _) = tcx.hir().expect_trait_item(trait_c_def_id).expect_const();
1721             ty.span
1722         });
1723
1724         infcx.err_ctxt().note_type_err(
1725             &mut diag,
1726             &cause,
1727             trait_c_span.map(|span| (span, "type in trait".to_owned())),
1728             Some(infer::ValuePairs::Terms(ExpectedFound {
1729                 expected: trait_ty.into(),
1730                 found: impl_ty.into(),
1731             })),
1732             terr,
1733             false,
1734             false,
1735         );
1736         return Err(diag.emit());
1737     };
1738
1739     // Check that all obligations are satisfied by the implementation's
1740     // version.
1741     let errors = ocx.select_all_or_error();
1742     if !errors.is_empty() {
1743         return Err(infcx.err_ctxt().report_fulfillment_errors(&errors, None));
1744     }
1745
1746     let outlives_environment = OutlivesEnvironment::new(param_env);
1747     infcx
1748         .err_ctxt()
1749         .check_region_obligations_and_report_errors(impl_const_item_def, &outlives_environment)?;
1750     Ok(())
1751 }
1752
1753 pub(super) fn compare_impl_ty<'tcx>(
1754     tcx: TyCtxt<'tcx>,
1755     impl_ty: &ty::AssocItem,
1756     impl_ty_span: Span,
1757     trait_ty: &ty::AssocItem,
1758     impl_trait_ref: ty::TraitRef<'tcx>,
1759     trait_item_span: Option<Span>,
1760 ) {
1761     debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1762
1763     let _: Result<(), ErrorGuaranteed> = try {
1764         compare_number_of_generics(tcx, impl_ty, trait_ty, trait_item_span, false)?;
1765
1766         compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
1767
1768         let sp = tcx.def_span(impl_ty.def_id);
1769         compare_type_predicate_entailment(tcx, impl_ty, sp, trait_ty, impl_trait_ref)?;
1770
1771         check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)?;
1772     };
1773 }
1774
1775 /// The equivalent of [compare_method_predicate_entailment], but for associated types
1776 /// instead of associated functions.
1777 fn compare_type_predicate_entailment<'tcx>(
1778     tcx: TyCtxt<'tcx>,
1779     impl_ty: &ty::AssocItem,
1780     impl_ty_span: Span,
1781     trait_ty: &ty::AssocItem,
1782     impl_trait_ref: ty::TraitRef<'tcx>,
1783 ) -> Result<(), ErrorGuaranteed> {
1784     let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1785     let trait_to_impl_substs =
1786         impl_substs.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.substs);
1787
1788     let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1789     let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1790
1791     check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
1792
1793     let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1794     if impl_ty_own_bounds.len() == 0 {
1795         // Nothing to check.
1796         return Ok(());
1797     }
1798
1799     // This `HirId` should be used for the `body_id` field on each
1800     // `ObligationCause` (and the `FnCtxt`). This is what
1801     // `regionck_item` expects.
1802     let impl_ty_def_id = impl_ty.def_id.expect_local();
1803     debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1804
1805     // The predicates declared by the impl definition, the trait and the
1806     // associated type in the trait are assumed.
1807     let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1808     let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1809     hybrid_preds.predicates.extend(
1810         trait_ty_predicates
1811             .instantiate_own(tcx, trait_to_impl_substs)
1812             .map(|(predicate, _)| predicate),
1813     );
1814
1815     debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1816
1817     let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_def_id);
1818     let param_env = ty::ParamEnv::new(
1819         tcx.intern_predicates(&hybrid_preds.predicates),
1820         Reveal::UserFacing,
1821         hir::Constness::NotConst,
1822     );
1823     let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
1824     let infcx = tcx.infer_ctxt().build();
1825     let ocx = ObligationCtxt::new(&infcx);
1826
1827     debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1828
1829     for (predicate, span) in impl_ty_own_bounds {
1830         let cause = ObligationCause::misc(span, impl_ty_def_id);
1831         let predicate = ocx.normalize(&cause, param_env, predicate);
1832
1833         let cause = ObligationCause::new(
1834             span,
1835             impl_ty_def_id,
1836             ObligationCauseCode::CompareImplItemObligation {
1837                 impl_item_def_id: impl_ty.def_id.expect_local(),
1838                 trait_item_def_id: trait_ty.def_id,
1839                 kind: impl_ty.kind,
1840             },
1841         );
1842         ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
1843     }
1844
1845     // Check that all obligations are satisfied by the implementation's
1846     // version.
1847     let errors = ocx.select_all_or_error();
1848     if !errors.is_empty() {
1849         let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
1850         return Err(reported);
1851     }
1852
1853     // Finally, resolve all regions. This catches wily misuses of
1854     // lifetime parameters.
1855     let outlives_environment = OutlivesEnvironment::new(param_env);
1856     infcx.err_ctxt().check_region_obligations_and_report_errors(
1857         impl_ty.def_id.expect_local(),
1858         &outlives_environment,
1859     )?;
1860
1861     Ok(())
1862 }
1863
1864 /// Validate that `ProjectionCandidate`s created for this associated type will
1865 /// be valid.
1866 ///
1867 /// Usually given
1868 ///
1869 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1870 ///
1871 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1872 /// impl is well-formed we have to prove `S: Copy`.
1873 ///
1874 /// For default associated types the normalization is not possible (the value
1875 /// from the impl could be overridden). We also can't normalize generic
1876 /// associated types (yet) because they contain bound parameters.
1877 #[instrument(level = "debug", skip(tcx))]
1878 pub(super) fn check_type_bounds<'tcx>(
1879     tcx: TyCtxt<'tcx>,
1880     trait_ty: &ty::AssocItem,
1881     impl_ty: &ty::AssocItem,
1882     impl_ty_span: Span,
1883     impl_trait_ref: ty::TraitRef<'tcx>,
1884 ) -> Result<(), ErrorGuaranteed> {
1885     // Given
1886     //
1887     // impl<A, B> Foo<u32> for (A, B) {
1888     //     type Bar<C> =...
1889     // }
1890     //
1891     // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1892     // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1893     // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1894     //    the *trait* with the generic associated type parameters (as bound vars).
1895     //
1896     // A note regarding the use of bound vars here:
1897     // Imagine as an example
1898     // ```
1899     // trait Family {
1900     //     type Member<C: Eq>;
1901     // }
1902     //
1903     // impl Family for VecFamily {
1904     //     type Member<C: Eq> = i32;
1905     // }
1906     // ```
1907     // Here, we would generate
1908     // ```notrust
1909     // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1910     // ```
1911     // when we really would like to generate
1912     // ```notrust
1913     // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1914     // ```
1915     // But, this is probably fine, because although the first clause can be used with types C that
1916     // do not implement Eq, for it to cause some kind of problem, there would have to be a
1917     // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1918     // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1919     // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1920     // the trait (notably, that X: Eq and T: Family).
1921     let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1922     let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1923     if let Some(def_id) = defs.parent {
1924         let parent_defs = tcx.generics_of(def_id);
1925         InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1926             tcx.mk_param_from_def(param)
1927         });
1928     }
1929     let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1930         smallvec::SmallVec::with_capacity(defs.count());
1931     InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1932         GenericParamDefKind::Type { .. } => {
1933             let kind = ty::BoundTyKind::Param(param.def_id, param.name);
1934             let bound_var = ty::BoundVariableKind::Ty(kind);
1935             bound_vars.push(bound_var);
1936             tcx.mk_ty(ty::Bound(
1937                 ty::INNERMOST,
1938                 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1939             ))
1940             .into()
1941         }
1942         GenericParamDefKind::Lifetime => {
1943             let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1944             let bound_var = ty::BoundVariableKind::Region(kind);
1945             bound_vars.push(bound_var);
1946             tcx.mk_region(ty::ReLateBound(
1947                 ty::INNERMOST,
1948                 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1949             ))
1950             .into()
1951         }
1952         GenericParamDefKind::Const { .. } => {
1953             let bound_var = ty::BoundVariableKind::Const;
1954             bound_vars.push(bound_var);
1955             tcx.mk_const(
1956                 ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_usize(bound_vars.len() - 1)),
1957                 tcx.type_of(param.def_id),
1958             )
1959             .into()
1960         }
1961     });
1962     let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
1963     let impl_ty_substs = tcx.intern_substs(&substs);
1964     let container_id = impl_ty.container_id(tcx);
1965
1966     let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
1967     let impl_ty_value = tcx.type_of(impl_ty.def_id);
1968
1969     let param_env = tcx.param_env(impl_ty.def_id);
1970
1971     // When checking something like
1972     //
1973     // trait X { type Y: PartialEq<<Self as X>::Y> }
1974     // impl X for T { default type Y = S; }
1975     //
1976     // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
1977     // we want <T as X>::Y to normalize to S. This is valid because we are
1978     // checking the default value specifically here. Add this equality to the
1979     // ParamEnv for normalization specifically.
1980     let normalize_param_env = {
1981         let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
1982         match impl_ty_value.kind() {
1983             ty::Alias(ty::Projection, proj)
1984                 if proj.def_id == trait_ty.def_id && proj.substs == rebased_substs =>
1985             {
1986                 // Don't include this predicate if the projected type is
1987                 // exactly the same as the projection. This can occur in
1988                 // (somewhat dubious) code like this:
1989                 //
1990                 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
1991             }
1992             _ => predicates.push(
1993                 ty::Binder::bind_with_vars(
1994                     ty::ProjectionPredicate {
1995                         projection_ty: tcx.mk_alias_ty(trait_ty.def_id, rebased_substs),
1996                         term: impl_ty_value.into(),
1997                     },
1998                     bound_vars,
1999                 )
2000                 .to_predicate(tcx),
2001             ),
2002         };
2003         ty::ParamEnv::new(
2004             tcx.intern_predicates(&predicates),
2005             Reveal::UserFacing,
2006             param_env.constness(),
2007         )
2008     };
2009     debug!(?normalize_param_env);
2010
2011     let impl_ty_def_id = impl_ty.def_id.expect_local();
2012     let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
2013     let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
2014
2015     let infcx = tcx.infer_ctxt().build();
2016     let ocx = ObligationCtxt::new(&infcx);
2017
2018     let assumed_wf_types =
2019         ocx.assumed_wf_types(param_env, impl_ty_span, impl_ty.def_id.expect_local());
2020
2021     let normalize_cause = ObligationCause::new(
2022         impl_ty_span,
2023         impl_ty_def_id,
2024         ObligationCauseCode::CheckAssociatedTypeBounds {
2025             impl_item_def_id: impl_ty.def_id.expect_local(),
2026             trait_item_def_id: trait_ty.def_id,
2027         },
2028     );
2029     let mk_cause = |span: Span| {
2030         let code = if span.is_dummy() {
2031             traits::ItemObligation(trait_ty.def_id)
2032         } else {
2033             traits::BindingObligation(trait_ty.def_id, span)
2034         };
2035         ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2036     };
2037
2038     let obligations = tcx
2039         .bound_explicit_item_bounds(trait_ty.def_id)
2040         .subst_iter_copied(tcx, rebased_substs)
2041         .map(|(concrete_ty_bound, span)| {
2042             debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
2043             traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2044         })
2045         .collect();
2046     debug!("check_type_bounds: item_bounds={:?}", obligations);
2047
2048     for mut obligation in util::elaborate_obligations(tcx, obligations) {
2049         let normalized_predicate =
2050             ocx.normalize(&normalize_cause, normalize_param_env, obligation.predicate);
2051         debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
2052         obligation.predicate = normalized_predicate;
2053
2054         ocx.register_obligation(obligation);
2055     }
2056     // Check that all obligations are satisfied by the implementation's
2057     // version.
2058     let errors = ocx.select_all_or_error();
2059     if !errors.is_empty() {
2060         let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
2061         return Err(reported);
2062     }
2063
2064     // Finally, resolve all regions. This catches wily misuses of
2065     // lifetime parameters.
2066     let implied_bounds = infcx.implied_bounds_tys(param_env, impl_ty_def_id, assumed_wf_types);
2067     let outlives_environment =
2068         OutlivesEnvironment::with_bounds(param_env, Some(&infcx), implied_bounds);
2069
2070     infcx.err_ctxt().check_region_obligations_and_report_errors(
2071         impl_ty.def_id.expect_local(),
2072         &outlives_environment,
2073     )?;
2074
2075     Ok(())
2076 }
2077
2078 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
2079     match impl_item.kind {
2080         ty::AssocKind::Const => "const",
2081         ty::AssocKind::Fn => "method",
2082         ty::AssocKind::Type => "type",
2083     }
2084 }