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