]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/compare_method.rs
`compare_predicate_entailment` move comment
[rust.git] / compiler / rustc_typeck / src / check / compare_method.rs
1 use super::potentially_plural_count;
2 use crate::check::regionck::OutlivesEnvironmentExt;
3 use crate::errors::LifetimesOrBoundsMismatchOnTrait;
4 use rustc_data_structures::fx::FxHashSet;
5 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, ErrorGuaranteed};
6 use rustc_hir as hir;
7 use rustc_hir::def::{DefKind, Res};
8 use rustc_hir::intravisit;
9 use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind};
10 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
11 use rustc_infer::infer::{self, TyCtxtInferExt};
12 use rustc_infer::traits::util;
13 use rustc_middle::ty::error::{ExpectedFound, TypeError};
14 use rustc_middle::ty::subst::{InternalSubsts, Subst};
15 use rustc_middle::ty::util::ExplicitSelf;
16 use rustc_middle::ty::{self, DefIdTree};
17 use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt};
18 use rustc_span::Span;
19 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
20 use rustc_trait_selection::traits::{
21     self, ObligationCause, ObligationCauseCode, ObligationCtxt, Reveal,
22 };
23 use std::iter;
24
25 /// Checks that a method from an impl conforms to the signature of
26 /// the same method as declared in the trait.
27 ///
28 /// # Parameters
29 ///
30 /// - `impl_m`: type of the method we are checking
31 /// - `impl_m_span`: span to use for reporting errors
32 /// - `trait_m`: the method in the trait
33 /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
34 pub(crate) fn compare_impl_method<'tcx>(
35     tcx: TyCtxt<'tcx>,
36     impl_m: &ty::AssocItem,
37     trait_m: &ty::AssocItem,
38     impl_trait_ref: ty::TraitRef<'tcx>,
39     trait_item_span: Option<Span>,
40 ) {
41     debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref);
42
43     let impl_m_span = tcx.def_span(impl_m.def_id);
44
45     if let Err(_) = compare_self_type(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref) {
46         return;
47     }
48
49     if let Err(_) = compare_number_of_generics(tcx, impl_m, impl_m_span, trait_m, trait_item_span) {
50         return;
51     }
52
53     if let Err(_) = compare_generic_param_kinds(tcx, impl_m, trait_m) {
54         return;
55     }
56
57     if let Err(_) =
58         compare_number_of_method_arguments(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
59     {
60         return;
61     }
62
63     if let Err(_) = compare_synthetic_generics(tcx, impl_m, trait_m) {
64         return;
65     }
66
67     if let Err(_) = compare_predicate_entailment(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
68     {
69         return;
70     }
71 }
72
73 /// This function is best explained by example. Consider a trait:
74 ///
75 ///     trait Trait<'t, T> {
76 ///         // `trait_m`
77 ///         fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
78 ///     }
79 ///
80 /// And an impl:
81 ///
82 ///     impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
83 ///          // `impl_m`
84 ///          fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo;
85 ///     }
86 ///
87 /// We wish to decide if those two method types are compatible.
88 /// For this we have to show that, assuming the bounds of the impl hold, the
89 /// bounds of `trait_m` imply the bounds of `impl_m`.
90 ///
91 /// We start out with `trait_to_impl_substs`, that maps the trait
92 /// type parameters to impl type parameters. This is taken from the
93 /// impl trait reference:
94 ///
95 ///     trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
96 ///
97 /// We create a mapping `dummy_substs` that maps from the impl type
98 /// parameters to fresh types and regions. For type parameters,
99 /// this is the identity transform, but we could as well use any
100 /// placeholder types. For regions, we convert from bound to free
101 /// regions (Note: but only early-bound regions, i.e., those
102 /// declared on the impl or used in type parameter bounds).
103 ///
104 ///     impl_to_placeholder_substs = {'i => 'i0, U => U0, N => N0 }
105 ///
106 /// Now we can apply `placeholder_substs` to the type of the impl method
107 /// to yield a new function type in terms of our fresh, placeholder
108 /// types:
109 ///
110 ///     <'b> fn(t: &'i0 U0, m: &'b) -> Foo
111 ///
112 /// We now want to extract and substitute the type of the *trait*
113 /// method and compare it. To do so, we must create a compound
114 /// substitution by combining `trait_to_impl_substs` and
115 /// `impl_to_placeholder_substs`, and also adding a mapping for the method
116 /// type parameters. We extend the mapping to also include
117 /// the method parameters.
118 ///
119 ///     trait_to_placeholder_substs = { T => &'i0 U0, Self => Foo, M => N0 }
120 ///
121 /// Applying this to the trait method type yields:
122 ///
123 ///     <'a> fn(t: &'i0 U0, m: &'a) -> Foo
124 ///
125 /// This type is also the same but the name of the bound region (`'a`
126 /// vs `'b`).  However, the normal subtyping rules on fn types handle
127 /// this kind of equivalency just fine.
128 ///
129 /// We now use these substitutions to ensure that all declared bounds are
130 /// satisfied by the implementation's method.
131 ///
132 /// We do this by creating a parameter environment which contains a
133 /// substitution corresponding to `impl_to_placeholder_substs`. We then build
134 /// `trait_to_placeholder_substs` and use it to convert the predicates contained
135 /// in the `trait_m` generics to the placeholder form.
136 ///
137 /// Finally we register each of these predicates as an obligation and check that
138 /// they hold.
139 fn compare_predicate_entailment<'tcx>(
140     tcx: TyCtxt<'tcx>,
141     impl_m: &ty::AssocItem,
142     impl_m_span: Span,
143     trait_m: &ty::AssocItem,
144     impl_trait_ref: ty::TraitRef<'tcx>,
145 ) -> Result<(), ErrorGuaranteed> {
146     let trait_to_impl_substs = impl_trait_ref.substs;
147
148     // This node-id should be used for the `body_id` field on each
149     // `ObligationCause` (and the `FnCtxt`).
150     //
151     // FIXME(@lcnr): remove that after removing `cause.body_id` from
152     // obligations.
153     let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
154     // We sometimes modify the span further down.
155     let mut cause = ObligationCause::new(
156         impl_m_span,
157         impl_m_hir_id,
158         ObligationCauseCode::CompareImplItemObligation {
159             impl_item_def_id: impl_m.def_id.expect_local(),
160             trait_item_def_id: trait_m.def_id,
161             kind: impl_m.kind,
162         },
163     );
164
165     // Create mapping from impl to placeholder.
166     let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
167
168     // Create mapping from trait to placeholder.
169     let trait_to_placeholder_substs =
170         impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
171     debug!("compare_impl_method: trait_to_placeholder_substs={:?}", trait_to_placeholder_substs);
172
173     let impl_m_generics = tcx.generics_of(impl_m.def_id);
174     let trait_m_generics = tcx.generics_of(trait_m.def_id);
175     let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
176     let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
177
178     // Check region bounds.
179     check_region_bounds_on_impl_item(tcx, impl_m, trait_m, &trait_m_generics, &impl_m_generics)?;
180
181     // Create obligations for each predicate declared by the impl
182     // definition in the context of the trait's parameter
183     // environment. We can't just use `impl_env.caller_bounds`,
184     // however, because we want to replace all late-bound regions with
185     // region variables.
186     let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
187     let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
188
189     debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
190
191     // This is the only tricky bit of the new way we check implementation methods
192     // We need to build a set of predicates where only the method-level bounds
193     // are from the trait and we assume all other bounds from the implementation
194     // to be previously satisfied.
195     //
196     // We then register the obligations from the impl_m and check to see
197     // if all constraints hold.
198     hybrid_preds
199         .predicates
200         .extend(trait_m_predicates.instantiate_own(tcx, trait_to_placeholder_substs).predicates);
201
202     // Construct trait parameter environment and then shift it into the placeholder viewpoint.
203     // The key step here is to update the caller_bounds's predicates to be
204     // the new hybrid bounds we computed.
205     let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
206     let param_env = ty::ParamEnv::new(
207         tcx.intern_predicates(&hybrid_preds.predicates),
208         Reveal::UserFacing,
209         hir::Constness::NotConst,
210     );
211     let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
212
213     tcx.infer_ctxt().enter(|ref infcx| {
214         let ocx = ObligationCtxt::new(infcx);
215
216         debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds());
217
218         let mut selcx = traits::SelectionContext::new(&infcx);
219         let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs);
220         for (predicate, span) in iter::zip(impl_m_own_bounds.predicates, impl_m_own_bounds.spans) {
221             let normalize_cause = traits::ObligationCause::misc(span, impl_m_hir_id);
222             let traits::Normalized { value: predicate, obligations } =
223                 traits::normalize(&mut selcx, param_env, normalize_cause, predicate);
224
225             ocx.register_obligations(obligations);
226             let cause = ObligationCause::new(
227                 span,
228                 impl_m_hir_id,
229                 ObligationCauseCode::CompareImplItemObligation {
230                     impl_item_def_id: impl_m.def_id.expect_local(),
231                     trait_item_def_id: trait_m.def_id,
232                     kind: impl_m.kind,
233                 },
234             );
235             ocx.register_obligation(traits::Obligation::new(cause, param_env, predicate));
236         }
237
238         // We now need to check that the signature of the impl method is
239         // compatible with that of the trait method. We do this by
240         // checking that `impl_fty <: trait_fty`.
241         //
242         // FIXME. Unfortunately, this doesn't quite work right now because
243         // associated type normalization is not integrated into subtype
244         // checks. For the comparison to be valid, we need to
245         // normalize the associated types in the impl/trait methods
246         // first. However, because function types bind regions, just
247         // calling `normalize_associated_types_in` would have no effect on
248         // any associated types appearing in the fn arguments or return
249         // type.
250
251         // Compute placeholder form of impl and trait method tys.
252         let tcx = infcx.tcx;
253
254         let mut wf_tys = FxHashSet::default();
255
256         let impl_sig = infcx.replace_bound_vars_with_fresh_vars(
257             impl_m_span,
258             infer::HigherRankedType,
259             tcx.fn_sig(impl_m.def_id),
260         );
261
262         let norm_cause = ObligationCause::misc(impl_m_span, impl_m_hir_id);
263         let impl_sig = ocx.normalize(norm_cause.clone(), param_env, impl_sig);
264         let impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(impl_sig));
265         debug!("compare_impl_method: impl_fty={:?}", impl_fty);
266
267         let trait_sig = tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs);
268         let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
269         // Next, add all inputs and output as well-formed tys. Importantly,
270         // we have to do this before normalization, since the normalized ty may
271         // not contain the input parameters. See issue #87748.
272         wf_tys.extend(trait_sig.inputs_and_output.iter());
273         let trait_sig = ocx.normalize(norm_cause, param_env, trait_sig);
274         // We also have to add the normalized trait signature
275         // as we don't normalize during implied bounds computation.
276         wf_tys.extend(trait_sig.inputs_and_output.iter());
277         let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));
278
279         debug!("compare_impl_method: trait_fty={:?}", trait_fty);
280
281         // FIXME: We'd want to keep more accurate spans than "the method signature" when
282         // processing the comparison between the trait and impl fn, but we sadly lose them
283         // and point at the whole signature when a trait bound or specific input or output
284         // type would be more appropriate. In other places we have a `Vec<Span>`
285         // corresponding to their `Vec<Predicate>`, but we don't have that here.
286         // Fixing this would improve the output of test `issue-83765.rs`.
287         let sub_result = infcx
288             .at(&cause, param_env)
289             .sup(trait_fty, impl_fty)
290             .map(|infer_ok| ocx.register_infer_ok_obligations(infer_ok));
291
292         if let Err(terr) = sub_result {
293             debug!("sub_types failed: impl ty {:?}, trait ty {:?}", impl_fty, trait_fty);
294
295             let (impl_err_span, trait_err_span) =
296                 extract_spans_for_error_reporting(&infcx, terr, &cause, impl_m, trait_m);
297
298             cause.span = impl_err_span;
299
300             let mut diag = struct_span_err!(
301                 tcx.sess,
302                 cause.span(),
303                 E0053,
304                 "method `{}` has an incompatible type for trait",
305                 trait_m.name
306             );
307             match &terr {
308                 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
309                     if trait_m.fn_has_self_parameter =>
310                 {
311                     let ty = trait_sig.inputs()[0];
312                     let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty())
313                     {
314                         ExplicitSelf::ByValue => "self".to_owned(),
315                         ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
316                         ExplicitSelf::ByReference(_, hir::Mutability::Mut) => {
317                             "&mut self".to_owned()
318                         }
319                         _ => format!("self: {ty}"),
320                     };
321
322                     // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
323                     // span points only at the type `Box<Self`>, but we want to cover the whole
324                     // argument pattern and type.
325                     let span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
326                         ImplItemKind::Fn(ref sig, body) => tcx
327                             .hir()
328                             .body_param_names(body)
329                             .zip(sig.decl.inputs.iter())
330                             .map(|(param, ty)| param.span.to(ty.span))
331                             .next()
332                             .unwrap_or(impl_err_span),
333                         _ => bug!("{:?} is not a method", impl_m),
334                     };
335
336                     diag.span_suggestion(
337                         span,
338                         "change the self-receiver type to match the trait",
339                         sugg,
340                         Applicability::MachineApplicable,
341                     );
342                 }
343                 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
344                     if trait_sig.inputs().len() == *i {
345                         // Suggestion to change output type. We do not suggest in `async` functions
346                         // to avoid complex logic or incorrect output.
347                         match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
348                             ImplItemKind::Fn(ref sig, _)
349                                 if sig.header.asyncness == hir::IsAsync::NotAsync =>
350                             {
351                                 let msg = "change the output type to match the trait";
352                                 let ap = Applicability::MachineApplicable;
353                                 match sig.decl.output {
354                                     hir::FnRetTy::DefaultReturn(sp) => {
355                                         let sugg = format!("-> {} ", trait_sig.output());
356                                         diag.span_suggestion_verbose(sp, msg, sugg, ap);
357                                     }
358                                     hir::FnRetTy::Return(hir_ty) => {
359                                         let sugg = trait_sig.output();
360                                         diag.span_suggestion(hir_ty.span, msg, sugg, ap);
361                                     }
362                                 };
363                             }
364                             _ => {}
365                         };
366                     } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
367                         diag.span_suggestion(
368                             impl_err_span,
369                             "change the parameter type to match the trait",
370                             trait_ty,
371                             Applicability::MachineApplicable,
372                         );
373                     }
374                 }
375                 _ => {}
376             }
377
378             infcx.note_type_err(
379                 &mut diag,
380                 &cause,
381                 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
382                 Some(infer::ValuePairs::Terms(ExpectedFound {
383                     expected: trait_fty.into(),
384                     found: impl_fty.into(),
385                 })),
386                 terr,
387                 false,
388                 false,
389             );
390
391             return Err(diag.emit());
392         }
393
394         // Check that all obligations are satisfied by the implementation's
395         // version.
396         let errors = ocx.select_all_or_error();
397         if !errors.is_empty() {
398             let reported = infcx.report_fulfillment_errors(&errors, None, false);
399             return Err(reported);
400         }
401
402         // Finally, resolve all regions. This catches wily misuses of
403         // lifetime parameters.
404         let mut outlives_environment = OutlivesEnvironment::new(param_env);
405         outlives_environment.add_implied_bounds(infcx, wf_tys, impl_m_hir_id);
406         infcx.check_region_obligations_and_report_errors(
407             impl_m.def_id.expect_local(),
408             &outlives_environment,
409         );
410
411         Ok(())
412     })
413 }
414
415 fn check_region_bounds_on_impl_item<'tcx>(
416     tcx: TyCtxt<'tcx>,
417     impl_m: &ty::AssocItem,
418     trait_m: &ty::AssocItem,
419     trait_generics: &ty::Generics,
420     impl_generics: &ty::Generics,
421 ) -> Result<(), ErrorGuaranteed> {
422     let trait_params = trait_generics.own_counts().lifetimes;
423     let impl_params = impl_generics.own_counts().lifetimes;
424
425     debug!(
426         "check_region_bounds_on_impl_item: \
427             trait_generics={:?} \
428             impl_generics={:?}",
429         trait_generics, impl_generics
430     );
431
432     // Must have same number of early-bound lifetime parameters.
433     // Unfortunately, if the user screws up the bounds, then this
434     // will change classification between early and late.  E.g.,
435     // if in trait we have `<'a,'b:'a>`, and in impl we just have
436     // `<'a,'b>`, then we have 2 early-bound lifetime parameters
437     // in trait but 0 in the impl. But if we report "expected 2
438     // but found 0" it's confusing, because it looks like there
439     // are zero. Since I don't quite know how to phrase things at
440     // the moment, give a kind of vague error message.
441     if trait_params != impl_params {
442         let span = tcx
443             .hir()
444             .get_generics(impl_m.def_id.expect_local())
445             .expect("expected impl item to have generics or else we can't compare them")
446             .span;
447         let generics_span = if let Some(local_def_id) = trait_m.def_id.as_local() {
448             Some(
449                 tcx.hir()
450                     .get_generics(local_def_id)
451                     .expect("expected trait item to have generics or else we can't compare them")
452                     .span,
453             )
454         } else {
455             None
456         };
457
458         let reported = tcx.sess.emit_err(LifetimesOrBoundsMismatchOnTrait {
459             span,
460             item_kind: assoc_item_kind_str(impl_m),
461             ident: impl_m.ident(tcx),
462             generics_span,
463         });
464         return Err(reported);
465     }
466
467     Ok(())
468 }
469
470 #[instrument(level = "debug", skip(infcx))]
471 fn extract_spans_for_error_reporting<'a, 'tcx>(
472     infcx: &infer::InferCtxt<'a, 'tcx>,
473     terr: TypeError<'_>,
474     cause: &ObligationCause<'tcx>,
475     impl_m: &ty::AssocItem,
476     trait_m: &ty::AssocItem,
477 ) -> (Span, Option<Span>) {
478     let tcx = infcx.tcx;
479     let mut impl_args = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
480         ImplItemKind::Fn(ref sig, _) => {
481             sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
482         }
483         _ => bug!("{:?} is not a method", impl_m),
484     };
485     let trait_args =
486         trait_m.def_id.as_local().map(|def_id| match tcx.hir().expect_trait_item(def_id).kind {
487             TraitItemKind::Fn(ref sig, _) => {
488                 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
489             }
490             _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
491         });
492
493     match terr {
494         TypeError::ArgumentMutability(i) => {
495             (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
496         }
497         TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
498             (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
499         }
500         _ => (cause.span(), tcx.hir().span_if_local(trait_m.def_id)),
501     }
502 }
503
504 fn compare_self_type<'tcx>(
505     tcx: TyCtxt<'tcx>,
506     impl_m: &ty::AssocItem,
507     impl_m_span: Span,
508     trait_m: &ty::AssocItem,
509     impl_trait_ref: ty::TraitRef<'tcx>,
510 ) -> Result<(), ErrorGuaranteed> {
511     // Try to give more informative error messages about self typing
512     // mismatches.  Note that any mismatch will also be detected
513     // below, where we construct a canonical function type that
514     // includes the self parameter as a normal parameter.  It's just
515     // that the error messages you get out of this code are a bit more
516     // inscrutable, particularly for cases where one method has no
517     // self.
518
519     let self_string = |method: &ty::AssocItem| {
520         let untransformed_self_ty = match method.container {
521             ty::ImplContainer => impl_trait_ref.self_ty(),
522             ty::TraitContainer => tcx.types.self_param,
523         };
524         let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
525         let param_env = ty::ParamEnv::reveal_all();
526
527         tcx.infer_ctxt().enter(|infcx| {
528             let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
529             let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
530             match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
531                 ExplicitSelf::ByValue => "self".to_owned(),
532                 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
533                 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
534                 _ => format!("self: {self_arg_ty}"),
535             }
536         })
537     };
538
539     match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
540         (false, false) | (true, true) => {}
541
542         (false, true) => {
543             let self_descr = self_string(impl_m);
544             let mut err = struct_span_err!(
545                 tcx.sess,
546                 impl_m_span,
547                 E0185,
548                 "method `{}` has a `{}` declaration in the impl, but not in the trait",
549                 trait_m.name,
550                 self_descr
551             );
552             err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
553             if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
554                 err.span_label(span, format!("trait method declared without `{self_descr}`"));
555             } else {
556                 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
557             }
558             let reported = err.emit();
559             return Err(reported);
560         }
561
562         (true, false) => {
563             let self_descr = self_string(trait_m);
564             let mut err = struct_span_err!(
565                 tcx.sess,
566                 impl_m_span,
567                 E0186,
568                 "method `{}` has a `{}` declaration in the trait, but not in the impl",
569                 trait_m.name,
570                 self_descr
571             );
572             err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
573             if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
574                 err.span_label(span, format!("`{self_descr}` used in trait"));
575             } else {
576                 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
577             }
578             let reported = err.emit();
579             return Err(reported);
580         }
581     }
582
583     Ok(())
584 }
585
586 /// Checks that the number of generics on a given assoc item in a trait impl is the same
587 /// as the number of generics on the respective assoc item in the trait definition.
588 ///
589 /// For example this code emits the errors in the following code:
590 /// ```
591 /// trait Trait {
592 ///     fn foo();
593 ///     type Assoc<T>;
594 /// }
595 ///
596 /// impl Trait for () {
597 ///     fn foo<T>() {}
598 ///     //~^ error
599 ///     type Assoc = u32;
600 ///     //~^ error
601 /// }
602 /// ```
603 ///
604 /// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
605 /// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
606 /// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
607 fn compare_number_of_generics<'tcx>(
608     tcx: TyCtxt<'tcx>,
609     impl_: &ty::AssocItem,
610     _impl_span: Span,
611     trait_: &ty::AssocItem,
612     trait_span: Option<Span>,
613 ) -> Result<(), ErrorGuaranteed> {
614     let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
615     let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
616
617     // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
618     // in `compare_generic_param_kinds` which will give a nicer error message than something like:
619     // "expected 1 type parameter, found 0 type parameters"
620     if (trait_own_counts.types + trait_own_counts.consts)
621         == (impl_own_counts.types + impl_own_counts.consts)
622     {
623         return Ok(());
624     }
625
626     let matchings = [
627         ("type", trait_own_counts.types, impl_own_counts.types),
628         ("const", trait_own_counts.consts, impl_own_counts.consts),
629     ];
630
631     let item_kind = assoc_item_kind_str(impl_);
632
633     let mut err_occurred = None;
634     for (kind, trait_count, impl_count) in matchings {
635         if impl_count != trait_count {
636             let arg_spans = |kind: ty::AssocKind, generics: &hir::Generics<'_>| {
637                 let mut spans = generics
638                     .params
639                     .iter()
640                     .filter(|p| match p.kind {
641                         hir::GenericParamKind::Lifetime {
642                             kind: hir::LifetimeParamKind::Elided,
643                         } => {
644                             // A fn can have an arbitrary number of extra elided lifetimes for the
645                             // same signature.
646                             !matches!(kind, ty::AssocKind::Fn)
647                         }
648                         _ => true,
649                     })
650                     .map(|p| p.span)
651                     .collect::<Vec<Span>>();
652                 if spans.is_empty() {
653                     spans = vec![generics.span]
654                 }
655                 spans
656             };
657             let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
658                 let trait_item = tcx.hir().expect_trait_item(def_id);
659                 let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics);
660                 let impl_trait_spans: Vec<Span> = trait_item
661                     .generics
662                     .params
663                     .iter()
664                     .filter_map(|p| match p.kind {
665                         GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
666                         _ => None,
667                     })
668                     .collect();
669                 (Some(arg_spans), impl_trait_spans)
670             } else {
671                 (trait_span.map(|s| vec![s]), vec![])
672             };
673
674             let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local());
675             let impl_item_impl_trait_spans: Vec<Span> = impl_item
676                 .generics
677                 .params
678                 .iter()
679                 .filter_map(|p| match p.kind {
680                     GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
681                     _ => None,
682                 })
683                 .collect();
684             let spans = arg_spans(impl_.kind, impl_item.generics);
685             let span = spans.first().copied();
686
687             let mut err = tcx.sess.struct_span_err_with_code(
688                 spans,
689                 &format!(
690                     "{} `{}` has {} {kind} parameter{} but its trait \
691                      declaration has {} {kind} parameter{}",
692                     item_kind,
693                     trait_.name,
694                     impl_count,
695                     pluralize!(impl_count),
696                     trait_count,
697                     pluralize!(trait_count),
698                     kind = kind,
699                 ),
700                 DiagnosticId::Error("E0049".into()),
701             );
702
703             let mut suffix = None;
704
705             if let Some(spans) = trait_spans {
706                 let mut spans = spans.iter();
707                 if let Some(span) = spans.next() {
708                     err.span_label(
709                         *span,
710                         format!(
711                             "expected {} {} parameter{}",
712                             trait_count,
713                             kind,
714                             pluralize!(trait_count),
715                         ),
716                     );
717                 }
718                 for span in spans {
719                     err.span_label(*span, "");
720                 }
721             } else {
722                 suffix = Some(format!(", expected {trait_count}"));
723             }
724
725             if let Some(span) = span {
726                 err.span_label(
727                     span,
728                     format!(
729                         "found {} {} parameter{}{}",
730                         impl_count,
731                         kind,
732                         pluralize!(impl_count),
733                         suffix.unwrap_or_else(String::new),
734                     ),
735                 );
736             }
737
738             for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
739                 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
740             }
741
742             let reported = err.emit();
743             err_occurred = Some(reported);
744         }
745     }
746
747     if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
748 }
749
750 fn compare_number_of_method_arguments<'tcx>(
751     tcx: TyCtxt<'tcx>,
752     impl_m: &ty::AssocItem,
753     impl_m_span: Span,
754     trait_m: &ty::AssocItem,
755     trait_item_span: Option<Span>,
756 ) -> Result<(), ErrorGuaranteed> {
757     let impl_m_fty = tcx.fn_sig(impl_m.def_id);
758     let trait_m_fty = tcx.fn_sig(trait_m.def_id);
759     let trait_number_args = trait_m_fty.inputs().skip_binder().len();
760     let impl_number_args = impl_m_fty.inputs().skip_binder().len();
761     if trait_number_args != impl_number_args {
762         let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
763             match tcx.hir().expect_trait_item(def_id).kind {
764                 TraitItemKind::Fn(ref trait_m_sig, _) => {
765                     let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
766                     if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
767                         Some(if pos == 0 {
768                             arg.span
769                         } else {
770                             arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
771                         })
772                     } else {
773                         trait_item_span
774                     }
775                 }
776                 _ => bug!("{:?} is not a method", impl_m),
777             }
778         } else {
779             trait_item_span
780         };
781         let impl_span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
782             ImplItemKind::Fn(ref impl_m_sig, _) => {
783                 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
784                 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
785                     if pos == 0 {
786                         arg.span
787                     } else {
788                         arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
789                     }
790                 } else {
791                     impl_m_span
792                 }
793             }
794             _ => bug!("{:?} is not a method", impl_m),
795         };
796         let mut err = struct_span_err!(
797             tcx.sess,
798             impl_span,
799             E0050,
800             "method `{}` has {} but the declaration in trait `{}` has {}",
801             trait_m.name,
802             potentially_plural_count(impl_number_args, "parameter"),
803             tcx.def_path_str(trait_m.def_id),
804             trait_number_args
805         );
806         if let Some(trait_span) = trait_span {
807             err.span_label(
808                 trait_span,
809                 format!(
810                     "trait requires {}",
811                     potentially_plural_count(trait_number_args, "parameter")
812                 ),
813             );
814         } else {
815             err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
816         }
817         err.span_label(
818             impl_span,
819             format!(
820                 "expected {}, found {}",
821                 potentially_plural_count(trait_number_args, "parameter"),
822                 impl_number_args
823             ),
824         );
825         let reported = err.emit();
826         return Err(reported);
827     }
828
829     Ok(())
830 }
831
832 fn compare_synthetic_generics<'tcx>(
833     tcx: TyCtxt<'tcx>,
834     impl_m: &ty::AssocItem,
835     trait_m: &ty::AssocItem,
836 ) -> Result<(), ErrorGuaranteed> {
837     // FIXME(chrisvittal) Clean up this function, list of FIXME items:
838     //     1. Better messages for the span labels
839     //     2. Explanation as to what is going on
840     // If we get here, we already have the same number of generics, so the zip will
841     // be okay.
842     let mut error_found = None;
843     let impl_m_generics = tcx.generics_of(impl_m.def_id);
844     let trait_m_generics = tcx.generics_of(trait_m.def_id);
845     let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
846         GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
847         GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
848     });
849     let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
850         GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
851         GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
852     });
853     for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
854         iter::zip(impl_m_type_params, trait_m_type_params)
855     {
856         if impl_synthetic != trait_synthetic {
857             let impl_def_id = impl_def_id.expect_local();
858             let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_def_id);
859             let impl_span = tcx.hir().span(impl_hir_id);
860             let trait_span = tcx.def_span(trait_def_id);
861             let mut err = struct_span_err!(
862                 tcx.sess,
863                 impl_span,
864                 E0643,
865                 "method `{}` has incompatible signature for trait",
866                 trait_m.name
867             );
868             err.span_label(trait_span, "declaration in trait here");
869             match (impl_synthetic, trait_synthetic) {
870                 // The case where the impl method uses `impl Trait` but the trait method uses
871                 // explicit generics
872                 (true, false) => {
873                     err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
874                     (|| {
875                         // try taking the name from the trait impl
876                         // FIXME: this is obviously suboptimal since the name can already be used
877                         // as another generic argument
878                         let new_name = tcx.sess.source_map().span_to_snippet(trait_span).ok()?;
879                         let trait_m = trait_m.def_id.as_local()?;
880                         let trait_m = tcx.hir().trait_item(hir::TraitItemId { def_id: trait_m });
881
882                         let impl_m = impl_m.def_id.as_local()?;
883                         let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
884
885                         // in case there are no generics, take the spot between the function name
886                         // and the opening paren of the argument list
887                         let new_generics_span =
888                             tcx.sess.source_map().generate_fn_name_span(impl_span)?.shrink_to_hi();
889                         // in case there are generics, just replace them
890                         let generics_span =
891                             impl_m.generics.span.substitute_dummy(new_generics_span);
892                         // replace with the generics from the trait
893                         let new_generics =
894                             tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
895
896                         err.multipart_suggestion(
897                             "try changing the `impl Trait` argument to a generic parameter",
898                             vec![
899                                 // replace `impl Trait` with `T`
900                                 (impl_span, new_name),
901                                 // replace impl method generics with trait method generics
902                                 // This isn't quite right, as users might have changed the names
903                                 // of the generics, but it works for the common case
904                                 (generics_span, new_generics),
905                             ],
906                             Applicability::MaybeIncorrect,
907                         );
908                         Some(())
909                     })();
910                 }
911                 // The case where the trait method uses `impl Trait`, but the impl method uses
912                 // explicit generics.
913                 (false, true) => {
914                     err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
915                     (|| {
916                         let impl_m = impl_m.def_id.as_local()?;
917                         let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
918                         let input_tys = match impl_m.kind {
919                             hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
920                             _ => unreachable!(),
921                         };
922                         struct Visitor(Option<Span>, hir::def_id::LocalDefId);
923                         impl<'v> intravisit::Visitor<'v> for Visitor {
924                             fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
925                                 intravisit::walk_ty(self, ty);
926                                 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
927                                     ty.kind
928                                     && let Res::Def(DefKind::TyParam, def_id) = path.res
929                                     && def_id == self.1.to_def_id()
930                                 {
931                                     self.0 = Some(ty.span);
932                                 }
933                             }
934                         }
935                         let mut visitor = Visitor(None, impl_def_id);
936                         for ty in input_tys {
937                             intravisit::Visitor::visit_ty(&mut visitor, ty);
938                         }
939                         let span = visitor.0?;
940
941                         let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
942                         let bounds = bounds.first()?.span().to(bounds.last()?.span());
943                         let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
944
945                         err.multipart_suggestion(
946                             "try removing the generic parameter and using `impl Trait` instead",
947                             vec![
948                                 // delete generic parameters
949                                 (impl_m.generics.span, String::new()),
950                                 // replace param usage with `impl Trait`
951                                 (span, format!("impl {bounds}")),
952                             ],
953                             Applicability::MaybeIncorrect,
954                         );
955                         Some(())
956                     })();
957                 }
958                 _ => unreachable!(),
959             }
960             let reported = err.emit();
961             error_found = Some(reported);
962         }
963     }
964     if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
965 }
966
967 /// Checks that all parameters in the generics of a given assoc item in a trait impl have
968 /// the same kind as the respective generic parameter in the trait def.
969 ///
970 /// For example all 4 errors in the following code are emitted here:
971 /// ```
972 /// trait Foo {
973 ///     fn foo<const N: u8>();
974 ///     type bar<const N: u8>;
975 ///     fn baz<const N: u32>();
976 ///     type blah<T>;
977 /// }
978 ///
979 /// impl Foo for () {
980 ///     fn foo<const N: u64>() {}
981 ///     //~^ error
982 ///     type bar<const N: u64> {}
983 ///     //~^ error
984 ///     fn baz<T>() {}
985 ///     //~^ error
986 ///     type blah<const N: i64> = u32;
987 ///     //~^ error
988 /// }
989 /// ```
990 ///
991 /// This function does not handle lifetime parameters
992 fn compare_generic_param_kinds<'tcx>(
993     tcx: TyCtxt<'tcx>,
994     impl_item: &ty::AssocItem,
995     trait_item: &ty::AssocItem,
996 ) -> Result<(), ErrorGuaranteed> {
997     assert_eq!(impl_item.kind, trait_item.kind);
998
999     let ty_const_params_of = |def_id| {
1000         tcx.generics_of(def_id).params.iter().filter(|param| {
1001             matches!(
1002                 param.kind,
1003                 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1004             )
1005         })
1006     };
1007
1008     for (param_impl, param_trait) in
1009         iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1010     {
1011         use GenericParamDefKind::*;
1012         if match (&param_impl.kind, &param_trait.kind) {
1013             (Const { .. }, Const { .. })
1014                 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1015             {
1016                 true
1017             }
1018             (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1019             // this is exhaustive so that anyone adding new generic param kinds knows
1020             // to make sure this error is reported for them.
1021             (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1022             (Lifetime { .. }, _) | (_, Lifetime { .. }) => unreachable!(),
1023         } {
1024             let param_impl_span = tcx.def_span(param_impl.def_id);
1025             let param_trait_span = tcx.def_span(param_trait.def_id);
1026
1027             let mut err = struct_span_err!(
1028                 tcx.sess,
1029                 param_impl_span,
1030                 E0053,
1031                 "{} `{}` has an incompatible generic parameter for trait `{}`",
1032                 assoc_item_kind_str(&impl_item),
1033                 trait_item.name,
1034                 &tcx.def_path_str(tcx.parent(trait_item.def_id))
1035             );
1036
1037             let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
1038                 Const { .. } => {
1039                     format!("{} const parameter of type `{}`", prefix, tcx.type_of(param.def_id))
1040                 }
1041                 Type { .. } => format!("{} type parameter", prefix),
1042                 Lifetime { .. } => unreachable!(),
1043             };
1044
1045             let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
1046             err.span_label(trait_header_span, "");
1047             err.span_label(param_trait_span, make_param_message("expected", param_trait));
1048
1049             let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1050             err.span_label(impl_header_span, "");
1051             err.span_label(param_impl_span, make_param_message("found", param_impl));
1052
1053             let reported = err.emit();
1054             return Err(reported);
1055         }
1056     }
1057
1058     Ok(())
1059 }
1060
1061 pub(crate) fn compare_const_impl<'tcx>(
1062     tcx: TyCtxt<'tcx>,
1063     impl_c: &ty::AssocItem,
1064     impl_c_span: Span,
1065     trait_c: &ty::AssocItem,
1066     impl_trait_ref: ty::TraitRef<'tcx>,
1067 ) {
1068     debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
1069
1070     tcx.infer_ctxt().enter(|infcx| {
1071         let param_env = tcx.param_env(impl_c.def_id);
1072         let ocx = ObligationCtxt::new(&infcx);
1073
1074         // The below is for the most part highly similar to the procedure
1075         // for methods above. It is simpler in many respects, especially
1076         // because we shouldn't really have to deal with lifetimes or
1077         // predicates. In fact some of this should probably be put into
1078         // shared functions because of DRY violations...
1079         let trait_to_impl_substs = impl_trait_ref.substs;
1080
1081         // Create a parameter environment that represents the implementation's
1082         // method.
1083         let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_c.def_id.expect_local());
1084
1085         // Compute placeholder form of impl and trait const tys.
1086         let impl_ty = tcx.type_of(impl_c.def_id);
1087         let trait_ty = tcx.bound_type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
1088         let mut cause = ObligationCause::new(
1089             impl_c_span,
1090             impl_c_hir_id,
1091             ObligationCauseCode::CompareImplItemObligation {
1092                 impl_item_def_id: impl_c.def_id.expect_local(),
1093                 trait_item_def_id: trait_c.def_id,
1094                 kind: impl_c.kind,
1095             },
1096         );
1097
1098         // There is no "body" here, so just pass dummy id.
1099         let impl_ty = ocx.normalize(cause.clone(), param_env, impl_ty);
1100
1101         debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1102
1103         let trait_ty = ocx.normalize(cause.clone(), param_env, trait_ty);
1104
1105         debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1106
1107         let err = infcx
1108             .at(&cause, param_env)
1109             .sup(trait_ty, impl_ty)
1110             .map(|ok| ocx.register_infer_ok_obligations(ok));
1111
1112         if let Err(terr) = err {
1113             debug!(
1114                 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1115                 impl_ty, trait_ty
1116             );
1117
1118             // Locate the Span containing just the type of the offending impl
1119             match tcx.hir().expect_impl_item(impl_c.def_id.expect_local()).kind {
1120                 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
1121                 _ => bug!("{:?} is not a impl const", impl_c),
1122             }
1123
1124             let mut diag = struct_span_err!(
1125                 tcx.sess,
1126                 cause.span,
1127                 E0326,
1128                 "implemented const `{}` has an incompatible type for trait",
1129                 trait_c.name
1130             );
1131
1132             let trait_c_span = trait_c.def_id.as_local().map(|trait_c_def_id| {
1133                 // Add a label to the Span containing just the type of the const
1134                 match tcx.hir().expect_trait_item(trait_c_def_id).kind {
1135                     TraitItemKind::Const(ref ty, _) => ty.span,
1136                     _ => bug!("{:?} is not a trait const", trait_c),
1137                 }
1138             });
1139
1140             infcx.note_type_err(
1141                 &mut diag,
1142                 &cause,
1143                 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1144                 Some(infer::ValuePairs::Terms(ExpectedFound {
1145                     expected: trait_ty.into(),
1146                     found: impl_ty.into(),
1147                 })),
1148                 terr,
1149                 false,
1150                 false,
1151             );
1152             diag.emit();
1153         }
1154
1155         // Check that all obligations are satisfied by the implementation's
1156         // version.
1157         let errors = ocx.select_all_or_error();
1158         if !errors.is_empty() {
1159             infcx.report_fulfillment_errors(&errors, None, false);
1160             return;
1161         }
1162
1163         let outlives_environment = OutlivesEnvironment::new(param_env);
1164         infcx.check_region_obligations_and_report_errors(
1165             impl_c.def_id.expect_local(),
1166             &outlives_environment,
1167         );
1168     });
1169 }
1170
1171 pub(crate) fn compare_ty_impl<'tcx>(
1172     tcx: TyCtxt<'tcx>,
1173     impl_ty: &ty::AssocItem,
1174     impl_ty_span: Span,
1175     trait_ty: &ty::AssocItem,
1176     impl_trait_ref: ty::TraitRef<'tcx>,
1177     trait_item_span: Option<Span>,
1178 ) {
1179     debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1180
1181     let _: Result<(), ErrorGuaranteed> = (|| {
1182         compare_number_of_generics(tcx, impl_ty, impl_ty_span, trait_ty, trait_item_span)?;
1183
1184         compare_generic_param_kinds(tcx, impl_ty, trait_ty)?;
1185
1186         let sp = tcx.def_span(impl_ty.def_id);
1187         compare_type_predicate_entailment(tcx, impl_ty, sp, trait_ty, impl_trait_ref)?;
1188
1189         check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
1190     })();
1191 }
1192
1193 /// The equivalent of [compare_predicate_entailment], but for associated types
1194 /// instead of associated functions.
1195 fn compare_type_predicate_entailment<'tcx>(
1196     tcx: TyCtxt<'tcx>,
1197     impl_ty: &ty::AssocItem,
1198     impl_ty_span: Span,
1199     trait_ty: &ty::AssocItem,
1200     impl_trait_ref: ty::TraitRef<'tcx>,
1201 ) -> Result<(), ErrorGuaranteed> {
1202     let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1203     let trait_to_impl_substs =
1204         impl_substs.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.substs);
1205
1206     let impl_ty_generics = tcx.generics_of(impl_ty.def_id);
1207     let trait_ty_generics = tcx.generics_of(trait_ty.def_id);
1208     let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1209     let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1210
1211     check_region_bounds_on_impl_item(
1212         tcx,
1213         impl_ty,
1214         trait_ty,
1215         &trait_ty_generics,
1216         &impl_ty_generics,
1217     )?;
1218
1219     let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1220
1221     if impl_ty_own_bounds.is_empty() {
1222         // Nothing to check.
1223         return Ok(());
1224     }
1225
1226     // This `HirId` should be used for the `body_id` field on each
1227     // `ObligationCause` (and the `FnCtxt`). This is what
1228     // `regionck_item` expects.
1229     let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1230     debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1231
1232     // The predicates declared by the impl definition, the trait and the
1233     // associated type in the trait are assumed.
1234     let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1235     let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1236     hybrid_preds
1237         .predicates
1238         .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1239
1240     debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1241
1242     let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1243     let param_env = ty::ParamEnv::new(
1244         tcx.intern_predicates(&hybrid_preds.predicates),
1245         Reveal::UserFacing,
1246         hir::Constness::NotConst,
1247     );
1248     let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
1249     tcx.infer_ctxt().enter(|infcx| {
1250         let ocx = ObligationCtxt::new(&infcx);
1251
1252         debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1253
1254         let mut selcx = traits::SelectionContext::new(&infcx);
1255
1256         assert_eq!(impl_ty_own_bounds.predicates.len(), impl_ty_own_bounds.spans.len());
1257         for (span, predicate) in
1258             std::iter::zip(impl_ty_own_bounds.spans, impl_ty_own_bounds.predicates)
1259         {
1260             let cause = ObligationCause::misc(span, impl_ty_hir_id);
1261             let traits::Normalized { value: predicate, obligations } =
1262                 traits::normalize(&mut selcx, param_env, cause, predicate);
1263
1264             let cause = ObligationCause::new(
1265                 span,
1266                 impl_ty_hir_id,
1267                 ObligationCauseCode::CompareImplItemObligation {
1268                     impl_item_def_id: impl_ty.def_id.expect_local(),
1269                     trait_item_def_id: trait_ty.def_id,
1270                     kind: impl_ty.kind,
1271                 },
1272             );
1273             ocx.register_obligations(obligations);
1274             ocx.register_obligation(traits::Obligation::new(cause, param_env, predicate));
1275         }
1276
1277         // Check that all obligations are satisfied by the implementation's
1278         // version.
1279         let errors = ocx.select_all_or_error();
1280         if !errors.is_empty() {
1281             let reported = infcx.report_fulfillment_errors(&errors, None, false);
1282             return Err(reported);
1283         }
1284
1285         // Finally, resolve all regions. This catches wily misuses of
1286         // lifetime parameters.
1287         let outlives_environment = OutlivesEnvironment::new(param_env);
1288         infcx.check_region_obligations_and_report_errors(
1289             impl_ty.def_id.expect_local(),
1290             &outlives_environment,
1291         );
1292
1293         Ok(())
1294     })
1295 }
1296
1297 /// Validate that `ProjectionCandidate`s created for this associated type will
1298 /// be valid.
1299 ///
1300 /// Usually given
1301 ///
1302 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1303 ///
1304 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1305 /// impl is well-formed we have to prove `S: Copy`.
1306 ///
1307 /// For default associated types the normalization is not possible (the value
1308 /// from the impl could be overridden). We also can't normalize generic
1309 /// associated types (yet) because they contain bound parameters.
1310 #[tracing::instrument(level = "debug", skip(tcx))]
1311 pub fn check_type_bounds<'tcx>(
1312     tcx: TyCtxt<'tcx>,
1313     trait_ty: &ty::AssocItem,
1314     impl_ty: &ty::AssocItem,
1315     impl_ty_span: Span,
1316     impl_trait_ref: ty::TraitRef<'tcx>,
1317 ) -> Result<(), ErrorGuaranteed> {
1318     // Given
1319     //
1320     // impl<A, B> Foo<u32> for (A, B) {
1321     //     type Bar<C> =...
1322     // }
1323     //
1324     // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1325     // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1326     // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1327     //    the *trait* with the generic associated type parameters (as bound vars).
1328     //
1329     // A note regarding the use of bound vars here:
1330     // Imagine as an example
1331     // ```
1332     // trait Family {
1333     //     type Member<C: Eq>;
1334     // }
1335     //
1336     // impl Family for VecFamily {
1337     //     type Member<C: Eq> = i32;
1338     // }
1339     // ```
1340     // Here, we would generate
1341     // ```notrust
1342     // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1343     // ```
1344     // when we really would like to generate
1345     // ```notrust
1346     // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1347     // ```
1348     // But, this is probably fine, because although the first clause can be used with types C that
1349     // do not implement Eq, for it to cause some kind of problem, there would have to be a
1350     // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1351     // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1352     // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1353     // the trait (notably, that X: Eq and T: Family).
1354     let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1355     let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1356     if let Some(def_id) = defs.parent {
1357         let parent_defs = tcx.generics_of(def_id);
1358         InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1359             tcx.mk_param_from_def(param)
1360         });
1361     }
1362     let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1363         smallvec::SmallVec::with_capacity(defs.count());
1364     InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1365         GenericParamDefKind::Type { .. } => {
1366             let kind = ty::BoundTyKind::Param(param.name);
1367             let bound_var = ty::BoundVariableKind::Ty(kind);
1368             bound_vars.push(bound_var);
1369             tcx.mk_ty(ty::Bound(
1370                 ty::INNERMOST,
1371                 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1372             ))
1373             .into()
1374         }
1375         GenericParamDefKind::Lifetime => {
1376             let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1377             let bound_var = ty::BoundVariableKind::Region(kind);
1378             bound_vars.push(bound_var);
1379             tcx.mk_region(ty::ReLateBound(
1380                 ty::INNERMOST,
1381                 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1382             ))
1383             .into()
1384         }
1385         GenericParamDefKind::Const { .. } => {
1386             let bound_var = ty::BoundVariableKind::Const;
1387             bound_vars.push(bound_var);
1388             tcx.mk_const(ty::ConstS {
1389                 ty: tcx.type_of(param.def_id),
1390                 kind: ty::ConstKind::Bound(
1391                     ty::INNERMOST,
1392                     ty::BoundVar::from_usize(bound_vars.len() - 1),
1393                 ),
1394             })
1395             .into()
1396         }
1397     });
1398     let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
1399     let impl_ty_substs = tcx.intern_substs(&substs);
1400     let container_id = impl_ty.container_id(tcx);
1401
1402     let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
1403     let impl_ty_value = tcx.type_of(impl_ty.def_id);
1404
1405     let param_env = tcx.param_env(impl_ty.def_id);
1406
1407     // When checking something like
1408     //
1409     // trait X { type Y: PartialEq<<Self as X>::Y> }
1410     // impl X for T { default type Y = S; }
1411     //
1412     // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
1413     // we want <T as X>::Y to normalize to S. This is valid because we are
1414     // checking the default value specifically here. Add this equality to the
1415     // ParamEnv for normalization specifically.
1416     let normalize_param_env = {
1417         let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
1418         match impl_ty_value.kind() {
1419             ty::Projection(proj)
1420                 if proj.item_def_id == trait_ty.def_id && proj.substs == rebased_substs =>
1421             {
1422                 // Don't include this predicate if the projected type is
1423                 // exactly the same as the projection. This can occur in
1424                 // (somewhat dubious) code like this:
1425                 //
1426                 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
1427             }
1428             _ => predicates.push(
1429                 ty::Binder::bind_with_vars(
1430                     ty::ProjectionPredicate {
1431                         projection_ty: ty::ProjectionTy {
1432                             item_def_id: trait_ty.def_id,
1433                             substs: rebased_substs,
1434                         },
1435                         term: impl_ty_value.into(),
1436                     },
1437                     bound_vars,
1438                 )
1439                 .to_predicate(tcx),
1440             ),
1441         };
1442         ty::ParamEnv::new(
1443             tcx.intern_predicates(&predicates),
1444             Reveal::UserFacing,
1445             param_env.constness(),
1446         )
1447     };
1448     debug!(?normalize_param_env);
1449
1450     let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1451     let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1452     let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
1453
1454     tcx.infer_ctxt().enter(move |infcx| {
1455         let ocx = ObligationCtxt::new(&infcx);
1456
1457         let assumed_wf_types = tcx.assumed_wf_types(impl_ty.def_id);
1458         let mut implied_bounds = FxHashSet::default();
1459         let cause = ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1460         for ty in assumed_wf_types {
1461             implied_bounds.insert(ty);
1462             let normalized = ocx.normalize(cause.clone(), param_env, ty);
1463             implied_bounds.insert(normalized);
1464         }
1465         let implied_bounds = implied_bounds;
1466
1467         let mut selcx = traits::SelectionContext::new(&infcx);
1468         let normalize_cause = ObligationCause::new(
1469             impl_ty_span,
1470             impl_ty_hir_id,
1471             ObligationCauseCode::CheckAssociatedTypeBounds {
1472                 impl_item_def_id: impl_ty.def_id.expect_local(),
1473                 trait_item_def_id: trait_ty.def_id,
1474             },
1475         );
1476         let mk_cause = |span: Span| {
1477             let code = if span.is_dummy() {
1478                 traits::MiscObligation
1479             } else {
1480                 traits::BindingObligation(trait_ty.def_id, span)
1481             };
1482             ObligationCause::new(impl_ty_span, impl_ty_hir_id, code)
1483         };
1484
1485         let obligations = tcx
1486             .bound_explicit_item_bounds(trait_ty.def_id)
1487             .transpose_iter()
1488             .map(|e| e.map_bound(|e| *e).transpose_tuple2())
1489             .map(|(bound, span)| {
1490                 debug!(?bound);
1491                 // this is where opaque type is found
1492                 let concrete_ty_bound = bound.subst(tcx, rebased_substs);
1493                 debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
1494
1495                 traits::Obligation::new(mk_cause(span.0), param_env, concrete_ty_bound)
1496             })
1497             .collect();
1498         debug!("check_type_bounds: item_bounds={:?}", obligations);
1499
1500         for mut obligation in util::elaborate_obligations(tcx, obligations) {
1501             let traits::Normalized { value: normalized_predicate, obligations } = traits::normalize(
1502                 &mut selcx,
1503                 normalize_param_env,
1504                 normalize_cause.clone(),
1505                 obligation.predicate,
1506             );
1507             debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
1508             obligation.predicate = normalized_predicate;
1509
1510             ocx.register_obligations(obligations);
1511             ocx.register_obligation(obligation);
1512         }
1513         // Check that all obligations are satisfied by the implementation's
1514         // version.
1515         let errors = ocx.select_all_or_error();
1516         if !errors.is_empty() {
1517             let reported = infcx.report_fulfillment_errors(&errors, None, false);
1518             return Err(reported);
1519         }
1520
1521         // Finally, resolve all regions. This catches wily misuses of
1522         // lifetime parameters.
1523         let mut outlives_environment = OutlivesEnvironment::new(param_env);
1524         outlives_environment.add_implied_bounds(&infcx, implied_bounds, impl_ty_hir_id);
1525         infcx.check_region_obligations_and_report_errors(
1526             impl_ty.def_id.expect_local(),
1527             &outlives_environment,
1528         );
1529
1530         let constraints = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
1531         for (key, value) in constraints {
1532             infcx
1533                 .report_mismatched_types(
1534                     &ObligationCause::misc(
1535                         value.hidden_type.span,
1536                         tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local()),
1537                     ),
1538                     tcx.mk_opaque(key.def_id.to_def_id(), key.substs),
1539                     value.hidden_type.ty,
1540                     TypeError::Mismatch,
1541                 )
1542                 .emit();
1543         }
1544
1545         Ok(())
1546     })
1547 }
1548
1549 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
1550     match impl_item.kind {
1551         ty::AssocKind::Const => "const",
1552         ty::AssocKind::Fn => "method",
1553         ty::AssocKind::Type => "type",
1554     }
1555 }