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