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