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