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