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