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();
620 tcx.impl_trait_ref(impl_m.impl_container(tcx).unwrap()).unwrap().subst_identity();
621 let param_env = tcx.param_env(def_id);
623 // First, check a few of the same things as `compare_impl_method`,
624 // just so we don't ICE during substitution later.
625 compare_number_of_generics(tcx, impl_m, trait_m, tcx.hir().span_if_local(impl_m.def_id), true)?;
626 compare_generic_param_kinds(tcx, impl_m, trait_m, true)?;
627 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, true)?;
629 let trait_to_impl_substs = impl_trait_ref.substs;
631 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
632 let return_span = tcx.hir().fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
633 let cause = ObligationCause::new(
636 ObligationCauseCode::CompareImplItemObligation {
637 impl_item_def_id: impl_m.def_id.expect_local(),
638 trait_item_def_id: trait_m.def_id,
643 // Create mapping from impl to placeholder.
644 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
646 // Create mapping from trait to placeholder.
647 let trait_to_placeholder_substs =
648 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
650 let infcx = &tcx.infer_ctxt().build();
651 let ocx = ObligationCtxt::new(infcx);
653 // Normalize the impl signature with fresh variables for lifetime inference.
654 let norm_cause = ObligationCause::misc(return_span, impl_m_hir_id);
655 let impl_sig = ocx.normalize(
658 infcx.replace_bound_vars_with_fresh_vars(
660 infer::HigherRankedType,
661 tcx.fn_sig(impl_m.def_id),
664 impl_sig.error_reported()?;
665 let impl_return_ty = impl_sig.output();
667 // Normalize the trait signature with liberated bound vars, passing it through
668 // the ImplTraitInTraitCollector, which gathers all of the RPITITs and replaces
669 // them with inference variables.
670 // We will use these inference variables to collect the hidden types of RPITITs.
671 let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_hir_id);
672 let unnormalized_trait_sig = tcx
673 .liberate_late_bound_regions(
675 tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs),
677 .fold_with(&mut collector);
678 let trait_sig = ocx.normalize(&norm_cause, param_env, unnormalized_trait_sig);
679 trait_sig.error_reported()?;
680 let trait_return_ty = trait_sig.output();
682 let wf_tys = FxIndexSet::from_iter(
683 unnormalized_trait_sig.inputs_and_output.iter().chain(trait_sig.inputs_and_output.iter()),
686 match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
689 let mut diag = struct_span_err!(
693 "method `{}` has an incompatible return type for trait",
697 infcx.err_ctxt().note_type_err(
700 hir.get_if_local(impl_m.def_id)
701 .and_then(|node| node.fn_decl())
702 .map(|decl| (decl.output.span(), "return type in trait".to_owned())),
703 Some(infer::ValuePairs::Terms(ExpectedFound {
704 expected: trait_return_ty.into(),
705 found: impl_return_ty.into(),
711 return Err(diag.emit());
715 debug!(?trait_sig, ?impl_sig, "equating function signatures");
717 // Unify the whole function signature. We need to do this to fully infer
718 // the lifetimes of the return type, but do this after unifying just the
719 // return types, since we want to avoid duplicating errors from
720 // `compare_method_predicate_entailment`.
721 match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
724 // This function gets called during `compare_method_predicate_entailment` when normalizing a
725 // signature that contains RPITIT. When the method signatures don't match, we have to
726 // emit an error now because `compare_method_predicate_entailment` will not report the error
727 // when normalization fails.
728 let emitted = report_trait_method_mismatch(
732 (trait_m, trait_sig),
740 // Check that all obligations are satisfied by the implementation's
742 let errors = ocx.select_all_or_error();
743 if !errors.is_empty() {
744 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
745 return Err(reported);
748 // Finally, resolve all regions. This catches wily misuses of
749 // lifetime parameters.
750 let outlives_environment = OutlivesEnvironment::with_bounds(
753 infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys),
755 infcx.err_ctxt().check_region_obligations_and_report_errors(
756 impl_m.def_id.expect_local(),
757 &outlives_environment,
760 let mut collected_tys = FxHashMap::default();
761 for (def_id, (ty, substs)) in collector.types {
762 match infcx.fully_resolve(ty) {
764 // `ty` contains free regions that we created earlier while liberating the
765 // trait fn signature. However, projection normalization expects `ty` to
766 // contains `def_id`'s early-bound regions.
767 let id_substs = InternalSubsts::identity_for_item(tcx, def_id);
768 debug!(?id_substs, ?substs);
769 let map: FxHashMap<ty::GenericArg<'tcx>, ty::GenericArg<'tcx>> =
770 std::iter::zip(substs, id_substs).collect();
773 // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound
774 // region substs that are synthesized during AST lowering. These are substs
775 // that are appended to the parent substs (trait and trait method). However,
776 // we're trying to infer the unsubstituted type value of the RPITIT inside
777 // the *impl*, so we can later use the impl's method substs to normalize
778 // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`).
780 // Due to the design of RPITITs, during AST lowering, we have no idea that
781 // an impl method corresponds to a trait method with RPITITs in it. Therefore,
782 // we don't have a list of early-bound region substs for the RPITIT in the impl.
783 // Since early region parameters are index-based, we can't just rebase these
784 // (trait method) early-bound region substs onto the impl, and there's no
785 // guarantee that the indices from the trait substs and impl substs line up.
786 // So to fix this, we subtract the number of trait substs and add the number of
787 // impl substs to *renumber* these early-bound regions to their corresponding
788 // indices in the impl's substitutions list.
790 // Also, we only need to account for a difference in trait and impl substs,
791 // since we previously enforce that the trait method and impl method have the
793 let num_trait_substs = trait_to_impl_substs.len();
794 let num_impl_substs = tcx.generics_of(impl_m.container_id(tcx)).params.len();
795 let ty = tcx.fold_regions(ty, |region, _| {
796 match region.kind() {
797 // Remap all free regions, which correspond to late-bound regions in the function.
799 // Remap early-bound regions as long as they don't come from the `impl` itself.
800 ty::ReEarlyBound(ebr) if tcx.parent(ebr.def_id) != impl_m.container_id(tcx) => {}
803 let Some(ty::ReEarlyBound(e)) = map.get(®ion.into()).map(|r| r.expect_region().kind())
809 "expected ReFree to map to ReEarlyBound"
811 return tcx.lifetimes.re_static;
813 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
816 index: (e.index as usize - num_trait_substs + num_impl_substs) as u32,
820 collected_tys.insert(def_id, ty);
823 let reported = tcx.sess.delay_span_bug(
825 format!("could not fully resolve: {ty} => {err:?}"),
827 collected_tys.insert(def_id, tcx.ty_error_with_guaranteed(reported));
832 Ok(&*tcx.arena.alloc(collected_tys))
835 struct ImplTraitInTraitCollector<'a, 'tcx> {
836 ocx: &'a ObligationCtxt<'a, 'tcx>,
837 types: FxHashMap<DefId, (Ty<'tcx>, ty::SubstsRef<'tcx>)>,
839 param_env: ty::ParamEnv<'tcx>,
843 impl<'a, 'tcx> ImplTraitInTraitCollector<'a, 'tcx> {
845 ocx: &'a ObligationCtxt<'a, 'tcx>,
847 param_env: ty::ParamEnv<'tcx>,
850 ImplTraitInTraitCollector { ocx, types: FxHashMap::default(), span, param_env, body_id }
854 impl<'tcx> TypeFolder<'tcx> for ImplTraitInTraitCollector<'_, 'tcx> {
855 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
859 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
860 if let ty::Alias(ty::Projection, proj) = ty.kind()
861 && self.tcx().def_kind(proj.def_id) == DefKind::ImplTraitPlaceholder
863 if let Some((ty, _)) = self.types.get(&proj.def_id) {
866 //FIXME(RPITIT): Deny nested RPITIT in substs too
867 if proj.substs.has_escaping_bound_vars() {
868 bug!("FIXME(RPITIT): error here");
870 // Replace with infer var
871 let infer_ty = self.ocx.infcx.next_ty_var(TypeVariableOrigin {
873 kind: TypeVariableOriginKind::MiscVariable,
875 self.types.insert(proj.def_id, (infer_ty, proj.substs));
876 // Recurse into bounds
877 for (pred, pred_span) in self.tcx().bound_explicit_item_bounds(proj.def_id).subst_iter_copied(self.tcx(), proj.substs) {
878 let pred = pred.fold_with(self);
879 let pred = self.ocx.normalize(
880 &ObligationCause::misc(self.span, self.body_id),
885 self.ocx.register_obligation(traits::Obligation::new(
887 ObligationCause::new(
890 ObligationCauseCode::BindingObligation(proj.def_id, pred_span),
898 ty.super_fold_with(self)
903 fn report_trait_method_mismatch<'tcx>(
904 infcx: &InferCtxt<'tcx>,
905 mut cause: ObligationCause<'tcx>,
906 terr: TypeError<'tcx>,
907 (trait_m, trait_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
908 (impl_m, impl_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
909 impl_trait_ref: ty::TraitRef<'tcx>,
910 ) -> ErrorGuaranteed {
912 let (impl_err_span, trait_err_span) =
913 extract_spans_for_error_reporting(&infcx, terr, &cause, impl_m, trait_m);
915 let mut diag = struct_span_err!(
919 "method `{}` has an incompatible type for trait",
923 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
924 if trait_m.fn_has_self_parameter =>
926 let ty = trait_sig.inputs()[0];
927 let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty()) {
928 ExplicitSelf::ByValue => "self".to_owned(),
929 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
930 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
931 _ => format!("self: {ty}"),
934 // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
935 // span points only at the type `Box<Self`>, but we want to cover the whole
936 // argument pattern and type.
937 let span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
938 ImplItemKind::Fn(ref sig, body) => tcx
940 .body_param_names(body)
941 .zip(sig.decl.inputs.iter())
942 .map(|(param, ty)| param.span.to(ty.span))
944 .unwrap_or(impl_err_span),
945 _ => bug!("{:?} is not a method", impl_m),
948 diag.span_suggestion(
950 "change the self-receiver type to match the trait",
952 Applicability::MachineApplicable,
955 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
956 if trait_sig.inputs().len() == *i {
957 // Suggestion to change output type. We do not suggest in `async` functions
958 // to avoid complex logic or incorrect output.
959 match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
960 ImplItemKind::Fn(ref sig, _) if !sig.header.asyncness.is_async() => {
961 let msg = "change the output type to match the trait";
962 let ap = Applicability::MachineApplicable;
963 match sig.decl.output {
964 hir::FnRetTy::DefaultReturn(sp) => {
965 let sugg = format!("-> {} ", trait_sig.output());
966 diag.span_suggestion_verbose(sp, msg, sugg, ap);
968 hir::FnRetTy::Return(hir_ty) => {
969 let sugg = trait_sig.output();
970 diag.span_suggestion(hir_ty.span, msg, sugg, ap);
976 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
977 diag.span_suggestion(
979 "change the parameter type to match the trait",
981 Applicability::MachineApplicable,
988 cause.span = impl_err_span;
989 infcx.err_ctxt().note_type_err(
992 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
993 Some(infer::ValuePairs::Sigs(ExpectedFound { expected: trait_sig, found: impl_sig })),
1002 fn check_region_bounds_on_impl_item<'tcx>(
1004 impl_m: &ty::AssocItem,
1005 trait_m: &ty::AssocItem,
1007 ) -> Result<(), ErrorGuaranteed> {
1008 let impl_generics = tcx.generics_of(impl_m.def_id);
1009 let impl_params = impl_generics.own_counts().lifetimes;
1011 let trait_generics = tcx.generics_of(trait_m.def_id);
1012 let trait_params = trait_generics.own_counts().lifetimes;
1015 "check_region_bounds_on_impl_item: \
1016 trait_generics={:?} \
1017 impl_generics={:?}",
1018 trait_generics, impl_generics
1021 // Must have same number of early-bound lifetime parameters.
1022 // Unfortunately, if the user screws up the bounds, then this
1023 // will change classification between early and late. E.g.,
1024 // if in trait we have `<'a,'b:'a>`, and in impl we just have
1025 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
1026 // in trait but 0 in the impl. But if we report "expected 2
1027 // but found 0" it's confusing, because it looks like there
1028 // are zero. Since I don't quite know how to phrase things at
1029 // the moment, give a kind of vague error message.
1030 if trait_params != impl_params {
1033 .get_generics(impl_m.def_id.expect_local())
1034 .expect("expected impl item to have generics or else we can't compare them")
1037 let mut generics_span = None;
1038 let mut bounds_span = vec![];
1039 let mut where_span = None;
1040 if let Some(trait_node) = tcx.hir().get_if_local(trait_m.def_id)
1041 && let Some(trait_generics) = trait_node.generics()
1043 generics_span = Some(trait_generics.span);
1044 // FIXME: we could potentially look at the impl's bounds to not point at bounds that
1045 // *are* present in the impl.
1046 for p in trait_generics.predicates {
1047 if let hir::WherePredicate::BoundPredicate(pred) = p {
1048 for b in pred.bounds {
1049 if let hir::GenericBound::Outlives(lt) = b {
1050 bounds_span.push(lt.ident.span);
1055 if let Some(impl_node) = tcx.hir().get_if_local(impl_m.def_id)
1056 && let Some(impl_generics) = impl_node.generics()
1058 let mut impl_bounds = 0;
1059 for p in impl_generics.predicates {
1060 if let hir::WherePredicate::BoundPredicate(pred) = p {
1061 for b in pred.bounds {
1062 if let hir::GenericBound::Outlives(_) = b {
1068 if impl_bounds == bounds_span.len() {
1069 bounds_span = vec![];
1070 } else if impl_generics.has_where_clause_predicates {
1071 where_span = Some(impl_generics.where_clause_span);
1077 .create_err(LifetimesOrBoundsMismatchOnTrait {
1079 item_kind: assoc_item_kind_str(impl_m),
1080 ident: impl_m.ident(tcx),
1085 .emit_unless(delay);
1086 return Err(reported);
1092 #[instrument(level = "debug", skip(infcx))]
1093 fn extract_spans_for_error_reporting<'tcx>(
1094 infcx: &infer::InferCtxt<'tcx>,
1095 terr: TypeError<'_>,
1096 cause: &ObligationCause<'tcx>,
1097 impl_m: &ty::AssocItem,
1098 trait_m: &ty::AssocItem,
1099 ) -> (Span, Option<Span>) {
1100 let tcx = infcx.tcx;
1101 let mut impl_args = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
1102 ImplItemKind::Fn(ref sig, _) => {
1103 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1105 _ => bug!("{:?} is not a method", impl_m),
1108 trait_m.def_id.as_local().map(|def_id| match tcx.hir().expect_trait_item(def_id).kind {
1109 TraitItemKind::Fn(ref sig, _) => {
1110 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1112 _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
1116 TypeError::ArgumentMutability(i) => {
1117 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1119 TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1120 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1122 _ => (cause.span(), tcx.hir().span_if_local(trait_m.def_id)),
1126 fn compare_self_type<'tcx>(
1128 impl_m: &ty::AssocItem,
1130 trait_m: &ty::AssocItem,
1131 impl_trait_ref: ty::TraitRef<'tcx>,
1132 ) -> Result<(), ErrorGuaranteed> {
1133 // Try to give more informative error messages about self typing
1134 // mismatches. Note that any mismatch will also be detected
1135 // below, where we construct a canonical function type that
1136 // includes the self parameter as a normal parameter. It's just
1137 // that the error messages you get out of this code are a bit more
1138 // inscrutable, particularly for cases where one method has no
1141 let self_string = |method: &ty::AssocItem| {
1142 let untransformed_self_ty = match method.container {
1143 ty::ImplContainer => impl_trait_ref.self_ty(),
1144 ty::TraitContainer => tcx.types.self_param,
1146 let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
1147 let param_env = ty::ParamEnv::reveal_all();
1149 let infcx = tcx.infer_ctxt().build();
1150 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1151 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
1152 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
1153 ExplicitSelf::ByValue => "self".to_owned(),
1154 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
1155 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
1156 _ => format!("self: {self_arg_ty}"),
1160 match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
1161 (false, false) | (true, true) => {}
1164 let self_descr = self_string(impl_m);
1165 let mut err = struct_span_err!(
1169 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1173 err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
1174 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1175 err.span_label(span, format!("trait method declared without `{self_descr}`"));
1177 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1179 let reported = err.emit();
1180 return Err(reported);
1184 let self_descr = self_string(trait_m);
1185 let mut err = struct_span_err!(
1189 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1193 err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
1194 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1195 err.span_label(span, format!("`{self_descr}` used in trait"));
1197 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1199 let reported = err.emit();
1200 return Err(reported);
1207 /// Checks that the number of generics on a given assoc item in a trait impl is the same
1208 /// as the number of generics on the respective assoc item in the trait definition.
1210 /// For example this code emits the errors in the following code:
1217 /// impl Trait for () {
1220 /// type Assoc = u32;
1225 /// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
1226 /// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
1227 /// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
1228 fn compare_number_of_generics<'tcx>(
1230 impl_: &ty::AssocItem,
1231 trait_: &ty::AssocItem,
1232 trait_span: Option<Span>,
1234 ) -> Result<(), ErrorGuaranteed> {
1235 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1236 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1238 // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
1239 // in `compare_generic_param_kinds` which will give a nicer error message than something like:
1240 // "expected 1 type parameter, found 0 type parameters"
1241 if (trait_own_counts.types + trait_own_counts.consts)
1242 == (impl_own_counts.types + impl_own_counts.consts)
1248 ("type", trait_own_counts.types, impl_own_counts.types),
1249 ("const", trait_own_counts.consts, impl_own_counts.consts),
1252 let item_kind = assoc_item_kind_str(impl_);
1254 let mut err_occurred = None;
1255 for (kind, trait_count, impl_count) in matchings {
1256 if impl_count != trait_count {
1257 let arg_spans = |kind: ty::AssocKind, generics: &hir::Generics<'_>| {
1258 let mut spans = generics
1261 .filter(|p| match p.kind {
1262 hir::GenericParamKind::Lifetime {
1263 kind: hir::LifetimeParamKind::Elided,
1265 // A fn can have an arbitrary number of extra elided lifetimes for the
1267 !matches!(kind, ty::AssocKind::Fn)
1272 .collect::<Vec<Span>>();
1273 if spans.is_empty() {
1274 spans = vec![generics.span]
1278 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1279 let trait_item = tcx.hir().expect_trait_item(def_id);
1280 let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics);
1281 let impl_trait_spans: Vec<Span> = trait_item
1285 .filter_map(|p| match p.kind {
1286 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1290 (Some(arg_spans), impl_trait_spans)
1292 (trait_span.map(|s| vec![s]), vec![])
1295 let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local());
1296 let impl_item_impl_trait_spans: Vec<Span> = impl_item
1300 .filter_map(|p| match p.kind {
1301 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1305 let spans = arg_spans(impl_.kind, impl_item.generics);
1306 let span = spans.first().copied();
1308 let mut err = tcx.sess.struct_span_err_with_code(
1311 "{} `{}` has {} {kind} parameter{} but its trait \
1312 declaration has {} {kind} parameter{}",
1316 pluralize!(impl_count),
1318 pluralize!(trait_count),
1321 DiagnosticId::Error("E0049".into()),
1324 let mut suffix = None;
1326 if let Some(spans) = trait_spans {
1327 let mut spans = spans.iter();
1328 if let Some(span) = spans.next() {
1332 "expected {} {} parameter{}",
1335 pluralize!(trait_count),
1340 err.span_label(*span, "");
1343 suffix = Some(format!(", expected {trait_count}"));
1346 if let Some(span) = span {
1350 "found {} {} parameter{}{}",
1353 pluralize!(impl_count),
1354 suffix.unwrap_or_else(String::new),
1359 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1360 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1363 let reported = err.emit_unless(delay);
1364 err_occurred = Some(reported);
1368 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1371 fn compare_number_of_method_arguments<'tcx>(
1373 impl_m: &ty::AssocItem,
1375 trait_m: &ty::AssocItem,
1376 trait_item_span: Option<Span>,
1377 ) -> Result<(), ErrorGuaranteed> {
1378 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1379 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1380 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
1381 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
1382 if trait_number_args != impl_number_args {
1383 let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
1384 match tcx.hir().expect_trait_item(def_id).kind {
1385 TraitItemKind::Fn(ref trait_m_sig, _) => {
1386 let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
1387 if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
1391 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1397 _ => bug!("{:?} is not a method", impl_m),
1402 let impl_span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
1403 ImplItemKind::Fn(ref impl_m_sig, _) => {
1404 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
1405 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
1409 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1415 _ => bug!("{:?} is not a method", impl_m),
1417 let mut err = struct_span_err!(
1421 "method `{}` has {} but the declaration in trait `{}` has {}",
1423 potentially_plural_count(impl_number_args, "parameter"),
1424 tcx.def_path_str(trait_m.def_id),
1427 if let Some(trait_span) = trait_span {
1431 "trait requires {}",
1432 potentially_plural_count(trait_number_args, "parameter")
1436 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1441 "expected {}, found {}",
1442 potentially_plural_count(trait_number_args, "parameter"),
1446 let reported = err.emit();
1447 return Err(reported);
1453 fn compare_synthetic_generics<'tcx>(
1455 impl_m: &ty::AssocItem,
1456 trait_m: &ty::AssocItem,
1457 ) -> Result<(), ErrorGuaranteed> {
1458 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
1459 // 1. Better messages for the span labels
1460 // 2. Explanation as to what is going on
1461 // If we get here, we already have the same number of generics, so the zip will
1463 let mut error_found = None;
1464 let impl_m_generics = tcx.generics_of(impl_m.def_id);
1465 let trait_m_generics = tcx.generics_of(trait_m.def_id);
1466 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
1467 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1468 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1470 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
1471 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1472 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1474 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1475 iter::zip(impl_m_type_params, trait_m_type_params)
1477 if impl_synthetic != trait_synthetic {
1478 let impl_def_id = impl_def_id.expect_local();
1479 let impl_span = tcx.def_span(impl_def_id);
1480 let trait_span = tcx.def_span(trait_def_id);
1481 let mut err = struct_span_err!(
1485 "method `{}` has incompatible signature for trait",
1488 err.span_label(trait_span, "declaration in trait here");
1489 match (impl_synthetic, trait_synthetic) {
1490 // The case where the impl method uses `impl Trait` but the trait method uses
1491 // explicit generics
1493 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1495 // try taking the name from the trait impl
1496 // FIXME: this is obviously suboptimal since the name can already be used
1497 // as another generic argument
1498 let new_name = tcx.opt_item_name(trait_def_id)?;
1499 let trait_m = trait_m.def_id.as_local()?;
1500 let trait_m = tcx.hir().expect_trait_item(trait_m);
1502 let impl_m = impl_m.def_id.as_local()?;
1503 let impl_m = tcx.hir().expect_impl_item(impl_m);
1505 // in case there are no generics, take the spot between the function name
1506 // and the opening paren of the argument list
1507 let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1508 // in case there are generics, just replace them
1510 impl_m.generics.span.substitute_dummy(new_generics_span);
1511 // replace with the generics from the trait
1513 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1515 err.multipart_suggestion(
1516 "try changing the `impl Trait` argument to a generic parameter",
1518 // replace `impl Trait` with `T`
1519 (impl_span, new_name.to_string()),
1520 // replace impl method generics with trait method generics
1521 // This isn't quite right, as users might have changed the names
1522 // of the generics, but it works for the common case
1523 (generics_span, new_generics),
1525 Applicability::MaybeIncorrect,
1530 // The case where the trait method uses `impl Trait`, but the impl method uses
1531 // explicit generics.
1533 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1535 let impl_m = impl_m.def_id.as_local()?;
1536 let impl_m = tcx.hir().expect_impl_item(impl_m);
1537 let input_tys = match impl_m.kind {
1538 hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
1539 _ => unreachable!(),
1541 struct Visitor(Option<Span>, hir::def_id::LocalDefId);
1542 impl<'v> intravisit::Visitor<'v> for Visitor {
1543 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
1544 intravisit::walk_ty(self, ty);
1545 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
1547 && let Res::Def(DefKind::TyParam, def_id) = path.res
1548 && def_id == self.1.to_def_id()
1550 self.0 = Some(ty.span);
1554 let mut visitor = Visitor(None, impl_def_id);
1555 for ty in input_tys {
1556 intravisit::Visitor::visit_ty(&mut visitor, ty);
1558 let span = visitor.0?;
1560 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
1561 let bounds = bounds.first()?.span().to(bounds.last()?.span());
1562 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
1564 err.multipart_suggestion(
1565 "try removing the generic parameter and using `impl Trait` instead",
1567 // delete generic parameters
1568 (impl_m.generics.span, String::new()),
1569 // replace param usage with `impl Trait`
1570 (span, format!("impl {bounds}")),
1572 Applicability::MaybeIncorrect,
1577 _ => unreachable!(),
1579 let reported = err.emit();
1580 error_found = Some(reported);
1583 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
1586 /// Checks that all parameters in the generics of a given assoc item in a trait impl have
1587 /// the same kind as the respective generic parameter in the trait def.
1589 /// For example all 4 errors in the following code are emitted here:
1592 /// fn foo<const N: u8>();
1593 /// type bar<const N: u8>;
1594 /// fn baz<const N: u32>();
1598 /// impl Foo for () {
1599 /// fn foo<const N: u64>() {}
1601 /// type bar<const N: u64> {}
1605 /// type blah<const N: i64> = u32;
1610 /// This function does not handle lifetime parameters
1611 fn compare_generic_param_kinds<'tcx>(
1613 impl_item: &ty::AssocItem,
1614 trait_item: &ty::AssocItem,
1616 ) -> Result<(), ErrorGuaranteed> {
1617 assert_eq!(impl_item.kind, trait_item.kind);
1619 let ty_const_params_of = |def_id| {
1620 tcx.generics_of(def_id).params.iter().filter(|param| {
1623 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1628 for (param_impl, param_trait) in
1629 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1631 use GenericParamDefKind::*;
1632 if match (¶m_impl.kind, ¶m_trait.kind) {
1633 (Const { .. }, Const { .. })
1634 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1638 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1639 // this is exhaustive so that anyone adding new generic param kinds knows
1640 // to make sure this error is reported for them.
1641 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1642 (Lifetime { .. }, _) | (_, Lifetime { .. }) => unreachable!(),
1644 let param_impl_span = tcx.def_span(param_impl.def_id);
1645 let param_trait_span = tcx.def_span(param_trait.def_id);
1647 let mut err = struct_span_err!(
1651 "{} `{}` has an incompatible generic parameter for trait `{}`",
1652 assoc_item_kind_str(&impl_item),
1654 &tcx.def_path_str(tcx.parent(trait_item.def_id))
1657 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
1659 format!("{} const parameter of type `{}`", prefix, tcx.type_of(param.def_id))
1661 Type { .. } => format!("{} type parameter", prefix),
1662 Lifetime { .. } => unreachable!(),
1665 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
1666 err.span_label(trait_header_span, "");
1667 err.span_label(param_trait_span, make_param_message("expected", param_trait));
1669 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1670 err.span_label(impl_header_span, "");
1671 err.span_label(param_impl_span, make_param_message("found", param_impl));
1673 let reported = err.emit_unless(delay);
1674 return Err(reported);
1681 /// Use `tcx.compare_impl_const` instead
1682 pub(super) fn compare_impl_const_raw(
1684 (impl_const_item_def, trait_const_item_def): (LocalDefId, DefId),
1685 ) -> Result<(), ErrorGuaranteed> {
1686 let impl_const_item = tcx.associated_item(impl_const_item_def);
1687 let trait_const_item = tcx.associated_item(trait_const_item_def);
1688 let impl_trait_ref =
1689 tcx.impl_trait_ref(impl_const_item.container_id(tcx)).unwrap().subst_identity();
1690 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
1692 let impl_c_span = tcx.def_span(impl_const_item_def.to_def_id());
1694 let infcx = tcx.infer_ctxt().build();
1695 let param_env = tcx.param_env(impl_const_item_def.to_def_id());
1696 let ocx = ObligationCtxt::new(&infcx);
1698 // The below is for the most part highly similar to the procedure
1699 // for methods above. It is simpler in many respects, especially
1700 // because we shouldn't really have to deal with lifetimes or
1701 // predicates. In fact some of this should probably be put into
1702 // shared functions because of DRY violations...
1703 let trait_to_impl_substs = impl_trait_ref.substs;
1705 // Create a parameter environment that represents the implementation's
1707 let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_const_item_def);
1709 // Compute placeholder form of impl and trait const tys.
1710 let impl_ty = tcx.type_of(impl_const_item_def.to_def_id());
1711 let trait_ty = tcx.bound_type_of(trait_const_item_def).subst(tcx, trait_to_impl_substs);
1712 let mut cause = ObligationCause::new(
1715 ObligationCauseCode::CompareImplItemObligation {
1716 impl_item_def_id: impl_const_item_def,
1717 trait_item_def_id: trait_const_item_def,
1718 kind: impl_const_item.kind,
1722 // There is no "body" here, so just pass dummy id.
1723 let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
1725 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1727 let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
1729 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1731 let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
1733 if let Err(terr) = err {
1735 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1739 // Locate the Span containing just the type of the offending impl
1740 match tcx.hir().expect_impl_item(impl_const_item_def).kind {
1741 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
1742 _ => bug!("{:?} is not a impl const", impl_const_item),
1745 let mut diag = struct_span_err!(
1749 "implemented const `{}` has an incompatible type for trait",
1750 trait_const_item.name
1753 let trait_c_span = trait_const_item_def.as_local().map(|trait_c_def_id| {
1754 // Add a label to the Span containing just the type of the const
1755 match tcx.hir().expect_trait_item(trait_c_def_id).kind {
1756 TraitItemKind::Const(ref ty, _) => ty.span,
1757 _ => bug!("{:?} is not a trait const", trait_const_item),
1761 infcx.err_ctxt().note_type_err(
1764 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1765 Some(infer::ValuePairs::Terms(ExpectedFound {
1766 expected: trait_ty.into(),
1767 found: impl_ty.into(),
1773 return Err(diag.emit());
1776 // Check that all obligations are satisfied by the implementation's
1778 let errors = ocx.select_all_or_error();
1779 if !errors.is_empty() {
1780 return Err(infcx.err_ctxt().report_fulfillment_errors(&errors, None));
1783 let outlives_environment = OutlivesEnvironment::new(param_env);
1786 .check_region_obligations_and_report_errors(impl_const_item_def, &outlives_environment)?;
1790 pub(super) fn compare_impl_ty<'tcx>(
1792 impl_ty: &ty::AssocItem,
1794 trait_ty: &ty::AssocItem,
1795 impl_trait_ref: ty::TraitRef<'tcx>,
1796 trait_item_span: Option<Span>,
1798 debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1800 let _: Result<(), ErrorGuaranteed> = (|| {
1801 compare_number_of_generics(tcx, impl_ty, trait_ty, trait_item_span, false)?;
1803 compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
1805 let sp = tcx.def_span(impl_ty.def_id);
1806 compare_type_predicate_entailment(tcx, impl_ty, sp, trait_ty, impl_trait_ref)?;
1808 check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
1812 /// The equivalent of [compare_method_predicate_entailment], but for associated types
1813 /// instead of associated functions.
1814 fn compare_type_predicate_entailment<'tcx>(
1816 impl_ty: &ty::AssocItem,
1818 trait_ty: &ty::AssocItem,
1819 impl_trait_ref: ty::TraitRef<'tcx>,
1820 ) -> Result<(), ErrorGuaranteed> {
1821 let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1822 let trait_to_impl_substs =
1823 impl_substs.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.substs);
1825 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1826 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1828 check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
1830 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1832 if impl_ty_own_bounds.is_empty() {
1833 // Nothing to check.
1837 // This `HirId` should be used for the `body_id` field on each
1838 // `ObligationCause` (and the `FnCtxt`). This is what
1839 // `regionck_item` expects.
1840 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1841 debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1843 // The predicates declared by the impl definition, the trait and the
1844 // associated type in the trait are assumed.
1845 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1846 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1849 .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1851 debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1853 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1854 let param_env = ty::ParamEnv::new(
1855 tcx.intern_predicates(&hybrid_preds.predicates),
1857 hir::Constness::NotConst,
1859 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
1860 let infcx = tcx.infer_ctxt().build();
1861 let ocx = ObligationCtxt::new(&infcx);
1863 debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1865 assert_eq!(impl_ty_own_bounds.predicates.len(), impl_ty_own_bounds.spans.len());
1866 for (span, predicate) in std::iter::zip(impl_ty_own_bounds.spans, impl_ty_own_bounds.predicates)
1868 let cause = ObligationCause::misc(span, impl_ty_hir_id);
1869 let predicate = ocx.normalize(&cause, param_env, predicate);
1871 let cause = ObligationCause::new(
1874 ObligationCauseCode::CompareImplItemObligation {
1875 impl_item_def_id: impl_ty.def_id.expect_local(),
1876 trait_item_def_id: trait_ty.def_id,
1880 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
1883 // Check that all obligations are satisfied by the implementation's
1885 let errors = ocx.select_all_or_error();
1886 if !errors.is_empty() {
1887 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
1888 return Err(reported);
1891 // Finally, resolve all regions. This catches wily misuses of
1892 // lifetime parameters.
1893 let outlives_environment = OutlivesEnvironment::new(param_env);
1894 infcx.err_ctxt().check_region_obligations_and_report_errors(
1895 impl_ty.def_id.expect_local(),
1896 &outlives_environment,
1902 /// Validate that `ProjectionCandidate`s created for this associated type will
1907 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1909 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1910 /// impl is well-formed we have to prove `S: Copy`.
1912 /// For default associated types the normalization is not possible (the value
1913 /// from the impl could be overridden). We also can't normalize generic
1914 /// associated types (yet) because they contain bound parameters.
1915 #[instrument(level = "debug", skip(tcx))]
1916 pub(super) fn check_type_bounds<'tcx>(
1918 trait_ty: &ty::AssocItem,
1919 impl_ty: &ty::AssocItem,
1921 impl_trait_ref: ty::TraitRef<'tcx>,
1922 ) -> Result<(), ErrorGuaranteed> {
1925 // impl<A, B> Foo<u32> for (A, B) {
1929 // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1930 // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1931 // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1932 // the *trait* with the generic associated type parameters (as bound vars).
1934 // A note regarding the use of bound vars here:
1935 // Imagine as an example
1938 // type Member<C: Eq>;
1941 // impl Family for VecFamily {
1942 // type Member<C: Eq> = i32;
1945 // Here, we would generate
1947 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1949 // when we really would like to generate
1951 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1953 // But, this is probably fine, because although the first clause can be used with types C that
1954 // do not implement Eq, for it to cause some kind of problem, there would have to be a
1955 // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1956 // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1957 // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1958 // the trait (notably, that X: Eq and T: Family).
1959 let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1960 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1961 if let Some(def_id) = defs.parent {
1962 let parent_defs = tcx.generics_of(def_id);
1963 InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1964 tcx.mk_param_from_def(param)
1967 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1968 smallvec::SmallVec::with_capacity(defs.count());
1969 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1970 GenericParamDefKind::Type { .. } => {
1971 let kind = ty::BoundTyKind::Param(param.name);
1972 let bound_var = ty::BoundVariableKind::Ty(kind);
1973 bound_vars.push(bound_var);
1974 tcx.mk_ty(ty::Bound(
1976 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1980 GenericParamDefKind::Lifetime => {
1981 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1982 let bound_var = ty::BoundVariableKind::Region(kind);
1983 bound_vars.push(bound_var);
1984 tcx.mk_region(ty::ReLateBound(
1986 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1990 GenericParamDefKind::Const { .. } => {
1991 let bound_var = ty::BoundVariableKind::Const;
1992 bound_vars.push(bound_var);
1994 ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_usize(bound_vars.len() - 1)),
1995 tcx.type_of(param.def_id),
2000 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
2001 let impl_ty_substs = tcx.intern_substs(&substs);
2002 let container_id = impl_ty.container_id(tcx);
2004 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
2005 let impl_ty_value = tcx.type_of(impl_ty.def_id);
2007 let param_env = tcx.param_env(impl_ty.def_id);
2009 // When checking something like
2011 // trait X { type Y: PartialEq<<Self as X>::Y> }
2012 // impl X for T { default type Y = S; }
2014 // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
2015 // we want <T as X>::Y to normalize to S. This is valid because we are
2016 // checking the default value specifically here. Add this equality to the
2017 // ParamEnv for normalization specifically.
2018 let normalize_param_env = {
2019 let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
2020 match impl_ty_value.kind() {
2021 ty::Alias(ty::Projection, proj)
2022 if proj.def_id == trait_ty.def_id && proj.substs == rebased_substs =>
2024 // Don't include this predicate if the projected type is
2025 // exactly the same as the projection. This can occur in
2026 // (somewhat dubious) code like this:
2028 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
2030 _ => predicates.push(
2031 ty::Binder::bind_with_vars(
2032 ty::ProjectionPredicate {
2033 projection_ty: tcx.mk_alias_ty(trait_ty.def_id, rebased_substs),
2034 term: impl_ty_value.into(),
2042 tcx.intern_predicates(&predicates),
2044 param_env.constness(),
2047 debug!(?normalize_param_env);
2049 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
2050 let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
2051 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
2053 let infcx = tcx.infer_ctxt().build();
2054 let ocx = ObligationCtxt::new(&infcx);
2056 let assumed_wf_types =
2057 ocx.assumed_wf_types(param_env, impl_ty_span, impl_ty.def_id.expect_local());
2059 let normalize_cause = ObligationCause::new(
2062 ObligationCauseCode::CheckAssociatedTypeBounds {
2063 impl_item_def_id: impl_ty.def_id.expect_local(),
2064 trait_item_def_id: trait_ty.def_id,
2067 let mk_cause = |span: Span| {
2068 let code = if span.is_dummy() {
2069 traits::ItemObligation(trait_ty.def_id)
2071 traits::BindingObligation(trait_ty.def_id, span)
2073 ObligationCause::new(impl_ty_span, impl_ty_hir_id, code)
2076 let obligations = tcx
2077 .bound_explicit_item_bounds(trait_ty.def_id)
2078 .subst_iter_copied(tcx, rebased_substs)
2079 .map(|(concrete_ty_bound, span)| {
2080 debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
2081 traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2084 debug!("check_type_bounds: item_bounds={:?}", obligations);
2086 for mut obligation in util::elaborate_obligations(tcx, obligations) {
2087 let normalized_predicate =
2088 ocx.normalize(&normalize_cause, normalize_param_env, obligation.predicate);
2089 debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
2090 obligation.predicate = normalized_predicate;
2092 ocx.register_obligation(obligation);
2094 // Check that all obligations are satisfied by the implementation's
2096 let errors = ocx.select_all_or_error();
2097 if !errors.is_empty() {
2098 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
2099 return Err(reported);
2102 // Finally, resolve all regions. This catches wily misuses of
2103 // lifetime parameters.
2104 let implied_bounds = infcx.implied_bounds_tys(param_env, impl_ty_hir_id, assumed_wf_types);
2105 let outlives_environment =
2106 OutlivesEnvironment::with_bounds(param_env, Some(&infcx), implied_bounds);
2108 infcx.err_ctxt().check_region_obligations_and_report_errors(
2109 impl_ty.def_id.expect_local(),
2110 &outlives_environment,
2116 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
2117 match impl_item.kind {
2118 ty::AssocKind::Const => "const",
2119 ty::AssocKind::Fn => "method",
2120 ty::AssocKind::Type => "type",