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