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