]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/check/compare_impl_item.rs
Rollup merge of #106489 - jschwe:fix_linker_detection, r=petrochenkov
[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 = tcx.impl_trait_ref(impl_m.impl_container(tcx).unwrap()).unwrap();
620     let param_env = tcx.param_env(def_id);
621
622     // First, check a few of the same things as `compare_impl_method`,
623     // just so we don't ICE during substitution later.
624     compare_number_of_generics(tcx, impl_m, trait_m, tcx.hir().span_if_local(impl_m.def_id), true)?;
625     compare_generic_param_kinds(tcx, impl_m, trait_m, true)?;
626     check_region_bounds_on_impl_item(tcx, impl_m, trait_m, true)?;
627
628     let trait_to_impl_substs = impl_trait_ref.substs;
629
630     let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
631     let return_span = tcx.hir().fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
632     let cause = ObligationCause::new(
633         return_span,
634         impl_m_hir_id,
635         ObligationCauseCode::CompareImplItemObligation {
636             impl_item_def_id: impl_m.def_id.expect_local(),
637             trait_item_def_id: trait_m.def_id,
638             kind: impl_m.kind,
639         },
640     );
641
642     // Create mapping from impl to placeholder.
643     let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
644
645     // Create mapping from trait to placeholder.
646     let trait_to_placeholder_substs =
647         impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
648
649     let infcx = &tcx.infer_ctxt().build();
650     let ocx = ObligationCtxt::new(infcx);
651
652     // Normalize the impl signature with fresh variables for lifetime inference.
653     let norm_cause = ObligationCause::misc(return_span, impl_m_hir_id);
654     let impl_sig = ocx.normalize(
655         &norm_cause,
656         param_env,
657         infcx.replace_bound_vars_with_fresh_vars(
658             return_span,
659             infer::HigherRankedType,
660             tcx.fn_sig(impl_m.def_id),
661         ),
662     );
663     impl_sig.error_reported()?;
664     let impl_return_ty = impl_sig.output();
665
666     // Normalize the trait signature with liberated bound vars, passing it through
667     // the ImplTraitInTraitCollector, which gathers all of the RPITITs and replaces
668     // them with inference variables.
669     // We will use these inference variables to collect the hidden types of RPITITs.
670     let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_hir_id);
671     let unnormalized_trait_sig = tcx
672         .liberate_late_bound_regions(
673             impl_m.def_id,
674             tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs),
675         )
676         .fold_with(&mut collector);
677     let trait_sig = ocx.normalize(&norm_cause, param_env, unnormalized_trait_sig);
678     trait_sig.error_reported()?;
679     let trait_return_ty = trait_sig.output();
680
681     let wf_tys = FxIndexSet::from_iter(
682         unnormalized_trait_sig.inputs_and_output.iter().chain(trait_sig.inputs_and_output.iter()),
683     );
684
685     match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
686         Ok(()) => {}
687         Err(terr) => {
688             let mut diag = struct_span_err!(
689                 tcx.sess,
690                 cause.span(),
691                 E0053,
692                 "method `{}` has an incompatible return type for trait",
693                 trait_m.name
694             );
695             let hir = tcx.hir();
696             infcx.err_ctxt().note_type_err(
697                 &mut diag,
698                 &cause,
699                 hir.get_if_local(impl_m.def_id)
700                     .and_then(|node| node.fn_decl())
701                     .map(|decl| (decl.output.span(), "return type in trait".to_owned())),
702                 Some(infer::ValuePairs::Terms(ExpectedFound {
703                     expected: trait_return_ty.into(),
704                     found: impl_return_ty.into(),
705                 })),
706                 terr,
707                 false,
708                 false,
709             );
710             return Err(diag.emit());
711         }
712     }
713
714     debug!(?trait_sig, ?impl_sig, "equating function signatures");
715
716     // Unify the whole function signature. We need to do this to fully infer
717     // the lifetimes of the return type, but do this after unifying just the
718     // return types, since we want to avoid duplicating errors from
719     // `compare_method_predicate_entailment`.
720     match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
721         Ok(()) => {}
722         Err(terr) => {
723             // This function gets called during `compare_method_predicate_entailment` when normalizing a
724             // signature that contains RPITIT. When the method signatures don't match, we have to
725             // emit an error now because `compare_method_predicate_entailment` will not report the error
726             // when normalization fails.
727             let emitted = report_trait_method_mismatch(
728                 infcx,
729                 cause,
730                 terr,
731                 (trait_m, trait_sig),
732                 (impl_m, impl_sig),
733                 impl_trait_ref,
734             );
735             return Err(emitted);
736         }
737     }
738
739     // Check that all obligations are satisfied by the implementation's
740     // RPITs.
741     let errors = ocx.select_all_or_error();
742     if !errors.is_empty() {
743         let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
744         return Err(reported);
745     }
746
747     // Finally, resolve all regions. This catches wily misuses of
748     // lifetime parameters.
749     let outlives_environment = OutlivesEnvironment::with_bounds(
750         param_env,
751         Some(infcx),
752         infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys),
753     );
754     infcx.err_ctxt().check_region_obligations_and_report_errors(
755         impl_m.def_id.expect_local(),
756         &outlives_environment,
757     )?;
758
759     let mut collected_tys = FxHashMap::default();
760     for (def_id, (ty, substs)) in collector.types {
761         match infcx.fully_resolve(ty) {
762             Ok(ty) => {
763                 // `ty` contains free regions that we created earlier while liberating the
764                 // trait fn signature.  However, projection normalization expects `ty` to
765                 // contains `def_id`'s early-bound regions.
766                 let id_substs = InternalSubsts::identity_for_item(tcx, def_id);
767                 debug!(?id_substs, ?substs);
768                 let map: FxHashMap<ty::GenericArg<'tcx>, ty::GenericArg<'tcx>> =
769                     std::iter::zip(substs, id_substs).collect();
770                 debug!(?map);
771
772                 // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound
773                 // region substs that are synthesized during AST lowering. These are substs
774                 // that are appended to the parent substs (trait and trait method). However,
775                 // we're trying to infer the unsubstituted type value of the RPITIT inside
776                 // the *impl*, so we can later use the impl's method substs to normalize
777                 // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`).
778                 //
779                 // Due to the design of RPITITs, during AST lowering, we have no idea that
780                 // an impl method corresponds to a trait method with RPITITs in it. Therefore,
781                 // we don't have a list of early-bound region substs for the RPITIT in the impl.
782                 // Since early region parameters are index-based, we can't just rebase these
783                 // (trait method) early-bound region substs onto the impl, and there's no
784                 // guarantee that the indices from the trait substs and impl substs line up.
785                 // So to fix this, we subtract the number of trait substs and add the number of
786                 // impl substs to *renumber* these early-bound regions to their corresponding
787                 // indices in the impl's substitutions list.
788                 //
789                 // Also, we only need to account for a difference in trait and impl substs,
790                 // since we previously enforce that the trait method and impl method have the
791                 // same generics.
792                 let num_trait_substs = trait_to_impl_substs.len();
793                 let num_impl_substs = tcx.generics_of(impl_m.container_id(tcx)).params.len();
794                 let ty = tcx.fold_regions(ty, |region, _| {
795                     match region.kind() {
796                         // Remap all free regions, which correspond to late-bound regions in the function.
797                         ty::ReFree(_) => {}
798                         // Remap early-bound regions as long as they don't come from the `impl` itself.
799                         ty::ReEarlyBound(ebr) if tcx.parent(ebr.def_id) != impl_m.container_id(tcx) => {}
800                         _ => return region,
801                     }
802                     let Some(ty::ReEarlyBound(e)) = map.get(&region.into()).map(|r| r.expect_region().kind())
803                     else {
804                         tcx
805                             .sess
806                             .delay_span_bug(
807                                 return_span,
808                                 "expected ReFree to map to ReEarlyBound"
809                             );
810                         return tcx.lifetimes.re_static;
811                     };
812                     tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
813                         def_id: e.def_id,
814                         name: e.name,
815                         index: (e.index as usize - num_trait_substs + num_impl_substs) as u32,
816                     }))
817                 });
818                 debug!(%ty);
819                 collected_tys.insert(def_id, ty);
820             }
821             Err(err) => {
822                 let reported = tcx.sess.delay_span_bug(
823                     return_span,
824                     format!("could not fully resolve: {ty} => {err:?}"),
825                 );
826                 collected_tys.insert(def_id, tcx.ty_error_with_guaranteed(reported));
827             }
828         }
829     }
830
831     Ok(&*tcx.arena.alloc(collected_tys))
832 }
833
834 struct ImplTraitInTraitCollector<'a, 'tcx> {
835     ocx: &'a ObligationCtxt<'a, 'tcx>,
836     types: FxHashMap<DefId, (Ty<'tcx>, ty::SubstsRef<'tcx>)>,
837     span: Span,
838     param_env: ty::ParamEnv<'tcx>,
839     body_id: hir::HirId,
840 }
841
842 impl<'a, 'tcx> ImplTraitInTraitCollector<'a, 'tcx> {
843     fn new(
844         ocx: &'a ObligationCtxt<'a, 'tcx>,
845         span: Span,
846         param_env: ty::ParamEnv<'tcx>,
847         body_id: hir::HirId,
848     ) -> Self {
849         ImplTraitInTraitCollector { ocx, types: FxHashMap::default(), span, param_env, body_id }
850     }
851 }
852
853 impl<'tcx> TypeFolder<'tcx> for ImplTraitInTraitCollector<'_, 'tcx> {
854     fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
855         self.ocx.infcx.tcx
856     }
857
858     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
859         if let ty::Alias(ty::Projection, proj) = ty.kind()
860             && self.tcx().def_kind(proj.def_id) == DefKind::ImplTraitPlaceholder
861         {
862             if let Some((ty, _)) = self.types.get(&proj.def_id) {
863                 return *ty;
864             }
865             //FIXME(RPITIT): Deny nested RPITIT in substs too
866             if proj.substs.has_escaping_bound_vars() {
867                 bug!("FIXME(RPITIT): error here");
868             }
869             // Replace with infer var
870             let infer_ty = self.ocx.infcx.next_ty_var(TypeVariableOrigin {
871                 span: self.span,
872                 kind: TypeVariableOriginKind::MiscVariable,
873             });
874             self.types.insert(proj.def_id, (infer_ty, proj.substs));
875             // Recurse into bounds
876             for (pred, pred_span) in self.tcx().bound_explicit_item_bounds(proj.def_id).subst_iter_copied(self.tcx(), proj.substs) {
877                 let pred = pred.fold_with(self);
878                 let pred = self.ocx.normalize(
879                     &ObligationCause::misc(self.span, self.body_id),
880                     self.param_env,
881                     pred,
882                 );
883
884                 self.ocx.register_obligation(traits::Obligation::new(
885                     self.tcx(),
886                     ObligationCause::new(
887                         self.span,
888                         self.body_id,
889                         ObligationCauseCode::BindingObligation(proj.def_id, pred_span),
890                     ),
891                     self.param_env,
892                     pred,
893                 ));
894             }
895             infer_ty
896         } else {
897             ty.super_fold_with(self)
898         }
899     }
900 }
901
902 fn report_trait_method_mismatch<'tcx>(
903     infcx: &InferCtxt<'tcx>,
904     mut cause: ObligationCause<'tcx>,
905     terr: TypeError<'tcx>,
906     (trait_m, trait_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
907     (impl_m, impl_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
908     impl_trait_ref: ty::TraitRef<'tcx>,
909 ) -> ErrorGuaranteed {
910     let tcx = infcx.tcx;
911     let (impl_err_span, trait_err_span) =
912         extract_spans_for_error_reporting(&infcx, terr, &cause, impl_m, trait_m);
913
914     let mut diag = struct_span_err!(
915         tcx.sess,
916         impl_err_span,
917         E0053,
918         "method `{}` has an incompatible type for trait",
919         trait_m.name
920     );
921     match &terr {
922         TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
923             if trait_m.fn_has_self_parameter =>
924         {
925             let ty = trait_sig.inputs()[0];
926             let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty()) {
927                 ExplicitSelf::ByValue => "self".to_owned(),
928                 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
929                 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
930                 _ => format!("self: {ty}"),
931             };
932
933             // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
934             // span points only at the type `Box<Self`>, but we want to cover the whole
935             // argument pattern and type.
936             let span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
937                 ImplItemKind::Fn(ref sig, body) => tcx
938                     .hir()
939                     .body_param_names(body)
940                     .zip(sig.decl.inputs.iter())
941                     .map(|(param, ty)| param.span.to(ty.span))
942                     .next()
943                     .unwrap_or(impl_err_span),
944                 _ => bug!("{:?} is not a method", impl_m),
945             };
946
947             diag.span_suggestion(
948                 span,
949                 "change the self-receiver type to match the trait",
950                 sugg,
951                 Applicability::MachineApplicable,
952             );
953         }
954         TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
955             if trait_sig.inputs().len() == *i {
956                 // Suggestion to change output type. We do not suggest in `async` functions
957                 // to avoid complex logic or incorrect output.
958                 match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
959                     ImplItemKind::Fn(ref sig, _) if !sig.header.asyncness.is_async() => {
960                         let msg = "change the output type to match the trait";
961                         let ap = Applicability::MachineApplicable;
962                         match sig.decl.output {
963                             hir::FnRetTy::DefaultReturn(sp) => {
964                                 let sugg = format!("-> {} ", trait_sig.output());
965                                 diag.span_suggestion_verbose(sp, msg, sugg, ap);
966                             }
967                             hir::FnRetTy::Return(hir_ty) => {
968                                 let sugg = trait_sig.output();
969                                 diag.span_suggestion(hir_ty.span, msg, sugg, ap);
970                             }
971                         };
972                     }
973                     _ => {}
974                 };
975             } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
976                 diag.span_suggestion(
977                     impl_err_span,
978                     "change the parameter type to match the trait",
979                     trait_ty,
980                     Applicability::MachineApplicable,
981                 );
982             }
983         }
984         _ => {}
985     }
986
987     cause.span = impl_err_span;
988     infcx.err_ctxt().note_type_err(
989         &mut diag,
990         &cause,
991         trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
992         Some(infer::ValuePairs::Sigs(ExpectedFound { expected: trait_sig, found: impl_sig })),
993         terr,
994         false,
995         false,
996     );
997
998     return diag.emit();
999 }
1000
1001 fn check_region_bounds_on_impl_item<'tcx>(
1002     tcx: TyCtxt<'tcx>,
1003     impl_m: &ty::AssocItem,
1004     trait_m: &ty::AssocItem,
1005     delay: bool,
1006 ) -> Result<(), ErrorGuaranteed> {
1007     let impl_generics = tcx.generics_of(impl_m.def_id);
1008     let impl_params = impl_generics.own_counts().lifetimes;
1009
1010     let trait_generics = tcx.generics_of(trait_m.def_id);
1011     let trait_params = trait_generics.own_counts().lifetimes;
1012
1013     debug!(
1014         "check_region_bounds_on_impl_item: \
1015             trait_generics={:?} \
1016             impl_generics={:?}",
1017         trait_generics, impl_generics
1018     );
1019
1020     // Must have same number of early-bound lifetime parameters.
1021     // Unfortunately, if the user screws up the bounds, then this
1022     // will change classification between early and late.  E.g.,
1023     // if in trait we have `<'a,'b:'a>`, and in impl we just have
1024     // `<'a,'b>`, then we have 2 early-bound lifetime parameters
1025     // in trait but 0 in the impl. But if we report "expected 2
1026     // but found 0" it's confusing, because it looks like there
1027     // are zero. Since I don't quite know how to phrase things at
1028     // the moment, give a kind of vague error message.
1029     if trait_params != impl_params {
1030         let span = tcx
1031             .hir()
1032             .get_generics(impl_m.def_id.expect_local())
1033             .expect("expected impl item to have generics or else we can't compare them")
1034             .span;
1035
1036         let mut generics_span = None;
1037         let mut bounds_span = vec![];
1038         let mut where_span = None;
1039         if let Some(trait_node) = tcx.hir().get_if_local(trait_m.def_id)
1040             && let Some(trait_generics) = trait_node.generics()
1041         {
1042             generics_span = Some(trait_generics.span);
1043             // FIXME: we could potentially look at the impl's bounds to not point at bounds that
1044             // *are* present in the impl.
1045             for p in trait_generics.predicates {
1046                 if let hir::WherePredicate::BoundPredicate(pred) = p {
1047                     for b in pred.bounds {
1048                         if let hir::GenericBound::Outlives(lt) = b {
1049                             bounds_span.push(lt.ident.span);
1050                         }
1051                     }
1052                 }
1053             }
1054             if let Some(impl_node) = tcx.hir().get_if_local(impl_m.def_id)
1055                 && let Some(impl_generics) = impl_node.generics()
1056             {
1057                 let mut impl_bounds = 0;
1058                 for p in impl_generics.predicates {
1059                     if let hir::WherePredicate::BoundPredicate(pred) = p {
1060                         for b in pred.bounds {
1061                             if let hir::GenericBound::Outlives(_) = b {
1062                                 impl_bounds += 1;
1063                             }
1064                         }
1065                     }
1066                 }
1067                 if impl_bounds == bounds_span.len() {
1068                     bounds_span = vec![];
1069                 } else if impl_generics.has_where_clause_predicates {
1070                     where_span = Some(impl_generics.where_clause_span);
1071                 }
1072             }
1073         }
1074         let reported = tcx
1075             .sess
1076             .create_err(LifetimesOrBoundsMismatchOnTrait {
1077                 span,
1078                 item_kind: assoc_item_kind_str(impl_m),
1079                 ident: impl_m.ident(tcx),
1080                 generics_span,
1081                 bounds_span,
1082                 where_span,
1083             })
1084             .emit_unless(delay);
1085         return Err(reported);
1086     }
1087
1088     Ok(())
1089 }
1090
1091 #[instrument(level = "debug", skip(infcx))]
1092 fn extract_spans_for_error_reporting<'tcx>(
1093     infcx: &infer::InferCtxt<'tcx>,
1094     terr: TypeError<'_>,
1095     cause: &ObligationCause<'tcx>,
1096     impl_m: &ty::AssocItem,
1097     trait_m: &ty::AssocItem,
1098 ) -> (Span, Option<Span>) {
1099     let tcx = infcx.tcx;
1100     let mut impl_args = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
1101         ImplItemKind::Fn(ref sig, _) => {
1102             sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1103         }
1104         _ => bug!("{:?} is not a method", impl_m),
1105     };
1106     let trait_args =
1107         trait_m.def_id.as_local().map(|def_id| match tcx.hir().expect_trait_item(def_id).kind {
1108             TraitItemKind::Fn(ref sig, _) => {
1109                 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1110             }
1111             _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
1112         });
1113
1114     match terr {
1115         TypeError::ArgumentMutability(i) => {
1116             (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1117         }
1118         TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1119             (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1120         }
1121         _ => (cause.span(), tcx.hir().span_if_local(trait_m.def_id)),
1122     }
1123 }
1124
1125 fn compare_self_type<'tcx>(
1126     tcx: TyCtxt<'tcx>,
1127     impl_m: &ty::AssocItem,
1128     impl_m_span: Span,
1129     trait_m: &ty::AssocItem,
1130     impl_trait_ref: ty::TraitRef<'tcx>,
1131 ) -> Result<(), ErrorGuaranteed> {
1132     // Try to give more informative error messages about self typing
1133     // mismatches.  Note that any mismatch will also be detected
1134     // below, where we construct a canonical function type that
1135     // includes the self parameter as a normal parameter.  It's just
1136     // that the error messages you get out of this code are a bit more
1137     // inscrutable, particularly for cases where one method has no
1138     // self.
1139
1140     let self_string = |method: &ty::AssocItem| {
1141         let untransformed_self_ty = match method.container {
1142             ty::ImplContainer => impl_trait_ref.self_ty(),
1143             ty::TraitContainer => tcx.types.self_param,
1144         };
1145         let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
1146         let param_env = ty::ParamEnv::reveal_all();
1147
1148         let infcx = tcx.infer_ctxt().build();
1149         let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1150         let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
1151         match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
1152             ExplicitSelf::ByValue => "self".to_owned(),
1153             ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
1154             ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
1155             _ => format!("self: {self_arg_ty}"),
1156         }
1157     };
1158
1159     match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
1160         (false, false) | (true, true) => {}
1161
1162         (false, true) => {
1163             let self_descr = self_string(impl_m);
1164             let mut err = struct_span_err!(
1165                 tcx.sess,
1166                 impl_m_span,
1167                 E0185,
1168                 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1169                 trait_m.name,
1170                 self_descr
1171             );
1172             err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
1173             if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1174                 err.span_label(span, format!("trait method declared without `{self_descr}`"));
1175             } else {
1176                 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1177             }
1178             let reported = err.emit();
1179             return Err(reported);
1180         }
1181
1182         (true, false) => {
1183             let self_descr = self_string(trait_m);
1184             let mut err = struct_span_err!(
1185                 tcx.sess,
1186                 impl_m_span,
1187                 E0186,
1188                 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1189                 trait_m.name,
1190                 self_descr
1191             );
1192             err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
1193             if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1194                 err.span_label(span, format!("`{self_descr}` used in trait"));
1195             } else {
1196                 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1197             }
1198             let reported = err.emit();
1199             return Err(reported);
1200         }
1201     }
1202
1203     Ok(())
1204 }
1205
1206 /// Checks that the number of generics on a given assoc item in a trait impl is the same
1207 /// as the number of generics on the respective assoc item in the trait definition.
1208 ///
1209 /// For example this code emits the errors in the following code:
1210 /// ```
1211 /// trait Trait {
1212 ///     fn foo();
1213 ///     type Assoc<T>;
1214 /// }
1215 ///
1216 /// impl Trait for () {
1217 ///     fn foo<T>() {}
1218 ///     //~^ error
1219 ///     type Assoc = u32;
1220 ///     //~^ error
1221 /// }
1222 /// ```
1223 ///
1224 /// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
1225 /// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
1226 /// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
1227 fn compare_number_of_generics<'tcx>(
1228     tcx: TyCtxt<'tcx>,
1229     impl_: &ty::AssocItem,
1230     trait_: &ty::AssocItem,
1231     trait_span: Option<Span>,
1232     delay: bool,
1233 ) -> Result<(), ErrorGuaranteed> {
1234     let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1235     let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1236
1237     // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
1238     // in `compare_generic_param_kinds` which will give a nicer error message than something like:
1239     // "expected 1 type parameter, found 0 type parameters"
1240     if (trait_own_counts.types + trait_own_counts.consts)
1241         == (impl_own_counts.types + impl_own_counts.consts)
1242     {
1243         return Ok(());
1244     }
1245
1246     let matchings = [
1247         ("type", trait_own_counts.types, impl_own_counts.types),
1248         ("const", trait_own_counts.consts, impl_own_counts.consts),
1249     ];
1250
1251     let item_kind = assoc_item_kind_str(impl_);
1252
1253     let mut err_occurred = None;
1254     for (kind, trait_count, impl_count) in matchings {
1255         if impl_count != trait_count {
1256             let arg_spans = |kind: ty::AssocKind, generics: &hir::Generics<'_>| {
1257                 let mut spans = generics
1258                     .params
1259                     .iter()
1260                     .filter(|p| match p.kind {
1261                         hir::GenericParamKind::Lifetime {
1262                             kind: hir::LifetimeParamKind::Elided,
1263                         } => {
1264                             // A fn can have an arbitrary number of extra elided lifetimes for the
1265                             // same signature.
1266                             !matches!(kind, ty::AssocKind::Fn)
1267                         }
1268                         _ => true,
1269                     })
1270                     .map(|p| p.span)
1271                     .collect::<Vec<Span>>();
1272                 if spans.is_empty() {
1273                     spans = vec![generics.span]
1274                 }
1275                 spans
1276             };
1277             let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1278                 let trait_item = tcx.hir().expect_trait_item(def_id);
1279                 let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics);
1280                 let impl_trait_spans: Vec<Span> = trait_item
1281                     .generics
1282                     .params
1283                     .iter()
1284                     .filter_map(|p| match p.kind {
1285                         GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1286                         _ => None,
1287                     })
1288                     .collect();
1289                 (Some(arg_spans), impl_trait_spans)
1290             } else {
1291                 (trait_span.map(|s| vec![s]), vec![])
1292             };
1293
1294             let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local());
1295             let impl_item_impl_trait_spans: Vec<Span> = impl_item
1296                 .generics
1297                 .params
1298                 .iter()
1299                 .filter_map(|p| match p.kind {
1300                     GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1301                     _ => None,
1302                 })
1303                 .collect();
1304             let spans = arg_spans(impl_.kind, impl_item.generics);
1305             let span = spans.first().copied();
1306
1307             let mut err = tcx.sess.struct_span_err_with_code(
1308                 spans,
1309                 &format!(
1310                     "{} `{}` has {} {kind} parameter{} but its trait \
1311                      declaration has {} {kind} parameter{}",
1312                     item_kind,
1313                     trait_.name,
1314                     impl_count,
1315                     pluralize!(impl_count),
1316                     trait_count,
1317                     pluralize!(trait_count),
1318                     kind = kind,
1319                 ),
1320                 DiagnosticId::Error("E0049".into()),
1321             );
1322
1323             let mut suffix = None;
1324
1325             if let Some(spans) = trait_spans {
1326                 let mut spans = spans.iter();
1327                 if let Some(span) = spans.next() {
1328                     err.span_label(
1329                         *span,
1330                         format!(
1331                             "expected {} {} parameter{}",
1332                             trait_count,
1333                             kind,
1334                             pluralize!(trait_count),
1335                         ),
1336                     );
1337                 }
1338                 for span in spans {
1339                     err.span_label(*span, "");
1340                 }
1341             } else {
1342                 suffix = Some(format!(", expected {trait_count}"));
1343             }
1344
1345             if let Some(span) = span {
1346                 err.span_label(
1347                     span,
1348                     format!(
1349                         "found {} {} parameter{}{}",
1350                         impl_count,
1351                         kind,
1352                         pluralize!(impl_count),
1353                         suffix.unwrap_or_else(String::new),
1354                     ),
1355                 );
1356             }
1357
1358             for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1359                 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1360             }
1361
1362             let reported = err.emit_unless(delay);
1363             err_occurred = Some(reported);
1364         }
1365     }
1366
1367     if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1368 }
1369
1370 fn compare_number_of_method_arguments<'tcx>(
1371     tcx: TyCtxt<'tcx>,
1372     impl_m: &ty::AssocItem,
1373     impl_m_span: Span,
1374     trait_m: &ty::AssocItem,
1375     trait_item_span: Option<Span>,
1376 ) -> Result<(), ErrorGuaranteed> {
1377     let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1378     let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1379     let trait_number_args = trait_m_fty.inputs().skip_binder().len();
1380     let impl_number_args = impl_m_fty.inputs().skip_binder().len();
1381     if trait_number_args != impl_number_args {
1382         let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
1383             match tcx.hir().expect_trait_item(def_id).kind {
1384                 TraitItemKind::Fn(ref trait_m_sig, _) => {
1385                     let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
1386                     if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
1387                         Some(if pos == 0 {
1388                             arg.span
1389                         } else {
1390                             arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1391                         })
1392                     } else {
1393                         trait_item_span
1394                     }
1395                 }
1396                 _ => bug!("{:?} is not a method", impl_m),
1397             }
1398         } else {
1399             trait_item_span
1400         };
1401         let impl_span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
1402             ImplItemKind::Fn(ref impl_m_sig, _) => {
1403                 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
1404                 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
1405                     if pos == 0 {
1406                         arg.span
1407                     } else {
1408                         arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1409                     }
1410                 } else {
1411                     impl_m_span
1412                 }
1413             }
1414             _ => bug!("{:?} is not a method", impl_m),
1415         };
1416         let mut err = struct_span_err!(
1417             tcx.sess,
1418             impl_span,
1419             E0050,
1420             "method `{}` has {} but the declaration in trait `{}` has {}",
1421             trait_m.name,
1422             potentially_plural_count(impl_number_args, "parameter"),
1423             tcx.def_path_str(trait_m.def_id),
1424             trait_number_args
1425         );
1426         if let Some(trait_span) = trait_span {
1427             err.span_label(
1428                 trait_span,
1429                 format!(
1430                     "trait requires {}",
1431                     potentially_plural_count(trait_number_args, "parameter")
1432                 ),
1433             );
1434         } else {
1435             err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1436         }
1437         err.span_label(
1438             impl_span,
1439             format!(
1440                 "expected {}, found {}",
1441                 potentially_plural_count(trait_number_args, "parameter"),
1442                 impl_number_args
1443             ),
1444         );
1445         let reported = err.emit();
1446         return Err(reported);
1447     }
1448
1449     Ok(())
1450 }
1451
1452 fn compare_synthetic_generics<'tcx>(
1453     tcx: TyCtxt<'tcx>,
1454     impl_m: &ty::AssocItem,
1455     trait_m: &ty::AssocItem,
1456 ) -> Result<(), ErrorGuaranteed> {
1457     // FIXME(chrisvittal) Clean up this function, list of FIXME items:
1458     //     1. Better messages for the span labels
1459     //     2. Explanation as to what is going on
1460     // If we get here, we already have the same number of generics, so the zip will
1461     // be okay.
1462     let mut error_found = None;
1463     let impl_m_generics = tcx.generics_of(impl_m.def_id);
1464     let trait_m_generics = tcx.generics_of(trait_m.def_id);
1465     let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
1466         GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1467         GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1468     });
1469     let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
1470         GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1471         GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1472     });
1473     for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1474         iter::zip(impl_m_type_params, trait_m_type_params)
1475     {
1476         if impl_synthetic != trait_synthetic {
1477             let impl_def_id = impl_def_id.expect_local();
1478             let impl_span = tcx.def_span(impl_def_id);
1479             let trait_span = tcx.def_span(trait_def_id);
1480             let mut err = struct_span_err!(
1481                 tcx.sess,
1482                 impl_span,
1483                 E0643,
1484                 "method `{}` has incompatible signature for trait",
1485                 trait_m.name
1486             );
1487             err.span_label(trait_span, "declaration in trait here");
1488             match (impl_synthetic, trait_synthetic) {
1489                 // The case where the impl method uses `impl Trait` but the trait method uses
1490                 // explicit generics
1491                 (true, false) => {
1492                     err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1493                     (|| {
1494                         // try taking the name from the trait impl
1495                         // FIXME: this is obviously suboptimal since the name can already be used
1496                         // as another generic argument
1497                         let new_name = tcx.opt_item_name(trait_def_id)?;
1498                         let trait_m = trait_m.def_id.as_local()?;
1499                         let trait_m = tcx.hir().expect_trait_item(trait_m);
1500
1501                         let impl_m = impl_m.def_id.as_local()?;
1502                         let impl_m = tcx.hir().expect_impl_item(impl_m);
1503
1504                         // in case there are no generics, take the spot between the function name
1505                         // and the opening paren of the argument list
1506                         let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1507                         // in case there are generics, just replace them
1508                         let generics_span =
1509                             impl_m.generics.span.substitute_dummy(new_generics_span);
1510                         // replace with the generics from the trait
1511                         let new_generics =
1512                             tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1513
1514                         err.multipart_suggestion(
1515                             "try changing the `impl Trait` argument to a generic parameter",
1516                             vec![
1517                                 // replace `impl Trait` with `T`
1518                                 (impl_span, new_name.to_string()),
1519                                 // replace impl method generics with trait method generics
1520                                 // This isn't quite right, as users might have changed the names
1521                                 // of the generics, but it works for the common case
1522                                 (generics_span, new_generics),
1523                             ],
1524                             Applicability::MaybeIncorrect,
1525                         );
1526                         Some(())
1527                     })();
1528                 }
1529                 // The case where the trait method uses `impl Trait`, but the impl method uses
1530                 // explicit generics.
1531                 (false, true) => {
1532                     err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1533                     (|| {
1534                         let impl_m = impl_m.def_id.as_local()?;
1535                         let impl_m = tcx.hir().expect_impl_item(impl_m);
1536                         let input_tys = match impl_m.kind {
1537                             hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
1538                             _ => unreachable!(),
1539                         };
1540                         struct Visitor(Option<Span>, hir::def_id::LocalDefId);
1541                         impl<'v> intravisit::Visitor<'v> for Visitor {
1542                             fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
1543                                 intravisit::walk_ty(self, ty);
1544                                 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
1545                                     ty.kind
1546                                     && let Res::Def(DefKind::TyParam, def_id) = path.res
1547                                     && def_id == self.1.to_def_id()
1548                                 {
1549                                     self.0 = Some(ty.span);
1550                                 }
1551                             }
1552                         }
1553                         let mut visitor = Visitor(None, impl_def_id);
1554                         for ty in input_tys {
1555                             intravisit::Visitor::visit_ty(&mut visitor, ty);
1556                         }
1557                         let span = visitor.0?;
1558
1559                         let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
1560                         let bounds = bounds.first()?.span().to(bounds.last()?.span());
1561                         let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
1562
1563                         err.multipart_suggestion(
1564                             "try removing the generic parameter and using `impl Trait` instead",
1565                             vec![
1566                                 // delete generic parameters
1567                                 (impl_m.generics.span, String::new()),
1568                                 // replace param usage with `impl Trait`
1569                                 (span, format!("impl {bounds}")),
1570                             ],
1571                             Applicability::MaybeIncorrect,
1572                         );
1573                         Some(())
1574                     })();
1575                 }
1576                 _ => unreachable!(),
1577             }
1578             let reported = err.emit();
1579             error_found = Some(reported);
1580         }
1581     }
1582     if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
1583 }
1584
1585 /// Checks that all parameters in the generics of a given assoc item in a trait impl have
1586 /// the same kind as the respective generic parameter in the trait def.
1587 ///
1588 /// For example all 4 errors in the following code are emitted here:
1589 /// ```
1590 /// trait Foo {
1591 ///     fn foo<const N: u8>();
1592 ///     type bar<const N: u8>;
1593 ///     fn baz<const N: u32>();
1594 ///     type blah<T>;
1595 /// }
1596 ///
1597 /// impl Foo for () {
1598 ///     fn foo<const N: u64>() {}
1599 ///     //~^ error
1600 ///     type bar<const N: u64> {}
1601 ///     //~^ error
1602 ///     fn baz<T>() {}
1603 ///     //~^ error
1604 ///     type blah<const N: i64> = u32;
1605 ///     //~^ error
1606 /// }
1607 /// ```
1608 ///
1609 /// This function does not handle lifetime parameters
1610 fn compare_generic_param_kinds<'tcx>(
1611     tcx: TyCtxt<'tcx>,
1612     impl_item: &ty::AssocItem,
1613     trait_item: &ty::AssocItem,
1614     delay: bool,
1615 ) -> Result<(), ErrorGuaranteed> {
1616     assert_eq!(impl_item.kind, trait_item.kind);
1617
1618     let ty_const_params_of = |def_id| {
1619         tcx.generics_of(def_id).params.iter().filter(|param| {
1620             matches!(
1621                 param.kind,
1622                 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1623             )
1624         })
1625     };
1626
1627     for (param_impl, param_trait) in
1628         iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1629     {
1630         use GenericParamDefKind::*;
1631         if match (&param_impl.kind, &param_trait.kind) {
1632             (Const { .. }, Const { .. })
1633                 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1634             {
1635                 true
1636             }
1637             (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1638             // this is exhaustive so that anyone adding new generic param kinds knows
1639             // to make sure this error is reported for them.
1640             (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1641             (Lifetime { .. }, _) | (_, Lifetime { .. }) => unreachable!(),
1642         } {
1643             let param_impl_span = tcx.def_span(param_impl.def_id);
1644             let param_trait_span = tcx.def_span(param_trait.def_id);
1645
1646             let mut err = struct_span_err!(
1647                 tcx.sess,
1648                 param_impl_span,
1649                 E0053,
1650                 "{} `{}` has an incompatible generic parameter for trait `{}`",
1651                 assoc_item_kind_str(&impl_item),
1652                 trait_item.name,
1653                 &tcx.def_path_str(tcx.parent(trait_item.def_id))
1654             );
1655
1656             let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
1657                 Const { .. } => {
1658                     format!("{} const parameter of type `{}`", prefix, tcx.type_of(param.def_id))
1659                 }
1660                 Type { .. } => format!("{} type parameter", prefix),
1661                 Lifetime { .. } => unreachable!(),
1662             };
1663
1664             let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
1665             err.span_label(trait_header_span, "");
1666             err.span_label(param_trait_span, make_param_message("expected", param_trait));
1667
1668             let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1669             err.span_label(impl_header_span, "");
1670             err.span_label(param_impl_span, make_param_message("found", param_impl));
1671
1672             let reported = err.emit_unless(delay);
1673             return Err(reported);
1674         }
1675     }
1676
1677     Ok(())
1678 }
1679
1680 /// Use `tcx.compare_impl_const` instead
1681 pub(super) fn compare_impl_const_raw(
1682     tcx: TyCtxt<'_>,
1683     (impl_const_item_def, trait_const_item_def): (LocalDefId, DefId),
1684 ) -> Result<(), ErrorGuaranteed> {
1685     let impl_const_item = tcx.associated_item(impl_const_item_def);
1686     let trait_const_item = tcx.associated_item(trait_const_item_def);
1687     let impl_trait_ref = tcx.impl_trait_ref(impl_const_item.container_id(tcx)).unwrap();
1688     debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
1689
1690     let impl_c_span = tcx.def_span(impl_const_item_def.to_def_id());
1691
1692     let infcx = tcx.infer_ctxt().build();
1693     let param_env = tcx.param_env(impl_const_item_def.to_def_id());
1694     let ocx = ObligationCtxt::new(&infcx);
1695
1696     // The below is for the most part highly similar to the procedure
1697     // for methods above. It is simpler in many respects, especially
1698     // because we shouldn't really have to deal with lifetimes or
1699     // predicates. In fact some of this should probably be put into
1700     // shared functions because of DRY violations...
1701     let trait_to_impl_substs = impl_trait_ref.substs;
1702
1703     // Create a parameter environment that represents the implementation's
1704     // method.
1705     let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_const_item_def);
1706
1707     // Compute placeholder form of impl and trait const tys.
1708     let impl_ty = tcx.type_of(impl_const_item_def.to_def_id());
1709     let trait_ty = tcx.bound_type_of(trait_const_item_def).subst(tcx, trait_to_impl_substs);
1710     let mut cause = ObligationCause::new(
1711         impl_c_span,
1712         impl_c_hir_id,
1713         ObligationCauseCode::CompareImplItemObligation {
1714             impl_item_def_id: impl_const_item_def,
1715             trait_item_def_id: trait_const_item_def,
1716             kind: impl_const_item.kind,
1717         },
1718     );
1719
1720     // There is no "body" here, so just pass dummy id.
1721     let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
1722
1723     debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1724
1725     let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
1726
1727     debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1728
1729     let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
1730
1731     if let Err(terr) = err {
1732         debug!(
1733             "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1734             impl_ty, trait_ty
1735         );
1736
1737         // Locate the Span containing just the type of the offending impl
1738         match tcx.hir().expect_impl_item(impl_const_item_def).kind {
1739             ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
1740             _ => bug!("{:?} is not a impl const", impl_const_item),
1741         }
1742
1743         let mut diag = struct_span_err!(
1744             tcx.sess,
1745             cause.span,
1746             E0326,
1747             "implemented const `{}` has an incompatible type for trait",
1748             trait_const_item.name
1749         );
1750
1751         let trait_c_span = trait_const_item_def.as_local().map(|trait_c_def_id| {
1752             // Add a label to the Span containing just the type of the const
1753             match tcx.hir().expect_trait_item(trait_c_def_id).kind {
1754                 TraitItemKind::Const(ref ty, _) => ty.span,
1755                 _ => bug!("{:?} is not a trait const", trait_const_item),
1756             }
1757         });
1758
1759         infcx.err_ctxt().note_type_err(
1760             &mut diag,
1761             &cause,
1762             trait_c_span.map(|span| (span, "type in trait".to_owned())),
1763             Some(infer::ValuePairs::Terms(ExpectedFound {
1764                 expected: trait_ty.into(),
1765                 found: impl_ty.into(),
1766             })),
1767             terr,
1768             false,
1769             false,
1770         );
1771         return Err(diag.emit());
1772     };
1773
1774     // Check that all obligations are satisfied by the implementation's
1775     // version.
1776     let errors = ocx.select_all_or_error();
1777     if !errors.is_empty() {
1778         return Err(infcx.err_ctxt().report_fulfillment_errors(&errors, None));
1779     }
1780
1781     let outlives_environment = OutlivesEnvironment::new(param_env);
1782     infcx
1783         .err_ctxt()
1784         .check_region_obligations_and_report_errors(impl_const_item_def, &outlives_environment)?;
1785     Ok(())
1786 }
1787
1788 pub(super) fn compare_impl_ty<'tcx>(
1789     tcx: TyCtxt<'tcx>,
1790     impl_ty: &ty::AssocItem,
1791     impl_ty_span: Span,
1792     trait_ty: &ty::AssocItem,
1793     impl_trait_ref: ty::TraitRef<'tcx>,
1794     trait_item_span: Option<Span>,
1795 ) {
1796     debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1797
1798     let _: Result<(), ErrorGuaranteed> = (|| {
1799         compare_number_of_generics(tcx, impl_ty, trait_ty, trait_item_span, false)?;
1800
1801         compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
1802
1803         let sp = tcx.def_span(impl_ty.def_id);
1804         compare_type_predicate_entailment(tcx, impl_ty, sp, trait_ty, impl_trait_ref)?;
1805
1806         check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
1807     })();
1808 }
1809
1810 /// The equivalent of [compare_method_predicate_entailment], but for associated types
1811 /// instead of associated functions.
1812 fn compare_type_predicate_entailment<'tcx>(
1813     tcx: TyCtxt<'tcx>,
1814     impl_ty: &ty::AssocItem,
1815     impl_ty_span: Span,
1816     trait_ty: &ty::AssocItem,
1817     impl_trait_ref: ty::TraitRef<'tcx>,
1818 ) -> Result<(), ErrorGuaranteed> {
1819     let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1820     let trait_to_impl_substs =
1821         impl_substs.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.substs);
1822
1823     let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1824     let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1825
1826     check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
1827
1828     let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1829
1830     if impl_ty_own_bounds.is_empty() {
1831         // Nothing to check.
1832         return Ok(());
1833     }
1834
1835     // This `HirId` should be used for the `body_id` field on each
1836     // `ObligationCause` (and the `FnCtxt`). This is what
1837     // `regionck_item` expects.
1838     let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1839     debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1840
1841     // The predicates declared by the impl definition, the trait and the
1842     // associated type in the trait are assumed.
1843     let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1844     let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1845     hybrid_preds
1846         .predicates
1847         .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1848
1849     debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1850
1851     let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1852     let param_env = ty::ParamEnv::new(
1853         tcx.intern_predicates(&hybrid_preds.predicates),
1854         Reveal::UserFacing,
1855         hir::Constness::NotConst,
1856     );
1857     let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
1858     let infcx = tcx.infer_ctxt().build();
1859     let ocx = ObligationCtxt::new(&infcx);
1860
1861     debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1862
1863     assert_eq!(impl_ty_own_bounds.predicates.len(), impl_ty_own_bounds.spans.len());
1864     for (span, predicate) in std::iter::zip(impl_ty_own_bounds.spans, impl_ty_own_bounds.predicates)
1865     {
1866         let cause = ObligationCause::misc(span, impl_ty_hir_id);
1867         let predicate = ocx.normalize(&cause, param_env, predicate);
1868
1869         let cause = ObligationCause::new(
1870             span,
1871             impl_ty_hir_id,
1872             ObligationCauseCode::CompareImplItemObligation {
1873                 impl_item_def_id: impl_ty.def_id.expect_local(),
1874                 trait_item_def_id: trait_ty.def_id,
1875                 kind: impl_ty.kind,
1876             },
1877         );
1878         ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
1879     }
1880
1881     // Check that all obligations are satisfied by the implementation's
1882     // version.
1883     let errors = ocx.select_all_or_error();
1884     if !errors.is_empty() {
1885         let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
1886         return Err(reported);
1887     }
1888
1889     // Finally, resolve all regions. This catches wily misuses of
1890     // lifetime parameters.
1891     let outlives_environment = OutlivesEnvironment::new(param_env);
1892     infcx.err_ctxt().check_region_obligations_and_report_errors(
1893         impl_ty.def_id.expect_local(),
1894         &outlives_environment,
1895     )?;
1896
1897     Ok(())
1898 }
1899
1900 /// Validate that `ProjectionCandidate`s created for this associated type will
1901 /// be valid.
1902 ///
1903 /// Usually given
1904 ///
1905 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1906 ///
1907 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1908 /// impl is well-formed we have to prove `S: Copy`.
1909 ///
1910 /// For default associated types the normalization is not possible (the value
1911 /// from the impl could be overridden). We also can't normalize generic
1912 /// associated types (yet) because they contain bound parameters.
1913 #[instrument(level = "debug", skip(tcx))]
1914 pub(super) fn check_type_bounds<'tcx>(
1915     tcx: TyCtxt<'tcx>,
1916     trait_ty: &ty::AssocItem,
1917     impl_ty: &ty::AssocItem,
1918     impl_ty_span: Span,
1919     impl_trait_ref: ty::TraitRef<'tcx>,
1920 ) -> Result<(), ErrorGuaranteed> {
1921     // Given
1922     //
1923     // impl<A, B> Foo<u32> for (A, B) {
1924     //     type Bar<C> =...
1925     // }
1926     //
1927     // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1928     // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1929     // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1930     //    the *trait* with the generic associated type parameters (as bound vars).
1931     //
1932     // A note regarding the use of bound vars here:
1933     // Imagine as an example
1934     // ```
1935     // trait Family {
1936     //     type Member<C: Eq>;
1937     // }
1938     //
1939     // impl Family for VecFamily {
1940     //     type Member<C: Eq> = i32;
1941     // }
1942     // ```
1943     // Here, we would generate
1944     // ```notrust
1945     // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1946     // ```
1947     // when we really would like to generate
1948     // ```notrust
1949     // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1950     // ```
1951     // But, this is probably fine, because although the first clause can be used with types C that
1952     // do not implement Eq, for it to cause some kind of problem, there would have to be a
1953     // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1954     // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1955     // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1956     // the trait (notably, that X: Eq and T: Family).
1957     let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1958     let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1959     if let Some(def_id) = defs.parent {
1960         let parent_defs = tcx.generics_of(def_id);
1961         InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1962             tcx.mk_param_from_def(param)
1963         });
1964     }
1965     let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1966         smallvec::SmallVec::with_capacity(defs.count());
1967     InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1968         GenericParamDefKind::Type { .. } => {
1969             let kind = ty::BoundTyKind::Param(param.name);
1970             let bound_var = ty::BoundVariableKind::Ty(kind);
1971             bound_vars.push(bound_var);
1972             tcx.mk_ty(ty::Bound(
1973                 ty::INNERMOST,
1974                 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1975             ))
1976             .into()
1977         }
1978         GenericParamDefKind::Lifetime => {
1979             let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1980             let bound_var = ty::BoundVariableKind::Region(kind);
1981             bound_vars.push(bound_var);
1982             tcx.mk_region(ty::ReLateBound(
1983                 ty::INNERMOST,
1984                 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1985             ))
1986             .into()
1987         }
1988         GenericParamDefKind::Const { .. } => {
1989             let bound_var = ty::BoundVariableKind::Const;
1990             bound_vars.push(bound_var);
1991             tcx.mk_const(
1992                 ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_usize(bound_vars.len() - 1)),
1993                 tcx.type_of(param.def_id),
1994             )
1995             .into()
1996         }
1997     });
1998     let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
1999     let impl_ty_substs = tcx.intern_substs(&substs);
2000     let container_id = impl_ty.container_id(tcx);
2001
2002     let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
2003     let impl_ty_value = tcx.type_of(impl_ty.def_id);
2004
2005     let param_env = tcx.param_env(impl_ty.def_id);
2006
2007     // When checking something like
2008     //
2009     // trait X { type Y: PartialEq<<Self as X>::Y> }
2010     // impl X for T { default type Y = S; }
2011     //
2012     // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
2013     // we want <T as X>::Y to normalize to S. This is valid because we are
2014     // checking the default value specifically here. Add this equality to the
2015     // ParamEnv for normalization specifically.
2016     let normalize_param_env = {
2017         let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
2018         match impl_ty_value.kind() {
2019             ty::Alias(ty::Projection, proj)
2020                 if proj.def_id == trait_ty.def_id && proj.substs == rebased_substs =>
2021             {
2022                 // Don't include this predicate if the projected type is
2023                 // exactly the same as the projection. This can occur in
2024                 // (somewhat dubious) code like this:
2025                 //
2026                 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
2027             }
2028             _ => predicates.push(
2029                 ty::Binder::bind_with_vars(
2030                     ty::ProjectionPredicate {
2031                         projection_ty: tcx.mk_alias_ty(trait_ty.def_id, rebased_substs),
2032                         term: impl_ty_value.into(),
2033                     },
2034                     bound_vars,
2035                 )
2036                 .to_predicate(tcx),
2037             ),
2038         };
2039         ty::ParamEnv::new(
2040             tcx.intern_predicates(&predicates),
2041             Reveal::UserFacing,
2042             param_env.constness(),
2043         )
2044     };
2045     debug!(?normalize_param_env);
2046
2047     let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
2048     let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
2049     let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
2050
2051     let infcx = tcx.infer_ctxt().build();
2052     let ocx = ObligationCtxt::new(&infcx);
2053
2054     let assumed_wf_types =
2055         ocx.assumed_wf_types(param_env, impl_ty_span, impl_ty.def_id.expect_local());
2056
2057     let normalize_cause = ObligationCause::new(
2058         impl_ty_span,
2059         impl_ty_hir_id,
2060         ObligationCauseCode::CheckAssociatedTypeBounds {
2061             impl_item_def_id: impl_ty.def_id.expect_local(),
2062             trait_item_def_id: trait_ty.def_id,
2063         },
2064     );
2065     let mk_cause = |span: Span| {
2066         let code = if span.is_dummy() {
2067             traits::ItemObligation(trait_ty.def_id)
2068         } else {
2069             traits::BindingObligation(trait_ty.def_id, span)
2070         };
2071         ObligationCause::new(impl_ty_span, impl_ty_hir_id, code)
2072     };
2073
2074     let obligations = tcx
2075         .bound_explicit_item_bounds(trait_ty.def_id)
2076         .subst_iter_copied(tcx, rebased_substs)
2077         .map(|(concrete_ty_bound, span)| {
2078             debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
2079             traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2080         })
2081         .collect();
2082     debug!("check_type_bounds: item_bounds={:?}", obligations);
2083
2084     for mut obligation in util::elaborate_obligations(tcx, obligations) {
2085         let normalized_predicate =
2086             ocx.normalize(&normalize_cause, normalize_param_env, obligation.predicate);
2087         debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
2088         obligation.predicate = normalized_predicate;
2089
2090         ocx.register_obligation(obligation);
2091     }
2092     // Check that all obligations are satisfied by the implementation's
2093     // version.
2094     let errors = ocx.select_all_or_error();
2095     if !errors.is_empty() {
2096         let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
2097         return Err(reported);
2098     }
2099
2100     // Finally, resolve all regions. This catches wily misuses of
2101     // lifetime parameters.
2102     let implied_bounds = infcx.implied_bounds_tys(param_env, impl_ty_hir_id, assumed_wf_types);
2103     let outlives_environment =
2104         OutlivesEnvironment::with_bounds(param_env, Some(&infcx), implied_bounds);
2105
2106     infcx.err_ctxt().check_region_obligations_and_report_errors(
2107         impl_ty.def_id.expect_local(),
2108         &outlives_environment,
2109     )?;
2110
2111     Ok(())
2112 }
2113
2114 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
2115     match impl_item.kind {
2116         ty::AssocKind::Const => "const",
2117         ty::AssocKind::Fn => "method",
2118         ty::AssocKind::Type => "type",
2119     }
2120 }