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, FxIndexSet};
6 pluralize, struct_span_err, Applicability, DiagnosticId, ErrorGuaranteed, MultiSpan,
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::intravisit;
11 use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind};
12 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
13 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
14 use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt};
15 use rustc_infer::traits::util;
16 use rustc_middle::ty::error::{ExpectedFound, TypeError};
17 use rustc_middle::ty::util::ExplicitSelf;
18 use rustc_middle::ty::{
19 self, DefIdTree, InternalSubsts, Ty, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable,
21 use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt};
23 use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt;
24 use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _;
25 use rustc_trait_selection::traits::{
26 self, ObligationCause, ObligationCauseCode, ObligationCtxt, Reveal,
30 /// Checks that a method from an impl conforms to the signature of
31 /// the same method as declared in the trait.
35 /// - `impl_m`: type of the method we are checking
36 /// - `impl_m_span`: span to use for reporting errors
37 /// - `trait_m`: the method in the trait
38 /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
39 pub(super) fn compare_impl_method<'tcx>(
41 impl_m: &ty::AssocItem,
42 trait_m: &ty::AssocItem,
43 impl_trait_ref: ty::TraitRef<'tcx>,
44 trait_item_span: Option<Span>,
46 debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref);
48 let impl_m_span = tcx.def_span(impl_m.def_id);
50 if let Err(_) = compare_self_type(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref) {
54 if let Err(_) = compare_number_of_generics(tcx, impl_m, trait_m, trait_item_span, false) {
58 if let Err(_) = compare_generic_param_kinds(tcx, impl_m, trait_m, false) {
63 compare_number_of_method_arguments(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
68 if let Err(_) = compare_synthetic_generics(tcx, impl_m, trait_m) {
72 if let Err(_) = compare_asyncness(tcx, impl_m, impl_m_span, trait_m, trait_item_span) {
76 if let Err(_) = compare_method_predicate_entailment(
82 CheckImpliedWfMode::Check,
88 /// This function is best explained by example. Consider a trait:
90 /// trait Trait<'t, T> {
92 /// fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
97 /// impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
99 /// fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo;
102 /// We wish to decide if those two method types are compatible.
103 /// For this we have to show that, assuming the bounds of the impl hold, the
104 /// bounds of `trait_m` imply the bounds of `impl_m`.
106 /// We start out with `trait_to_impl_substs`, that maps the trait
107 /// type parameters to impl type parameters. This is taken from the
108 /// impl trait reference:
110 /// trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
112 /// We create a mapping `dummy_substs` that maps from the impl type
113 /// parameters to fresh types and regions. For type parameters,
114 /// this is the identity transform, but we could as well use any
115 /// placeholder types. For regions, we convert from bound to free
116 /// regions (Note: but only early-bound regions, i.e., those
117 /// declared on the impl or used in type parameter bounds).
119 /// impl_to_placeholder_substs = {'i => 'i0, U => U0, N => N0 }
121 /// Now we can apply `placeholder_substs` to the type of the impl method
122 /// to yield a new function type in terms of our fresh, placeholder
125 /// <'b> fn(t: &'i0 U0, m: &'b) -> Foo
127 /// We now want to extract and substitute the type of the *trait*
128 /// method and compare it. To do so, we must create a compound
129 /// substitution by combining `trait_to_impl_substs` and
130 /// `impl_to_placeholder_substs`, and also adding a mapping for the method
131 /// type parameters. We extend the mapping to also include
132 /// the method parameters.
134 /// trait_to_placeholder_substs = { T => &'i0 U0, Self => Foo, M => N0 }
136 /// Applying this to the trait method type yields:
138 /// <'a> fn(t: &'i0 U0, m: &'a) -> Foo
140 /// This type is also the same but the name of the bound region (`'a`
141 /// vs `'b`). However, the normal subtyping rules on fn types handle
142 /// this kind of equivalency just fine.
144 /// We now use these substitutions to ensure that all declared bounds are
145 /// satisfied by the implementation's method.
147 /// We do this by creating a parameter environment which contains a
148 /// substitution corresponding to `impl_to_placeholder_substs`. We then build
149 /// `trait_to_placeholder_substs` and use it to convert the predicates contained
150 /// in the `trait_m` generics to the placeholder form.
152 /// Finally we register each of these predicates as an obligation and check that
154 #[instrument(level = "debug", skip(tcx, impl_m_span, impl_trait_ref))]
155 fn compare_method_predicate_entailment<'tcx>(
157 impl_m: &ty::AssocItem,
159 trait_m: &ty::AssocItem,
160 impl_trait_ref: ty::TraitRef<'tcx>,
161 check_implied_wf: CheckImpliedWfMode,
162 ) -> Result<(), ErrorGuaranteed> {
163 let trait_to_impl_substs = impl_trait_ref.substs;
165 // This node-id should be used for the `body_id` field on each
166 // `ObligationCause` (and the `FnCtxt`).
168 // FIXME(@lcnr): remove that after removing `cause.body_id` from
170 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
171 let cause = ObligationCause::new(
174 ObligationCauseCode::CompareImplItemObligation {
175 impl_item_def_id: impl_m.def_id.expect_local(),
176 trait_item_def_id: trait_m.def_id,
181 // Create mapping from impl to placeholder.
182 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
184 // Create mapping from trait to placeholder.
185 let trait_to_placeholder_substs =
186 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
187 debug!("compare_impl_method: trait_to_placeholder_substs={:?}", trait_to_placeholder_substs);
189 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
190 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
192 // Check region bounds.
193 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, false)?;
195 // Create obligations for each predicate declared by the impl
196 // definition in the context of the trait's parameter
197 // environment. We can't just use `impl_env.caller_bounds`,
198 // however, because we want to replace all late-bound regions with
200 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
201 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
203 debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
205 // This is the only tricky bit of the new way we check implementation methods
206 // We need to build a set of predicates where only the method-level bounds
207 // are from the trait and we assume all other bounds from the implementation
208 // to be previously satisfied.
210 // We then register the obligations from the impl_m and check to see
211 // if all constraints hold.
214 .extend(trait_m_predicates.instantiate_own(tcx, trait_to_placeholder_substs).predicates);
216 // Construct trait parameter environment and then shift it into the placeholder viewpoint.
217 // The key step here is to update the caller_bounds's predicates to be
218 // the new hybrid bounds we computed.
219 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
220 let param_env = ty::ParamEnv::new(
221 tcx.intern_predicates(&hybrid_preds.predicates),
223 hir::Constness::NotConst,
225 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
227 let infcx = &tcx.infer_ctxt().build();
228 let ocx = ObligationCtxt::new(infcx);
230 debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds());
232 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs);
233 for (predicate, span) in iter::zip(impl_m_own_bounds.predicates, impl_m_own_bounds.spans) {
234 let normalize_cause = traits::ObligationCause::misc(span, impl_m_hir_id);
235 let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
237 let cause = ObligationCause::new(
240 ObligationCauseCode::CompareImplItemObligation {
241 impl_item_def_id: impl_m.def_id.expect_local(),
242 trait_item_def_id: trait_m.def_id,
246 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
249 // We now need to check that the signature of the impl method is
250 // compatible with that of the trait method. We do this by
251 // checking that `impl_fty <: trait_fty`.
253 // FIXME. Unfortunately, this doesn't quite work right now because
254 // associated type normalization is not integrated into subtype
255 // checks. For the comparison to be valid, we need to
256 // normalize the associated types in the impl/trait methods
257 // first. However, because function types bind regions, just
258 // calling `normalize_associated_types_in` would have no effect on
259 // any associated types appearing in the fn arguments or return
262 // Compute placeholder form of impl and trait method tys.
265 let mut wf_tys = FxIndexSet::default();
267 let unnormalized_impl_sig = infcx.replace_bound_vars_with_fresh_vars(
269 infer::HigherRankedType,
270 tcx.fn_sig(impl_m.def_id),
272 let unnormalized_impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(unnormalized_impl_sig));
274 let norm_cause = ObligationCause::misc(impl_m_span, impl_m_hir_id);
275 let impl_sig = ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig);
276 debug!("compare_impl_method: impl_fty={:?}", impl_sig);
278 let trait_sig = tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs);
279 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
281 // Next, add all inputs and output as well-formed tys. Importantly,
282 // we have to do this before normalization, since the normalized ty may
283 // not contain the input parameters. See issue #87748.
284 wf_tys.extend(trait_sig.inputs_and_output.iter());
285 let trait_sig = ocx.normalize(&norm_cause, param_env, trait_sig);
286 // We also have to add the normalized trait signature
287 // as we don't normalize during implied bounds computation.
288 wf_tys.extend(trait_sig.inputs_and_output.iter());
289 let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));
291 debug!("compare_impl_method: trait_fty={:?}", trait_fty);
293 // FIXME: We'd want to keep more accurate spans than "the method signature" when
294 // processing the comparison between the trait and impl fn, but we sadly lose them
295 // and point at the whole signature when a trait bound or specific input or output
296 // type would be more appropriate. In other places we have a `Vec<Span>`
297 // corresponding to their `Vec<Predicate>`, but we don't have that here.
298 // Fixing this would improve the output of test `issue-83765.rs`.
299 let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
301 if let Err(terr) = result {
302 debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
304 let emitted = report_trait_method_mismatch(
308 (trait_m, trait_sig),
315 if check_implied_wf == CheckImpliedWfMode::Check {
316 // We need to check that the impl's args are well-formed given
317 // the hybrid param-env (impl + trait method where-clauses).
318 ocx.register_obligation(traits::Obligation::new(
320 ObligationCause::dummy(),
322 ty::Binder::dummy(ty::PredicateKind::WellFormed(unnormalized_impl_fty.into())),
326 // Check that all obligations are satisfied by the implementation's
328 let errors = ocx.select_all_or_error();
329 if !errors.is_empty() {
330 match check_implied_wf {
331 CheckImpliedWfMode::Check => {
332 return compare_method_predicate_entailment(
338 CheckImpliedWfMode::Skip,
341 // If the skip-mode was successful, emit a lint.
342 emit_implied_wf_lint(infcx.tcx, impl_m, impl_m_hir_id, vec![]);
345 CheckImpliedWfMode::Skip => {
346 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
347 return Err(reported);
352 // Finally, resolve all regions. This catches wily misuses of
353 // lifetime parameters.
354 let outlives_env = OutlivesEnvironment::with_bounds(
357 infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys.clone()),
359 infcx.process_registered_region_obligations(
360 outlives_env.region_bound_pairs(),
361 outlives_env.param_env,
363 let errors = infcx.resolve_regions(&outlives_env);
364 if !errors.is_empty() {
365 // FIXME(compiler-errors): This can be simplified when IMPLIED_BOUNDS_ENTAILMENT
366 // becomes a hard error (i.e. ideally we'd just call `resolve_regions_and_report_errors`
367 match check_implied_wf {
368 CheckImpliedWfMode::Check => {
369 return compare_method_predicate_entailment(
375 CheckImpliedWfMode::Skip,
378 let bad_args = extract_bad_args_for_implies_lint(
381 (trait_m, trait_sig),
382 // Unnormalized impl sig corresponds to the HIR types written
383 (impl_m, unnormalized_impl_sig),
386 // If the skip-mode was successful, emit a lint.
387 emit_implied_wf_lint(tcx, impl_m, impl_m_hir_id, bad_args);
390 CheckImpliedWfMode::Skip => {
391 if infcx.tainted_by_errors().is_none() {
392 infcx.err_ctxt().report_region_errors(impl_m.def_id.expect_local(), &errors);
396 .delay_span_bug(rustc_span::DUMMY_SP, "error should have been emitted"));
404 fn extract_bad_args_for_implies_lint<'tcx>(
406 errors: &[infer::RegionResolutionError<'tcx>],
407 (trait_m, trait_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
408 (impl_m, impl_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
410 ) -> Vec<(Span, Option<String>)> {
411 let mut blame_generics = vec![];
412 for error in errors {
413 // Look for the subregion origin that contains an input/output type
414 let origin = match error {
415 infer::RegionResolutionError::ConcreteFailure(o, ..) => o,
416 infer::RegionResolutionError::GenericBoundFailure(o, ..) => o,
417 infer::RegionResolutionError::SubSupConflict(_, _, o, ..) => o,
418 infer::RegionResolutionError::UpperBoundUniverseConflict(.., o, _) => o,
420 // Extract (possible) input/output types from origin
422 infer::SubregionOrigin::Subtype(trace) => {
423 if let Some((a, b)) = trace.values.ty() {
424 blame_generics.extend([a, b]);
427 infer::SubregionOrigin::RelateParamBound(_, ty, _) => blame_generics.push(*ty),
428 infer::SubregionOrigin::ReferenceOutlivesReferent(ty, _) => blame_generics.push(*ty),
433 let fn_decl = tcx.hir().fn_decl_by_hir_id(hir_id).unwrap();
434 let opt_ret_ty = match fn_decl.output {
435 hir::FnRetTy::DefaultReturn(_) => None,
436 hir::FnRetTy::Return(ty) => Some(ty),
439 // Map late-bound regions from trait to impl, so the names are right.
440 let mapping = std::iter::zip(
441 tcx.fn_sig(trait_m.def_id).bound_vars(),
442 tcx.fn_sig(impl_m.def_id).bound_vars(),
444 .filter_map(|(impl_bv, trait_bv)| {
445 if let ty::BoundVariableKind::Region(impl_bv) = impl_bv
446 && let ty::BoundVariableKind::Region(trait_bv) = trait_bv
448 Some((impl_bv, trait_bv))
455 // For each arg, see if it was in the "blame" of any of the region errors.
456 // If so, then try to produce a suggestion to replace the argument type with
457 // one from the trait.
458 let mut bad_args = vec![];
459 for (idx, (ty, hir_ty)) in
460 std::iter::zip(impl_sig.inputs_and_output, fn_decl.inputs.iter().chain(opt_ret_ty))
463 let expected_ty = trait_sig.inputs_and_output[idx]
464 .fold_with(&mut RemapLateBound { tcx, mapping: &mapping });
465 if blame_generics.iter().any(|blame| ty.contains(*blame)) {
466 let expected_ty_sugg = expected_ty.to_string();
469 // Only suggest something if it actually changed.
470 (expected_ty_sugg != ty.to_string()).then_some(expected_ty_sugg),
478 struct RemapLateBound<'a, 'tcx> {
480 mapping: &'a FxHashMap<ty::BoundRegionKind, ty::BoundRegionKind>,
483 impl<'tcx> TypeFolder<'tcx> for RemapLateBound<'_, 'tcx> {
484 fn tcx(&self) -> TyCtxt<'tcx> {
488 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
489 if let ty::ReFree(fr) = *r {
490 self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
493 .get(&fr.bound_region)
495 .unwrap_or(fr.bound_region),
504 fn emit_implied_wf_lint<'tcx>(
506 impl_m: &ty::AssocItem,
508 bad_args: Vec<(Span, Option<String>)>,
510 let span: MultiSpan = if bad_args.is_empty() {
511 tcx.def_span(impl_m.def_id).into()
513 bad_args.iter().map(|(span, _)| *span).collect::<Vec<_>>().into()
515 tcx.struct_span_lint_hir(
516 rustc_session::lint::builtin::IMPLIED_BOUNDS_ENTAILMENT,
519 "impl method assumes more implied bounds than the corresponding trait method",
521 let bad_args: Vec<_> =
522 bad_args.into_iter().filter_map(|(span, sugg)| Some((span, sugg?))).collect();
523 if !bad_args.is_empty() {
524 lint.multipart_suggestion(
526 "replace {} type{} to make the impl signature compatible",
527 pluralize!("this", bad_args.len()),
528 pluralize!(bad_args.len())
531 Applicability::MaybeIncorrect,
539 #[derive(Debug, PartialEq, Eq)]
540 enum CheckImpliedWfMode {
541 /// Checks implied well-formedness of the impl method. If it fails, we will
542 /// re-check with `Skip`, and emit a lint if it succeeds.
544 /// Skips checking implied well-formedness of the impl method, but will emit
545 /// a lint if the `compare_method_predicate_entailment` succeeded. This means that
546 /// the reason that we had failed earlier during `Check` was due to the impl
547 /// having stronger requirements than the trait.
551 fn compare_asyncness<'tcx>(
553 impl_m: &ty::AssocItem,
555 trait_m: &ty::AssocItem,
556 trait_item_span: Option<Span>,
557 ) -> Result<(), ErrorGuaranteed> {
558 if tcx.asyncness(trait_m.def_id) == hir::IsAsync::Async {
559 match tcx.fn_sig(impl_m.def_id).skip_binder().output().kind() {
560 ty::Alias(ty::Opaque, ..) => {
561 // allow both `async fn foo()` and `fn foo() -> impl Future`
564 // We don't know if it's ok, but at least it's already an error.
567 return Err(tcx.sess.emit_err(crate::errors::AsyncTraitImplShouldBeAsync {
569 method_name: trait_m.name,
579 /// Given a method def-id in an impl, compare the method signature of the impl
580 /// against the trait that it's implementing. In doing so, infer the hidden types
581 /// that this method's signature provides to satisfy each return-position `impl Trait`
582 /// in the trait signature.
584 /// The method is also responsible for making sure that the hidden types for each
585 /// RPITIT actually satisfy the bounds of the `impl Trait`, i.e. that if we infer
586 /// `impl Trait = Foo`, that `Foo: Trait` holds.
588 /// For example, given the sample code:
591 /// #![feature(return_position_impl_trait_in_trait)]
593 /// use std::ops::Deref;
596 /// fn bar() -> impl Deref<Target = impl Sized>;
597 /// // ^- RPITIT #1 ^- RPITIT #2
600 /// impl Foo for () {
601 /// fn bar() -> Box<String> { Box::new(String::new()) }
605 /// The hidden types for the RPITITs in `bar` would be inferred to:
606 /// * `impl Deref` (RPITIT #1) = `Box<String>`
607 /// * `impl Sized` (RPITIT #2) = `String`
609 /// The relationship between these two types is straightforward in this case, but
610 /// may be more tenuously connected via other `impl`s and normalization rules for
611 /// cases of more complicated nested RPITITs.
612 #[instrument(skip(tcx), level = "debug", ret)]
613 pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
616 ) -> Result<&'tcx FxHashMap<DefId, Ty<'tcx>>, ErrorGuaranteed> {
617 let impl_m = tcx.opt_associated_item(def_id).unwrap();
618 let trait_m = tcx.opt_associated_item(impl_m.trait_item_def_id.unwrap()).unwrap();
619 let impl_trait_ref = tcx.impl_trait_ref(impl_m.impl_container(tcx).unwrap()).unwrap();
620 let param_env = tcx.param_env(def_id);
622 // First, check a few of the same things as `compare_impl_method`,
623 // just so we don't ICE during substitution later.
624 compare_number_of_generics(tcx, impl_m, trait_m, tcx.hir().span_if_local(impl_m.def_id), true)?;
625 compare_generic_param_kinds(tcx, impl_m, trait_m, true)?;
626 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, true)?;
628 let trait_to_impl_substs = impl_trait_ref.substs;
630 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
631 let return_span = tcx.hir().fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
632 let cause = ObligationCause::new(
635 ObligationCauseCode::CompareImplItemObligation {
636 impl_item_def_id: impl_m.def_id.expect_local(),
637 trait_item_def_id: trait_m.def_id,
642 // Create mapping from impl to placeholder.
643 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
645 // Create mapping from trait to placeholder.
646 let trait_to_placeholder_substs =
647 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
649 let infcx = &tcx.infer_ctxt().build();
650 let ocx = ObligationCtxt::new(infcx);
652 // Normalize the impl signature with fresh variables for lifetime inference.
653 let norm_cause = ObligationCause::misc(return_span, impl_m_hir_id);
654 let impl_sig = ocx.normalize(
657 infcx.replace_bound_vars_with_fresh_vars(
659 infer::HigherRankedType,
660 tcx.fn_sig(impl_m.def_id),
663 impl_sig.error_reported()?;
664 let impl_return_ty = impl_sig.output();
666 // Normalize the trait signature with liberated bound vars, passing it through
667 // the ImplTraitInTraitCollector, which gathers all of the RPITITs and replaces
668 // them with inference variables.
669 // We will use these inference variables to collect the hidden types of RPITITs.
670 let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_hir_id);
671 let unnormalized_trait_sig = tcx
672 .liberate_late_bound_regions(
674 tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs),
676 .fold_with(&mut collector);
677 let trait_sig = ocx.normalize(&norm_cause, param_env, unnormalized_trait_sig);
678 trait_sig.error_reported()?;
679 let trait_return_ty = trait_sig.output();
681 let wf_tys = FxIndexSet::from_iter(
682 unnormalized_trait_sig.inputs_and_output.iter().chain(trait_sig.inputs_and_output.iter()),
685 match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
688 let mut diag = struct_span_err!(
692 "method `{}` has an incompatible return type for trait",
696 infcx.err_ctxt().note_type_err(
699 hir.get_if_local(impl_m.def_id)
700 .and_then(|node| node.fn_decl())
701 .map(|decl| (decl.output.span(), "return type in trait".to_owned())),
702 Some(infer::ValuePairs::Terms(ExpectedFound {
703 expected: trait_return_ty.into(),
704 found: impl_return_ty.into(),
710 return Err(diag.emit());
714 debug!(?trait_sig, ?impl_sig, "equating function signatures");
716 // Unify the whole function signature. We need to do this to fully infer
717 // the lifetimes of the return type, but do this after unifying just the
718 // return types, since we want to avoid duplicating errors from
719 // `compare_method_predicate_entailment`.
720 match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
723 // This function gets called during `compare_method_predicate_entailment` when normalizing a
724 // signature that contains RPITIT. When the method signatures don't match, we have to
725 // emit an error now because `compare_method_predicate_entailment` will not report the error
726 // when normalization fails.
727 let emitted = report_trait_method_mismatch(
731 (trait_m, trait_sig),
739 // Check that all obligations are satisfied by the implementation's
741 let errors = ocx.select_all_or_error();
742 if !errors.is_empty() {
743 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
744 return Err(reported);
747 // Finally, resolve all regions. This catches wily misuses of
748 // lifetime parameters.
749 let outlives_environment = OutlivesEnvironment::with_bounds(
752 infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys),
754 infcx.err_ctxt().check_region_obligations_and_report_errors(
755 impl_m.def_id.expect_local(),
756 &outlives_environment,
759 let mut collected_tys = FxHashMap::default();
760 for (def_id, (ty, substs)) in collector.types {
761 match infcx.fully_resolve(ty) {
763 // `ty` contains free regions that we created earlier while liberating the
764 // trait fn signature. However, projection normalization expects `ty` to
765 // contains `def_id`'s early-bound regions.
766 let id_substs = InternalSubsts::identity_for_item(tcx, def_id);
767 debug!(?id_substs, ?substs);
768 let map: FxHashMap<ty::GenericArg<'tcx>, ty::GenericArg<'tcx>> =
769 std::iter::zip(substs, id_substs).collect();
772 // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound
773 // region substs that are synthesized during AST lowering. These are substs
774 // that are appended to the parent substs (trait and trait method). However,
775 // we're trying to infer the unsubstituted type value of the RPITIT inside
776 // the *impl*, so we can later use the impl's method substs to normalize
777 // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`).
779 // Due to the design of RPITITs, during AST lowering, we have no idea that
780 // an impl method corresponds to a trait method with RPITITs in it. Therefore,
781 // we don't have a list of early-bound region substs for the RPITIT in the impl.
782 // Since early region parameters are index-based, we can't just rebase these
783 // (trait method) early-bound region substs onto the impl, and there's no
784 // guarantee that the indices from the trait substs and impl substs line up.
785 // So to fix this, we subtract the number of trait substs and add the number of
786 // impl substs to *renumber* these early-bound regions to their corresponding
787 // indices in the impl's substitutions list.
789 // Also, we only need to account for a difference in trait and impl substs,
790 // since we previously enforce that the trait method and impl method have the
792 let num_trait_substs = trait_to_impl_substs.len();
793 let num_impl_substs = tcx.generics_of(impl_m.container_id(tcx)).params.len();
794 let ty = tcx.fold_regions(ty, |region, _| {
795 match region.kind() {
796 // Remap all free regions, which correspond to late-bound regions in the function.
798 // Remap early-bound regions as long as they don't come from the `impl` itself.
799 ty::ReEarlyBound(ebr) if tcx.parent(ebr.def_id) != impl_m.container_id(tcx) => {}
802 let Some(ty::ReEarlyBound(e)) = map.get(®ion.into()).map(|r| r.expect_region().kind())
808 "expected ReFree to map to ReEarlyBound"
810 return tcx.lifetimes.re_static;
812 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
815 index: (e.index as usize - num_trait_substs + num_impl_substs) as u32,
819 collected_tys.insert(def_id, ty);
822 let reported = tcx.sess.delay_span_bug(
824 format!("could not fully resolve: {ty} => {err:?}"),
826 collected_tys.insert(def_id, tcx.ty_error_with_guaranteed(reported));
831 Ok(&*tcx.arena.alloc(collected_tys))
834 struct ImplTraitInTraitCollector<'a, 'tcx> {
835 ocx: &'a ObligationCtxt<'a, 'tcx>,
836 types: FxHashMap<DefId, (Ty<'tcx>, ty::SubstsRef<'tcx>)>,
838 param_env: ty::ParamEnv<'tcx>,
842 impl<'a, 'tcx> ImplTraitInTraitCollector<'a, 'tcx> {
844 ocx: &'a ObligationCtxt<'a, 'tcx>,
846 param_env: ty::ParamEnv<'tcx>,
849 ImplTraitInTraitCollector { ocx, types: FxHashMap::default(), span, param_env, body_id }
853 impl<'tcx> TypeFolder<'tcx> for ImplTraitInTraitCollector<'_, 'tcx> {
854 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
858 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
859 if let ty::Alias(ty::Projection, proj) = ty.kind()
860 && self.tcx().def_kind(proj.def_id) == DefKind::ImplTraitPlaceholder
862 if let Some((ty, _)) = self.types.get(&proj.def_id) {
865 //FIXME(RPITIT): Deny nested RPITIT in substs too
866 if proj.substs.has_escaping_bound_vars() {
867 bug!("FIXME(RPITIT): error here");
869 // Replace with infer var
870 let infer_ty = self.ocx.infcx.next_ty_var(TypeVariableOrigin {
872 kind: TypeVariableOriginKind::MiscVariable,
874 self.types.insert(proj.def_id, (infer_ty, proj.substs));
875 // Recurse into bounds
876 for (pred, pred_span) in self.tcx().bound_explicit_item_bounds(proj.def_id).subst_iter_copied(self.tcx(), proj.substs) {
877 let pred = pred.fold_with(self);
878 let pred = self.ocx.normalize(
879 &ObligationCause::misc(self.span, self.body_id),
884 self.ocx.register_obligation(traits::Obligation::new(
886 ObligationCause::new(
889 ObligationCauseCode::BindingObligation(proj.def_id, pred_span),
897 ty.super_fold_with(self)
902 fn report_trait_method_mismatch<'tcx>(
903 infcx: &InferCtxt<'tcx>,
904 mut cause: ObligationCause<'tcx>,
905 terr: TypeError<'tcx>,
906 (trait_m, trait_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
907 (impl_m, impl_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
908 impl_trait_ref: ty::TraitRef<'tcx>,
909 ) -> ErrorGuaranteed {
911 let (impl_err_span, trait_err_span) =
912 extract_spans_for_error_reporting(&infcx, terr, &cause, impl_m, trait_m);
914 let mut diag = struct_span_err!(
918 "method `{}` has an incompatible type for trait",
922 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
923 if trait_m.fn_has_self_parameter =>
925 let ty = trait_sig.inputs()[0];
926 let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty()) {
927 ExplicitSelf::ByValue => "self".to_owned(),
928 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
929 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
930 _ => format!("self: {ty}"),
933 // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
934 // span points only at the type `Box<Self`>, but we want to cover the whole
935 // argument pattern and type.
936 let span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
937 ImplItemKind::Fn(ref sig, body) => tcx
939 .body_param_names(body)
940 .zip(sig.decl.inputs.iter())
941 .map(|(param, ty)| param.span.to(ty.span))
943 .unwrap_or(impl_err_span),
944 _ => bug!("{:?} is not a method", impl_m),
947 diag.span_suggestion(
949 "change the self-receiver type to match the trait",
951 Applicability::MachineApplicable,
954 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
955 if trait_sig.inputs().len() == *i {
956 // Suggestion to change output type. We do not suggest in `async` functions
957 // to avoid complex logic or incorrect output.
958 match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
959 ImplItemKind::Fn(ref sig, _) if !sig.header.asyncness.is_async() => {
960 let msg = "change the output type to match the trait";
961 let ap = Applicability::MachineApplicable;
962 match sig.decl.output {
963 hir::FnRetTy::DefaultReturn(sp) => {
964 let sugg = format!("-> {} ", trait_sig.output());
965 diag.span_suggestion_verbose(sp, msg, sugg, ap);
967 hir::FnRetTy::Return(hir_ty) => {
968 let sugg = trait_sig.output();
969 diag.span_suggestion(hir_ty.span, msg, sugg, ap);
975 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
976 diag.span_suggestion(
978 "change the parameter type to match the trait",
980 Applicability::MachineApplicable,
987 cause.span = impl_err_span;
988 infcx.err_ctxt().note_type_err(
991 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
992 Some(infer::ValuePairs::Sigs(ExpectedFound { expected: trait_sig, found: impl_sig })),
1001 fn check_region_bounds_on_impl_item<'tcx>(
1003 impl_m: &ty::AssocItem,
1004 trait_m: &ty::AssocItem,
1006 ) -> Result<(), ErrorGuaranteed> {
1007 let impl_generics = tcx.generics_of(impl_m.def_id);
1008 let impl_params = impl_generics.own_counts().lifetimes;
1010 let trait_generics = tcx.generics_of(trait_m.def_id);
1011 let trait_params = trait_generics.own_counts().lifetimes;
1014 "check_region_bounds_on_impl_item: \
1015 trait_generics={:?} \
1016 impl_generics={:?}",
1017 trait_generics, impl_generics
1020 // Must have same number of early-bound lifetime parameters.
1021 // Unfortunately, if the user screws up the bounds, then this
1022 // will change classification between early and late. E.g.,
1023 // if in trait we have `<'a,'b:'a>`, and in impl we just have
1024 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
1025 // in trait but 0 in the impl. But if we report "expected 2
1026 // but found 0" it's confusing, because it looks like there
1027 // are zero. Since I don't quite know how to phrase things at
1028 // the moment, give a kind of vague error message.
1029 if trait_params != impl_params {
1032 .get_generics(impl_m.def_id.expect_local())
1033 .expect("expected impl item to have generics or else we can't compare them")
1036 let mut generics_span = None;
1037 let mut bounds_span = vec![];
1038 let mut where_span = None;
1039 if let Some(trait_node) = tcx.hir().get_if_local(trait_m.def_id)
1040 && let Some(trait_generics) = trait_node.generics()
1042 generics_span = Some(trait_generics.span);
1043 // FIXME: we could potentially look at the impl's bounds to not point at bounds that
1044 // *are* present in the impl.
1045 for p in trait_generics.predicates {
1046 if let hir::WherePredicate::BoundPredicate(pred) = p {
1047 for b in pred.bounds {
1048 if let hir::GenericBound::Outlives(lt) = b {
1049 bounds_span.push(lt.ident.span);
1054 if let Some(impl_node) = tcx.hir().get_if_local(impl_m.def_id)
1055 && let Some(impl_generics) = impl_node.generics()
1057 let mut impl_bounds = 0;
1058 for p in impl_generics.predicates {
1059 if let hir::WherePredicate::BoundPredicate(pred) = p {
1060 for b in pred.bounds {
1061 if let hir::GenericBound::Outlives(_) = b {
1067 if impl_bounds == bounds_span.len() {
1068 bounds_span = vec![];
1069 } else if impl_generics.has_where_clause_predicates {
1070 where_span = Some(impl_generics.where_clause_span);
1076 .create_err(LifetimesOrBoundsMismatchOnTrait {
1078 item_kind: assoc_item_kind_str(impl_m),
1079 ident: impl_m.ident(tcx),
1084 .emit_unless(delay);
1085 return Err(reported);
1091 #[instrument(level = "debug", skip(infcx))]
1092 fn extract_spans_for_error_reporting<'tcx>(
1093 infcx: &infer::InferCtxt<'tcx>,
1094 terr: TypeError<'_>,
1095 cause: &ObligationCause<'tcx>,
1096 impl_m: &ty::AssocItem,
1097 trait_m: &ty::AssocItem,
1098 ) -> (Span, Option<Span>) {
1099 let tcx = infcx.tcx;
1100 let mut impl_args = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
1101 ImplItemKind::Fn(ref sig, _) => {
1102 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1104 _ => bug!("{:?} is not a method", impl_m),
1107 trait_m.def_id.as_local().map(|def_id| match tcx.hir().expect_trait_item(def_id).kind {
1108 TraitItemKind::Fn(ref sig, _) => {
1109 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1111 _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
1115 TypeError::ArgumentMutability(i) => {
1116 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1118 TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1119 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1121 _ => (cause.span(), tcx.hir().span_if_local(trait_m.def_id)),
1125 fn compare_self_type<'tcx>(
1127 impl_m: &ty::AssocItem,
1129 trait_m: &ty::AssocItem,
1130 impl_trait_ref: ty::TraitRef<'tcx>,
1131 ) -> Result<(), ErrorGuaranteed> {
1132 // Try to give more informative error messages about self typing
1133 // mismatches. Note that any mismatch will also be detected
1134 // below, where we construct a canonical function type that
1135 // includes the self parameter as a normal parameter. It's just
1136 // that the error messages you get out of this code are a bit more
1137 // inscrutable, particularly for cases where one method has no
1140 let self_string = |method: &ty::AssocItem| {
1141 let untransformed_self_ty = match method.container {
1142 ty::ImplContainer => impl_trait_ref.self_ty(),
1143 ty::TraitContainer => tcx.types.self_param,
1145 let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
1146 let param_env = ty::ParamEnv::reveal_all();
1148 let infcx = tcx.infer_ctxt().build();
1149 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1150 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
1151 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
1152 ExplicitSelf::ByValue => "self".to_owned(),
1153 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
1154 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
1155 _ => format!("self: {self_arg_ty}"),
1159 match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
1160 (false, false) | (true, true) => {}
1163 let self_descr = self_string(impl_m);
1164 let mut err = struct_span_err!(
1168 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1172 err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
1173 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1174 err.span_label(span, format!("trait method declared without `{self_descr}`"));
1176 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1178 let reported = err.emit();
1179 return Err(reported);
1183 let self_descr = self_string(trait_m);
1184 let mut err = struct_span_err!(
1188 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1192 err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
1193 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1194 err.span_label(span, format!("`{self_descr}` used in trait"));
1196 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1198 let reported = err.emit();
1199 return Err(reported);
1206 /// Checks that the number of generics on a given assoc item in a trait impl is the same
1207 /// as the number of generics on the respective assoc item in the trait definition.
1209 /// For example this code emits the errors in the following code:
1216 /// impl Trait for () {
1219 /// type Assoc = u32;
1224 /// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
1225 /// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
1226 /// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
1227 fn compare_number_of_generics<'tcx>(
1229 impl_: &ty::AssocItem,
1230 trait_: &ty::AssocItem,
1231 trait_span: Option<Span>,
1233 ) -> Result<(), ErrorGuaranteed> {
1234 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1235 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1237 // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
1238 // in `compare_generic_param_kinds` which will give a nicer error message than something like:
1239 // "expected 1 type parameter, found 0 type parameters"
1240 if (trait_own_counts.types + trait_own_counts.consts)
1241 == (impl_own_counts.types + impl_own_counts.consts)
1247 ("type", trait_own_counts.types, impl_own_counts.types),
1248 ("const", trait_own_counts.consts, impl_own_counts.consts),
1251 let item_kind = assoc_item_kind_str(impl_);
1253 let mut err_occurred = None;
1254 for (kind, trait_count, impl_count) in matchings {
1255 if impl_count != trait_count {
1256 let arg_spans = |kind: ty::AssocKind, generics: &hir::Generics<'_>| {
1257 let mut spans = generics
1260 .filter(|p| match p.kind {
1261 hir::GenericParamKind::Lifetime {
1262 kind: hir::LifetimeParamKind::Elided,
1264 // A fn can have an arbitrary number of extra elided lifetimes for the
1266 !matches!(kind, ty::AssocKind::Fn)
1271 .collect::<Vec<Span>>();
1272 if spans.is_empty() {
1273 spans = vec![generics.span]
1277 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1278 let trait_item = tcx.hir().expect_trait_item(def_id);
1279 let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics);
1280 let impl_trait_spans: Vec<Span> = trait_item
1284 .filter_map(|p| match p.kind {
1285 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1289 (Some(arg_spans), impl_trait_spans)
1291 (trait_span.map(|s| vec![s]), vec![])
1294 let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local());
1295 let impl_item_impl_trait_spans: Vec<Span> = impl_item
1299 .filter_map(|p| match p.kind {
1300 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1304 let spans = arg_spans(impl_.kind, impl_item.generics);
1305 let span = spans.first().copied();
1307 let mut err = tcx.sess.struct_span_err_with_code(
1310 "{} `{}` has {} {kind} parameter{} but its trait \
1311 declaration has {} {kind} parameter{}",
1315 pluralize!(impl_count),
1317 pluralize!(trait_count),
1320 DiagnosticId::Error("E0049".into()),
1323 let mut suffix = None;
1325 if let Some(spans) = trait_spans {
1326 let mut spans = spans.iter();
1327 if let Some(span) = spans.next() {
1331 "expected {} {} parameter{}",
1334 pluralize!(trait_count),
1339 err.span_label(*span, "");
1342 suffix = Some(format!(", expected {trait_count}"));
1345 if let Some(span) = span {
1349 "found {} {} parameter{}{}",
1352 pluralize!(impl_count),
1353 suffix.unwrap_or_else(String::new),
1358 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1359 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1362 let reported = err.emit_unless(delay);
1363 err_occurred = Some(reported);
1367 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1370 fn compare_number_of_method_arguments<'tcx>(
1372 impl_m: &ty::AssocItem,
1374 trait_m: &ty::AssocItem,
1375 trait_item_span: Option<Span>,
1376 ) -> Result<(), ErrorGuaranteed> {
1377 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1378 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1379 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
1380 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
1381 if trait_number_args != impl_number_args {
1382 let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
1383 match tcx.hir().expect_trait_item(def_id).kind {
1384 TraitItemKind::Fn(ref trait_m_sig, _) => {
1385 let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
1386 if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
1390 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1396 _ => bug!("{:?} is not a method", impl_m),
1401 let impl_span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
1402 ImplItemKind::Fn(ref impl_m_sig, _) => {
1403 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
1404 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
1408 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1414 _ => bug!("{:?} is not a method", impl_m),
1416 let mut err = struct_span_err!(
1420 "method `{}` has {} but the declaration in trait `{}` has {}",
1422 potentially_plural_count(impl_number_args, "parameter"),
1423 tcx.def_path_str(trait_m.def_id),
1426 if let Some(trait_span) = trait_span {
1430 "trait requires {}",
1431 potentially_plural_count(trait_number_args, "parameter")
1435 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1440 "expected {}, found {}",
1441 potentially_plural_count(trait_number_args, "parameter"),
1445 let reported = err.emit();
1446 return Err(reported);
1452 fn compare_synthetic_generics<'tcx>(
1454 impl_m: &ty::AssocItem,
1455 trait_m: &ty::AssocItem,
1456 ) -> Result<(), ErrorGuaranteed> {
1457 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
1458 // 1. Better messages for the span labels
1459 // 2. Explanation as to what is going on
1460 // If we get here, we already have the same number of generics, so the zip will
1462 let mut error_found = None;
1463 let impl_m_generics = tcx.generics_of(impl_m.def_id);
1464 let trait_m_generics = tcx.generics_of(trait_m.def_id);
1465 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
1466 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1467 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1469 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
1470 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1471 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1473 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1474 iter::zip(impl_m_type_params, trait_m_type_params)
1476 if impl_synthetic != trait_synthetic {
1477 let impl_def_id = impl_def_id.expect_local();
1478 let impl_span = tcx.def_span(impl_def_id);
1479 let trait_span = tcx.def_span(trait_def_id);
1480 let mut err = struct_span_err!(
1484 "method `{}` has incompatible signature for trait",
1487 err.span_label(trait_span, "declaration in trait here");
1488 match (impl_synthetic, trait_synthetic) {
1489 // The case where the impl method uses `impl Trait` but the trait method uses
1490 // explicit generics
1492 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1494 // try taking the name from the trait impl
1495 // FIXME: this is obviously suboptimal since the name can already be used
1496 // as another generic argument
1497 let new_name = tcx.opt_item_name(trait_def_id)?;
1498 let trait_m = trait_m.def_id.as_local()?;
1499 let trait_m = tcx.hir().expect_trait_item(trait_m);
1501 let impl_m = impl_m.def_id.as_local()?;
1502 let impl_m = tcx.hir().expect_impl_item(impl_m);
1504 // in case there are no generics, take the spot between the function name
1505 // and the opening paren of the argument list
1506 let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1507 // in case there are generics, just replace them
1509 impl_m.generics.span.substitute_dummy(new_generics_span);
1510 // replace with the generics from the trait
1512 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1514 err.multipart_suggestion(
1515 "try changing the `impl Trait` argument to a generic parameter",
1517 // replace `impl Trait` with `T`
1518 (impl_span, new_name.to_string()),
1519 // replace impl method generics with trait method generics
1520 // This isn't quite right, as users might have changed the names
1521 // of the generics, but it works for the common case
1522 (generics_span, new_generics),
1524 Applicability::MaybeIncorrect,
1529 // The case where the trait method uses `impl Trait`, but the impl method uses
1530 // explicit generics.
1532 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1534 let impl_m = impl_m.def_id.as_local()?;
1535 let impl_m = tcx.hir().expect_impl_item(impl_m);
1536 let input_tys = match impl_m.kind {
1537 hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
1538 _ => unreachable!(),
1540 struct Visitor(Option<Span>, hir::def_id::LocalDefId);
1541 impl<'v> intravisit::Visitor<'v> for Visitor {
1542 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
1543 intravisit::walk_ty(self, ty);
1544 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
1546 && let Res::Def(DefKind::TyParam, def_id) = path.res
1547 && def_id == self.1.to_def_id()
1549 self.0 = Some(ty.span);
1553 let mut visitor = Visitor(None, impl_def_id);
1554 for ty in input_tys {
1555 intravisit::Visitor::visit_ty(&mut visitor, ty);
1557 let span = visitor.0?;
1559 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
1560 let bounds = bounds.first()?.span().to(bounds.last()?.span());
1561 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
1563 err.multipart_suggestion(
1564 "try removing the generic parameter and using `impl Trait` instead",
1566 // delete generic parameters
1567 (impl_m.generics.span, String::new()),
1568 // replace param usage with `impl Trait`
1569 (span, format!("impl {bounds}")),
1571 Applicability::MaybeIncorrect,
1576 _ => unreachable!(),
1578 let reported = err.emit();
1579 error_found = Some(reported);
1582 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
1585 /// Checks that all parameters in the generics of a given assoc item in a trait impl have
1586 /// the same kind as the respective generic parameter in the trait def.
1588 /// For example all 4 errors in the following code are emitted here:
1591 /// fn foo<const N: u8>();
1592 /// type bar<const N: u8>;
1593 /// fn baz<const N: u32>();
1597 /// impl Foo for () {
1598 /// fn foo<const N: u64>() {}
1600 /// type bar<const N: u64> {}
1604 /// type blah<const N: i64> = u32;
1609 /// This function does not handle lifetime parameters
1610 fn compare_generic_param_kinds<'tcx>(
1612 impl_item: &ty::AssocItem,
1613 trait_item: &ty::AssocItem,
1615 ) -> Result<(), ErrorGuaranteed> {
1616 assert_eq!(impl_item.kind, trait_item.kind);
1618 let ty_const_params_of = |def_id| {
1619 tcx.generics_of(def_id).params.iter().filter(|param| {
1622 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1627 for (param_impl, param_trait) in
1628 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1630 use GenericParamDefKind::*;
1631 if match (¶m_impl.kind, ¶m_trait.kind) {
1632 (Const { .. }, Const { .. })
1633 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1637 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1638 // this is exhaustive so that anyone adding new generic param kinds knows
1639 // to make sure this error is reported for them.
1640 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1641 (Lifetime { .. }, _) | (_, Lifetime { .. }) => unreachable!(),
1643 let param_impl_span = tcx.def_span(param_impl.def_id);
1644 let param_trait_span = tcx.def_span(param_trait.def_id);
1646 let mut err = struct_span_err!(
1650 "{} `{}` has an incompatible generic parameter for trait `{}`",
1651 assoc_item_kind_str(&impl_item),
1653 &tcx.def_path_str(tcx.parent(trait_item.def_id))
1656 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
1658 format!("{} const parameter of type `{}`", prefix, tcx.type_of(param.def_id))
1660 Type { .. } => format!("{} type parameter", prefix),
1661 Lifetime { .. } => unreachable!(),
1664 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
1665 err.span_label(trait_header_span, "");
1666 err.span_label(param_trait_span, make_param_message("expected", param_trait));
1668 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1669 err.span_label(impl_header_span, "");
1670 err.span_label(param_impl_span, make_param_message("found", param_impl));
1672 let reported = err.emit_unless(delay);
1673 return Err(reported);
1680 /// Use `tcx.compare_impl_const` instead
1681 pub(super) fn compare_impl_const_raw(
1683 (impl_const_item_def, trait_const_item_def): (LocalDefId, DefId),
1684 ) -> Result<(), ErrorGuaranteed> {
1685 let impl_const_item = tcx.associated_item(impl_const_item_def);
1686 let trait_const_item = tcx.associated_item(trait_const_item_def);
1687 let impl_trait_ref = tcx.impl_trait_ref(impl_const_item.container_id(tcx)).unwrap();
1688 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
1690 let impl_c_span = tcx.def_span(impl_const_item_def.to_def_id());
1692 let infcx = tcx.infer_ctxt().build();
1693 let param_env = tcx.param_env(impl_const_item_def.to_def_id());
1694 let ocx = ObligationCtxt::new(&infcx);
1696 // The below is for the most part highly similar to the procedure
1697 // for methods above. It is simpler in many respects, especially
1698 // because we shouldn't really have to deal with lifetimes or
1699 // predicates. In fact some of this should probably be put into
1700 // shared functions because of DRY violations...
1701 let trait_to_impl_substs = impl_trait_ref.substs;
1703 // Create a parameter environment that represents the implementation's
1705 let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_const_item_def);
1707 // Compute placeholder form of impl and trait const tys.
1708 let impl_ty = tcx.type_of(impl_const_item_def.to_def_id());
1709 let trait_ty = tcx.bound_type_of(trait_const_item_def).subst(tcx, trait_to_impl_substs);
1710 let mut cause = ObligationCause::new(
1713 ObligationCauseCode::CompareImplItemObligation {
1714 impl_item_def_id: impl_const_item_def,
1715 trait_item_def_id: trait_const_item_def,
1716 kind: impl_const_item.kind,
1720 // There is no "body" here, so just pass dummy id.
1721 let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
1723 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1725 let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
1727 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1729 let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
1731 if let Err(terr) = err {
1733 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1737 // Locate the Span containing just the type of the offending impl
1738 match tcx.hir().expect_impl_item(impl_const_item_def).kind {
1739 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
1740 _ => bug!("{:?} is not a impl const", impl_const_item),
1743 let mut diag = struct_span_err!(
1747 "implemented const `{}` has an incompatible type for trait",
1748 trait_const_item.name
1751 let trait_c_span = trait_const_item_def.as_local().map(|trait_c_def_id| {
1752 // Add a label to the Span containing just the type of the const
1753 match tcx.hir().expect_trait_item(trait_c_def_id).kind {
1754 TraitItemKind::Const(ref ty, _) => ty.span,
1755 _ => bug!("{:?} is not a trait const", trait_const_item),
1759 infcx.err_ctxt().note_type_err(
1762 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1763 Some(infer::ValuePairs::Terms(ExpectedFound {
1764 expected: trait_ty.into(),
1765 found: impl_ty.into(),
1771 return Err(diag.emit());
1774 // Check that all obligations are satisfied by the implementation's
1776 let errors = ocx.select_all_or_error();
1777 if !errors.is_empty() {
1778 return Err(infcx.err_ctxt().report_fulfillment_errors(&errors, None));
1781 let outlives_environment = OutlivesEnvironment::new(param_env);
1784 .check_region_obligations_and_report_errors(impl_const_item_def, &outlives_environment)?;
1788 pub(super) fn compare_impl_ty<'tcx>(
1790 impl_ty: &ty::AssocItem,
1792 trait_ty: &ty::AssocItem,
1793 impl_trait_ref: ty::TraitRef<'tcx>,
1794 trait_item_span: Option<Span>,
1796 debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1798 let _: Result<(), ErrorGuaranteed> = (|| {
1799 compare_number_of_generics(tcx, impl_ty, trait_ty, trait_item_span, false)?;
1801 compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
1803 let sp = tcx.def_span(impl_ty.def_id);
1804 compare_type_predicate_entailment(tcx, impl_ty, sp, trait_ty, impl_trait_ref)?;
1806 check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
1810 /// The equivalent of [compare_method_predicate_entailment], but for associated types
1811 /// instead of associated functions.
1812 fn compare_type_predicate_entailment<'tcx>(
1814 impl_ty: &ty::AssocItem,
1816 trait_ty: &ty::AssocItem,
1817 impl_trait_ref: ty::TraitRef<'tcx>,
1818 ) -> Result<(), ErrorGuaranteed> {
1819 let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1820 let trait_to_impl_substs =
1821 impl_substs.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.substs);
1823 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1824 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1826 check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
1828 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1830 if impl_ty_own_bounds.is_empty() {
1831 // Nothing to check.
1835 // This `HirId` should be used for the `body_id` field on each
1836 // `ObligationCause` (and the `FnCtxt`). This is what
1837 // `regionck_item` expects.
1838 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1839 debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1841 // The predicates declared by the impl definition, the trait and the
1842 // associated type in the trait are assumed.
1843 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1844 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1847 .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1849 debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1851 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1852 let param_env = ty::ParamEnv::new(
1853 tcx.intern_predicates(&hybrid_preds.predicates),
1855 hir::Constness::NotConst,
1857 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
1858 let infcx = tcx.infer_ctxt().build();
1859 let ocx = ObligationCtxt::new(&infcx);
1861 debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1863 assert_eq!(impl_ty_own_bounds.predicates.len(), impl_ty_own_bounds.spans.len());
1864 for (span, predicate) in std::iter::zip(impl_ty_own_bounds.spans, impl_ty_own_bounds.predicates)
1866 let cause = ObligationCause::misc(span, impl_ty_hir_id);
1867 let predicate = ocx.normalize(&cause, param_env, predicate);
1869 let cause = ObligationCause::new(
1872 ObligationCauseCode::CompareImplItemObligation {
1873 impl_item_def_id: impl_ty.def_id.expect_local(),
1874 trait_item_def_id: trait_ty.def_id,
1878 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
1881 // Check that all obligations are satisfied by the implementation's
1883 let errors = ocx.select_all_or_error();
1884 if !errors.is_empty() {
1885 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
1886 return Err(reported);
1889 // Finally, resolve all regions. This catches wily misuses of
1890 // lifetime parameters.
1891 let outlives_environment = OutlivesEnvironment::new(param_env);
1892 infcx.err_ctxt().check_region_obligations_and_report_errors(
1893 impl_ty.def_id.expect_local(),
1894 &outlives_environment,
1900 /// Validate that `ProjectionCandidate`s created for this associated type will
1905 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1907 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1908 /// impl is well-formed we have to prove `S: Copy`.
1910 /// For default associated types the normalization is not possible (the value
1911 /// from the impl could be overridden). We also can't normalize generic
1912 /// associated types (yet) because they contain bound parameters.
1913 #[instrument(level = "debug", skip(tcx))]
1914 pub(super) fn check_type_bounds<'tcx>(
1916 trait_ty: &ty::AssocItem,
1917 impl_ty: &ty::AssocItem,
1919 impl_trait_ref: ty::TraitRef<'tcx>,
1920 ) -> Result<(), ErrorGuaranteed> {
1923 // impl<A, B> Foo<u32> for (A, B) {
1927 // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1928 // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1929 // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1930 // the *trait* with the generic associated type parameters (as bound vars).
1932 // A note regarding the use of bound vars here:
1933 // Imagine as an example
1936 // type Member<C: Eq>;
1939 // impl Family for VecFamily {
1940 // type Member<C: Eq> = i32;
1943 // Here, we would generate
1945 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1947 // when we really would like to generate
1949 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1951 // But, this is probably fine, because although the first clause can be used with types C that
1952 // do not implement Eq, for it to cause some kind of problem, there would have to be a
1953 // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1954 // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1955 // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1956 // the trait (notably, that X: Eq and T: Family).
1957 let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1958 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1959 if let Some(def_id) = defs.parent {
1960 let parent_defs = tcx.generics_of(def_id);
1961 InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1962 tcx.mk_param_from_def(param)
1965 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1966 smallvec::SmallVec::with_capacity(defs.count());
1967 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1968 GenericParamDefKind::Type { .. } => {
1969 let kind = ty::BoundTyKind::Param(param.name);
1970 let bound_var = ty::BoundVariableKind::Ty(kind);
1971 bound_vars.push(bound_var);
1972 tcx.mk_ty(ty::Bound(
1974 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1978 GenericParamDefKind::Lifetime => {
1979 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1980 let bound_var = ty::BoundVariableKind::Region(kind);
1981 bound_vars.push(bound_var);
1982 tcx.mk_region(ty::ReLateBound(
1984 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1988 GenericParamDefKind::Const { .. } => {
1989 let bound_var = ty::BoundVariableKind::Const;
1990 bound_vars.push(bound_var);
1992 ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_usize(bound_vars.len() - 1)),
1993 tcx.type_of(param.def_id),
1998 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
1999 let impl_ty_substs = tcx.intern_substs(&substs);
2000 let container_id = impl_ty.container_id(tcx);
2002 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
2003 let impl_ty_value = tcx.type_of(impl_ty.def_id);
2005 let param_env = tcx.param_env(impl_ty.def_id);
2007 // When checking something like
2009 // trait X { type Y: PartialEq<<Self as X>::Y> }
2010 // impl X for T { default type Y = S; }
2012 // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
2013 // we want <T as X>::Y to normalize to S. This is valid because we are
2014 // checking the default value specifically here. Add this equality to the
2015 // ParamEnv for normalization specifically.
2016 let normalize_param_env = {
2017 let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
2018 match impl_ty_value.kind() {
2019 ty::Alias(ty::Projection, proj)
2020 if proj.def_id == trait_ty.def_id && proj.substs == rebased_substs =>
2022 // Don't include this predicate if the projected type is
2023 // exactly the same as the projection. This can occur in
2024 // (somewhat dubious) code like this:
2026 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
2028 _ => predicates.push(
2029 ty::Binder::bind_with_vars(
2030 ty::ProjectionPredicate {
2031 projection_ty: tcx.mk_alias_ty(trait_ty.def_id, rebased_substs),
2032 term: impl_ty_value.into(),
2040 tcx.intern_predicates(&predicates),
2042 param_env.constness(),
2045 debug!(?normalize_param_env);
2047 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
2048 let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
2049 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
2051 let infcx = tcx.infer_ctxt().build();
2052 let ocx = ObligationCtxt::new(&infcx);
2054 let assumed_wf_types =
2055 ocx.assumed_wf_types(param_env, impl_ty_span, impl_ty.def_id.expect_local());
2057 let normalize_cause = ObligationCause::new(
2060 ObligationCauseCode::CheckAssociatedTypeBounds {
2061 impl_item_def_id: impl_ty.def_id.expect_local(),
2062 trait_item_def_id: trait_ty.def_id,
2065 let mk_cause = |span: Span| {
2066 let code = if span.is_dummy() {
2067 traits::ItemObligation(trait_ty.def_id)
2069 traits::BindingObligation(trait_ty.def_id, span)
2071 ObligationCause::new(impl_ty_span, impl_ty_hir_id, code)
2074 let obligations = tcx
2075 .bound_explicit_item_bounds(trait_ty.def_id)
2076 .subst_iter_copied(tcx, rebased_substs)
2077 .map(|(concrete_ty_bound, span)| {
2078 debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
2079 traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2082 debug!("check_type_bounds: item_bounds={:?}", obligations);
2084 for mut obligation in util::elaborate_obligations(tcx, obligations) {
2085 let normalized_predicate =
2086 ocx.normalize(&normalize_cause, normalize_param_env, obligation.predicate);
2087 debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
2088 obligation.predicate = normalized_predicate;
2090 ocx.register_obligation(obligation);
2092 // Check that all obligations are satisfied by the implementation's
2094 let errors = ocx.select_all_or_error();
2095 if !errors.is_empty() {
2096 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
2097 return Err(reported);
2100 // Finally, resolve all regions. This catches wily misuses of
2101 // lifetime parameters.
2102 let implied_bounds = infcx.implied_bounds_tys(param_env, impl_ty_hir_id, assumed_wf_types);
2103 let outlives_environment =
2104 OutlivesEnvironment::with_bounds(param_env, Some(&infcx), implied_bounds);
2106 infcx.err_ctxt().check_region_obligations_and_report_errors(
2107 impl_ty.def_id.expect_local(),
2108 &outlives_environment,
2114 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
2115 match impl_item.kind {
2116 ty::AssocKind::Const => "const",
2117 ty::AssocKind::Fn => "method",
2118 ty::AssocKind::Type => "type",