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