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