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