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