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