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.
212 hybrid_preds.predicates.extend(
214 .instantiate_own(tcx, trait_to_placeholder_substs)
215 .map(|(predicate, _)| predicate),
218 // Construct trait parameter environment and then shift it into the placeholder viewpoint.
219 // The key step here is to update the caller_bounds's predicates to be
220 // the new hybrid bounds we computed.
221 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
222 let param_env = ty::ParamEnv::new(
223 tcx.intern_predicates(&hybrid_preds.predicates),
225 hir::Constness::NotConst,
227 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
229 let infcx = &tcx.infer_ctxt().build();
230 let ocx = ObligationCtxt::new(infcx);
232 debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds());
234 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs);
235 for (predicate, span) in impl_m_own_bounds {
236 let normalize_cause = traits::ObligationCause::misc(span, impl_m_hir_id);
237 let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
239 let cause = ObligationCause::new(
242 ObligationCauseCode::CompareImplItemObligation {
243 impl_item_def_id: impl_m.def_id.expect_local(),
244 trait_item_def_id: trait_m.def_id,
248 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
251 // We now need to check that the signature of the impl method is
252 // compatible with that of the trait method. We do this by
253 // checking that `impl_fty <: trait_fty`.
255 // FIXME. Unfortunately, this doesn't quite work right now because
256 // associated type normalization is not integrated into subtype
257 // checks. For the comparison to be valid, we need to
258 // normalize the associated types in the impl/trait methods
259 // first. However, because function types bind regions, just
260 // calling `normalize_associated_types_in` would have no effect on
261 // any associated types appearing in the fn arguments or return
264 // Compute placeholder form of impl and trait method tys.
267 let mut wf_tys = FxIndexSet::default();
269 let unnormalized_impl_sig = infcx.replace_bound_vars_with_fresh_vars(
271 infer::HigherRankedType,
272 tcx.fn_sig(impl_m.def_id),
274 let unnormalized_impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(unnormalized_impl_sig));
276 let norm_cause = ObligationCause::misc(impl_m_span, impl_m_hir_id);
277 let impl_sig = ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig);
278 debug!("compare_impl_method: impl_fty={:?}", impl_sig);
280 let trait_sig = tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs);
281 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
283 // Next, add all inputs and output as well-formed tys. Importantly,
284 // we have to do this before normalization, since the normalized ty may
285 // not contain the input parameters. See issue #87748.
286 wf_tys.extend(trait_sig.inputs_and_output.iter());
287 let trait_sig = ocx.normalize(&norm_cause, param_env, trait_sig);
288 // We also have to add the normalized trait signature
289 // as we don't normalize during implied bounds computation.
290 wf_tys.extend(trait_sig.inputs_and_output.iter());
291 let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));
293 debug!("compare_impl_method: trait_fty={:?}", trait_fty);
295 // FIXME: We'd want to keep more accurate spans than "the method signature" when
296 // processing the comparison between the trait and impl fn, but we sadly lose them
297 // and point at the whole signature when a trait bound or specific input or output
298 // type would be more appropriate. In other places we have a `Vec<Span>`
299 // corresponding to their `Vec<Predicate>`, but we don't have that here.
300 // Fixing this would improve the output of test `issue-83765.rs`.
301 let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
303 if let Err(terr) = result {
304 debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
306 let emitted = report_trait_method_mismatch(
310 (trait_m, trait_sig),
317 if check_implied_wf == CheckImpliedWfMode::Check {
318 // We need to check that the impl's args are well-formed given
319 // the hybrid param-env (impl + trait method where-clauses).
320 ocx.register_obligation(traits::Obligation::new(
322 ObligationCause::dummy(),
324 ty::Binder::dummy(ty::PredicateKind::WellFormed(unnormalized_impl_fty.into())),
328 // Check that all obligations are satisfied by the implementation's
330 let errors = ocx.select_all_or_error();
331 if !errors.is_empty() {
332 match check_implied_wf {
333 CheckImpliedWfMode::Check => {
334 return compare_method_predicate_entailment(
340 CheckImpliedWfMode::Skip,
343 // If the skip-mode was successful, emit a lint.
344 emit_implied_wf_lint(infcx.tcx, impl_m, impl_m_hir_id, vec![]);
347 CheckImpliedWfMode::Skip => {
348 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
349 return Err(reported);
354 // Finally, resolve all regions. This catches wily misuses of
355 // lifetime parameters.
356 let outlives_env = OutlivesEnvironment::with_bounds(
359 infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys.clone()),
361 infcx.process_registered_region_obligations(
362 outlives_env.region_bound_pairs(),
363 outlives_env.param_env,
365 let errors = infcx.resolve_regions(&outlives_env);
366 if !errors.is_empty() {
367 // FIXME(compiler-errors): This can be simplified when IMPLIED_BOUNDS_ENTAILMENT
368 // becomes a hard error (i.e. ideally we'd just call `resolve_regions_and_report_errors`
369 match check_implied_wf {
370 CheckImpliedWfMode::Check => {
371 return compare_method_predicate_entailment(
377 CheckImpliedWfMode::Skip,
380 let bad_args = extract_bad_args_for_implies_lint(
383 (trait_m, trait_sig),
384 // Unnormalized impl sig corresponds to the HIR types written
385 (impl_m, unnormalized_impl_sig),
388 // If the skip-mode was successful, emit a lint.
389 emit_implied_wf_lint(tcx, impl_m, impl_m_hir_id, bad_args);
392 CheckImpliedWfMode::Skip => {
393 if infcx.tainted_by_errors().is_none() {
394 infcx.err_ctxt().report_region_errors(impl_m.def_id.expect_local(), &errors);
398 .delay_span_bug(rustc_span::DUMMY_SP, "error should have been emitted"));
406 fn extract_bad_args_for_implies_lint<'tcx>(
408 errors: &[infer::RegionResolutionError<'tcx>],
409 (trait_m, trait_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
410 (impl_m, impl_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
412 ) -> Vec<(Span, Option<String>)> {
413 let mut blame_generics = vec![];
414 for error in errors {
415 // Look for the subregion origin that contains an input/output type
416 let origin = match error {
417 infer::RegionResolutionError::ConcreteFailure(o, ..) => o,
418 infer::RegionResolutionError::GenericBoundFailure(o, ..) => o,
419 infer::RegionResolutionError::SubSupConflict(_, _, o, ..) => o,
420 infer::RegionResolutionError::UpperBoundUniverseConflict(.., o, _) => o,
422 // Extract (possible) input/output types from origin
424 infer::SubregionOrigin::Subtype(trace) => {
425 if let Some((a, b)) = trace.values.ty() {
426 blame_generics.extend([a, b]);
429 infer::SubregionOrigin::RelateParamBound(_, ty, _) => blame_generics.push(*ty),
430 infer::SubregionOrigin::ReferenceOutlivesReferent(ty, _) => blame_generics.push(*ty),
435 let fn_decl = tcx.hir().fn_decl_by_hir_id(hir_id).unwrap();
436 let opt_ret_ty = match fn_decl.output {
437 hir::FnRetTy::DefaultReturn(_) => None,
438 hir::FnRetTy::Return(ty) => Some(ty),
441 // Map late-bound regions from trait to impl, so the names are right.
442 let mapping = std::iter::zip(
443 tcx.fn_sig(trait_m.def_id).bound_vars(),
444 tcx.fn_sig(impl_m.def_id).bound_vars(),
446 .filter_map(|(impl_bv, trait_bv)| {
447 if let ty::BoundVariableKind::Region(impl_bv) = impl_bv
448 && let ty::BoundVariableKind::Region(trait_bv) = trait_bv
450 Some((impl_bv, trait_bv))
457 // For each arg, see if it was in the "blame" of any of the region errors.
458 // If so, then try to produce a suggestion to replace the argument type with
459 // one from the trait.
460 let mut bad_args = vec![];
461 for (idx, (ty, hir_ty)) in
462 std::iter::zip(impl_sig.inputs_and_output, fn_decl.inputs.iter().chain(opt_ret_ty))
465 let expected_ty = trait_sig.inputs_and_output[idx]
466 .fold_with(&mut RemapLateBound { tcx, mapping: &mapping });
467 if blame_generics.iter().any(|blame| ty.contains(*blame)) {
468 let expected_ty_sugg = expected_ty.to_string();
471 // Only suggest something if it actually changed.
472 (expected_ty_sugg != ty.to_string()).then_some(expected_ty_sugg),
480 struct RemapLateBound<'a, 'tcx> {
482 mapping: &'a FxHashMap<ty::BoundRegionKind, ty::BoundRegionKind>,
485 impl<'tcx> TypeFolder<'tcx> for RemapLateBound<'_, 'tcx> {
486 fn tcx(&self) -> TyCtxt<'tcx> {
490 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
491 if let ty::ReFree(fr) = *r {
492 self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
495 .get(&fr.bound_region)
497 .unwrap_or(fr.bound_region),
506 fn emit_implied_wf_lint<'tcx>(
508 impl_m: &ty::AssocItem,
510 bad_args: Vec<(Span, Option<String>)>,
512 let span: MultiSpan = if bad_args.is_empty() {
513 tcx.def_span(impl_m.def_id).into()
515 bad_args.iter().map(|(span, _)| *span).collect::<Vec<_>>().into()
517 tcx.struct_span_lint_hir(
518 rustc_session::lint::builtin::IMPLIED_BOUNDS_ENTAILMENT,
521 "impl method assumes more implied bounds than the corresponding trait method",
523 let bad_args: Vec<_> =
524 bad_args.into_iter().filter_map(|(span, sugg)| Some((span, sugg?))).collect();
525 if !bad_args.is_empty() {
526 lint.multipart_suggestion(
528 "replace {} type{} to make the impl signature compatible",
529 pluralize!("this", bad_args.len()),
530 pluralize!(bad_args.len())
533 Applicability::MaybeIncorrect,
541 #[derive(Debug, PartialEq, Eq)]
542 enum CheckImpliedWfMode {
543 /// Checks implied well-formedness of the impl method. If it fails, we will
544 /// re-check with `Skip`, and emit a lint if it succeeds.
546 /// Skips checking implied well-formedness of the impl method, but will emit
547 /// a lint if the `compare_method_predicate_entailment` succeeded. This means that
548 /// the reason that we had failed earlier during `Check` was due to the impl
549 /// having stronger requirements than the trait.
553 fn compare_asyncness<'tcx>(
555 impl_m: &ty::AssocItem,
557 trait_m: &ty::AssocItem,
558 trait_item_span: Option<Span>,
559 ) -> Result<(), ErrorGuaranteed> {
560 if tcx.asyncness(trait_m.def_id) == hir::IsAsync::Async {
561 match tcx.fn_sig(impl_m.def_id).skip_binder().output().kind() {
562 ty::Alias(ty::Opaque, ..) => {
563 // allow both `async fn foo()` and `fn foo() -> impl Future`
566 // We don't know if it's ok, but at least it's already an error.
569 return Err(tcx.sess.emit_err(crate::errors::AsyncTraitImplShouldBeAsync {
571 method_name: trait_m.name,
581 /// Given a method def-id in an impl, compare the method signature of the impl
582 /// against the trait that it's implementing. In doing so, infer the hidden types
583 /// that this method's signature provides to satisfy each return-position `impl Trait`
584 /// in the trait signature.
586 /// The method is also responsible for making sure that the hidden types for each
587 /// RPITIT actually satisfy the bounds of the `impl Trait`, i.e. that if we infer
588 /// `impl Trait = Foo`, that `Foo: Trait` holds.
590 /// For example, given the sample code:
593 /// #![feature(return_position_impl_trait_in_trait)]
595 /// use std::ops::Deref;
598 /// fn bar() -> impl Deref<Target = impl Sized>;
599 /// // ^- RPITIT #1 ^- RPITIT #2
602 /// impl Foo for () {
603 /// fn bar() -> Box<String> { Box::new(String::new()) }
607 /// The hidden types for the RPITITs in `bar` would be inferred to:
608 /// * `impl Deref` (RPITIT #1) = `Box<String>`
609 /// * `impl Sized` (RPITIT #2) = `String`
611 /// The relationship between these two types is straightforward in this case, but
612 /// may be more tenuously connected via other `impl`s and normalization rules for
613 /// cases of more complicated nested RPITITs.
614 #[instrument(skip(tcx), level = "debug", ret)]
615 pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
618 ) -> Result<&'tcx FxHashMap<DefId, Ty<'tcx>>, ErrorGuaranteed> {
619 let impl_m = tcx.opt_associated_item(def_id).unwrap();
620 let trait_m = tcx.opt_associated_item(impl_m.trait_item_def_id.unwrap()).unwrap();
622 tcx.impl_trait_ref(impl_m.impl_container(tcx).unwrap()).unwrap().subst_identity();
623 let param_env = tcx.param_env(def_id);
625 // First, check a few of the same things as `compare_impl_method`,
626 // just so we don't ICE during substitution later.
627 compare_number_of_generics(tcx, impl_m, trait_m, tcx.hir().span_if_local(impl_m.def_id), true)?;
628 compare_generic_param_kinds(tcx, impl_m, trait_m, true)?;
629 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, true)?;
631 let trait_to_impl_substs = impl_trait_ref.substs;
633 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
634 let return_span = tcx.hir().fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
635 let cause = ObligationCause::new(
638 ObligationCauseCode::CompareImplItemObligation {
639 impl_item_def_id: impl_m.def_id.expect_local(),
640 trait_item_def_id: trait_m.def_id,
645 // Create mapping from impl to placeholder.
646 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
648 // Create mapping from trait to placeholder.
649 let trait_to_placeholder_substs =
650 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
652 let infcx = &tcx.infer_ctxt().build();
653 let ocx = ObligationCtxt::new(infcx);
655 // Normalize the impl signature with fresh variables for lifetime inference.
656 let norm_cause = ObligationCause::misc(return_span, impl_m_hir_id);
657 let impl_sig = ocx.normalize(
660 infcx.replace_bound_vars_with_fresh_vars(
662 infer::HigherRankedType,
663 tcx.fn_sig(impl_m.def_id),
666 impl_sig.error_reported()?;
667 let impl_return_ty = impl_sig.output();
669 // Normalize the trait signature with liberated bound vars, passing it through
670 // the ImplTraitInTraitCollector, which gathers all of the RPITITs and replaces
671 // them with inference variables.
672 // We will use these inference variables to collect the hidden types of RPITITs.
673 let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_hir_id);
674 let unnormalized_trait_sig = tcx
675 .liberate_late_bound_regions(
677 tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs),
679 .fold_with(&mut collector);
680 let trait_sig = ocx.normalize(&norm_cause, param_env, unnormalized_trait_sig);
681 trait_sig.error_reported()?;
682 let trait_return_ty = trait_sig.output();
684 let wf_tys = FxIndexSet::from_iter(
685 unnormalized_trait_sig.inputs_and_output.iter().chain(trait_sig.inputs_and_output.iter()),
688 match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
691 let mut diag = struct_span_err!(
695 "method `{}` has an incompatible return type for trait",
699 infcx.err_ctxt().note_type_err(
702 hir.get_if_local(impl_m.def_id)
703 .and_then(|node| node.fn_decl())
704 .map(|decl| (decl.output.span(), "return type in trait".to_owned())),
705 Some(infer::ValuePairs::Terms(ExpectedFound {
706 expected: trait_return_ty.into(),
707 found: impl_return_ty.into(),
713 return Err(diag.emit());
717 debug!(?trait_sig, ?impl_sig, "equating function signatures");
719 // Unify the whole function signature. We need to do this to fully infer
720 // the lifetimes of the return type, but do this after unifying just the
721 // return types, since we want to avoid duplicating errors from
722 // `compare_method_predicate_entailment`.
723 match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
726 // This function gets called during `compare_method_predicate_entailment` when normalizing a
727 // signature that contains RPITIT. When the method signatures don't match, we have to
728 // emit an error now because `compare_method_predicate_entailment` will not report the error
729 // when normalization fails.
730 let emitted = report_trait_method_mismatch(
734 (trait_m, trait_sig),
742 // Check that all obligations are satisfied by the implementation's
744 let errors = ocx.select_all_or_error();
745 if !errors.is_empty() {
746 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
747 return Err(reported);
750 // Finally, resolve all regions. This catches wily misuses of
751 // lifetime parameters.
752 let outlives_environment = OutlivesEnvironment::with_bounds(
755 infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys),
757 infcx.err_ctxt().check_region_obligations_and_report_errors(
758 impl_m.def_id.expect_local(),
759 &outlives_environment,
762 let mut collected_tys = FxHashMap::default();
763 for (def_id, (ty, substs)) in collector.types {
764 match infcx.fully_resolve(ty) {
766 // `ty` contains free regions that we created earlier while liberating the
767 // trait fn signature. However, projection normalization expects `ty` to
768 // contains `def_id`'s early-bound regions.
769 let id_substs = InternalSubsts::identity_for_item(tcx, def_id);
770 debug!(?id_substs, ?substs);
771 let map: FxHashMap<ty::GenericArg<'tcx>, ty::GenericArg<'tcx>> =
772 std::iter::zip(substs, id_substs).collect();
775 // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound
776 // region substs that are synthesized during AST lowering. These are substs
777 // that are appended to the parent substs (trait and trait method). However,
778 // we're trying to infer the unsubstituted type value of the RPITIT inside
779 // the *impl*, so we can later use the impl's method substs to normalize
780 // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`).
782 // Due to the design of RPITITs, during AST lowering, we have no idea that
783 // an impl method corresponds to a trait method with RPITITs in it. Therefore,
784 // we don't have a list of early-bound region substs for the RPITIT in the impl.
785 // Since early region parameters are index-based, we can't just rebase these
786 // (trait method) early-bound region substs onto the impl, and there's no
787 // guarantee that the indices from the trait substs and impl substs line up.
788 // So to fix this, we subtract the number of trait substs and add the number of
789 // impl substs to *renumber* these early-bound regions to their corresponding
790 // indices in the impl's substitutions list.
792 // Also, we only need to account for a difference in trait and impl substs,
793 // since we previously enforce that the trait method and impl method have the
795 let num_trait_substs = trait_to_impl_substs.len();
796 let num_impl_substs = tcx.generics_of(impl_m.container_id(tcx)).params.len();
797 let ty = tcx.fold_regions(ty, |region, _| {
798 match region.kind() {
799 // Remap all free regions, which correspond to late-bound regions in the function.
801 // Remap early-bound regions as long as they don't come from the `impl` itself.
802 ty::ReEarlyBound(ebr) if tcx.parent(ebr.def_id) != impl_m.container_id(tcx) => {}
805 let Some(ty::ReEarlyBound(e)) = map.get(®ion.into()).map(|r| r.expect_region().kind())
811 "expected ReFree to map to ReEarlyBound"
813 return tcx.lifetimes.re_static;
815 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
818 index: (e.index as usize - num_trait_substs + num_impl_substs) as u32,
822 collected_tys.insert(def_id, ty);
825 let reported = tcx.sess.delay_span_bug(
827 format!("could not fully resolve: {ty} => {err:?}"),
829 collected_tys.insert(def_id, tcx.ty_error_with_guaranteed(reported));
834 Ok(&*tcx.arena.alloc(collected_tys))
837 struct ImplTraitInTraitCollector<'a, 'tcx> {
838 ocx: &'a ObligationCtxt<'a, 'tcx>,
839 types: FxHashMap<DefId, (Ty<'tcx>, ty::SubstsRef<'tcx>)>,
841 param_env: ty::ParamEnv<'tcx>,
845 impl<'a, 'tcx> ImplTraitInTraitCollector<'a, 'tcx> {
847 ocx: &'a ObligationCtxt<'a, 'tcx>,
849 param_env: ty::ParamEnv<'tcx>,
852 ImplTraitInTraitCollector { ocx, types: FxHashMap::default(), span, param_env, body_id }
856 impl<'tcx> TypeFolder<'tcx> for ImplTraitInTraitCollector<'_, 'tcx> {
857 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
861 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
862 if let ty::Alias(ty::Projection, proj) = ty.kind()
863 && self.tcx().def_kind(proj.def_id) == DefKind::ImplTraitPlaceholder
865 if let Some((ty, _)) = self.types.get(&proj.def_id) {
868 //FIXME(RPITIT): Deny nested RPITIT in substs too
869 if proj.substs.has_escaping_bound_vars() {
870 bug!("FIXME(RPITIT): error here");
872 // Replace with infer var
873 let infer_ty = self.ocx.infcx.next_ty_var(TypeVariableOrigin {
875 kind: TypeVariableOriginKind::MiscVariable,
877 self.types.insert(proj.def_id, (infer_ty, proj.substs));
878 // Recurse into bounds
879 for (pred, pred_span) in self.tcx().bound_explicit_item_bounds(proj.def_id).subst_iter_copied(self.tcx(), proj.substs) {
880 let pred = pred.fold_with(self);
881 let pred = self.ocx.normalize(
882 &ObligationCause::misc(self.span, self.body_id),
887 self.ocx.register_obligation(traits::Obligation::new(
889 ObligationCause::new(
892 ObligationCauseCode::BindingObligation(proj.def_id, pred_span),
900 ty.super_fold_with(self)
905 fn report_trait_method_mismatch<'tcx>(
906 infcx: &InferCtxt<'tcx>,
907 mut cause: ObligationCause<'tcx>,
908 terr: TypeError<'tcx>,
909 (trait_m, trait_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
910 (impl_m, impl_sig): (&ty::AssocItem, ty::FnSig<'tcx>),
911 impl_trait_ref: ty::TraitRef<'tcx>,
912 ) -> ErrorGuaranteed {
914 let (impl_err_span, trait_err_span) =
915 extract_spans_for_error_reporting(&infcx, terr, &cause, impl_m, trait_m);
917 let mut diag = struct_span_err!(
921 "method `{}` has an incompatible type for trait",
925 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
926 if trait_m.fn_has_self_parameter =>
928 let ty = trait_sig.inputs()[0];
929 let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty()) {
930 ExplicitSelf::ByValue => "self".to_owned(),
931 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
932 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
933 _ => format!("self: {ty}"),
936 // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
937 // span points only at the type `Box<Self`>, but we want to cover the whole
938 // argument pattern and type.
939 let span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
940 ImplItemKind::Fn(ref sig, body) => tcx
942 .body_param_names(body)
943 .zip(sig.decl.inputs.iter())
944 .map(|(param, ty)| param.span.to(ty.span))
946 .unwrap_or(impl_err_span),
947 _ => bug!("{:?} is not a method", impl_m),
950 diag.span_suggestion(
952 "change the self-receiver type to match the trait",
954 Applicability::MachineApplicable,
957 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
958 if trait_sig.inputs().len() == *i {
959 // Suggestion to change output type. We do not suggest in `async` functions
960 // to avoid complex logic or incorrect output.
961 match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
962 ImplItemKind::Fn(ref sig, _) if !sig.header.asyncness.is_async() => {
963 let msg = "change the output type to match the trait";
964 let ap = Applicability::MachineApplicable;
965 match sig.decl.output {
966 hir::FnRetTy::DefaultReturn(sp) => {
967 let sugg = format!("-> {} ", trait_sig.output());
968 diag.span_suggestion_verbose(sp, msg, sugg, ap);
970 hir::FnRetTy::Return(hir_ty) => {
971 let sugg = trait_sig.output();
972 diag.span_suggestion(hir_ty.span, msg, sugg, ap);
978 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
979 diag.span_suggestion(
981 "change the parameter type to match the trait",
983 Applicability::MachineApplicable,
990 cause.span = impl_err_span;
991 infcx.err_ctxt().note_type_err(
994 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
995 Some(infer::ValuePairs::Sigs(ExpectedFound { expected: trait_sig, found: impl_sig })),
1004 fn check_region_bounds_on_impl_item<'tcx>(
1006 impl_m: &ty::AssocItem,
1007 trait_m: &ty::AssocItem,
1009 ) -> Result<(), ErrorGuaranteed> {
1010 let impl_generics = tcx.generics_of(impl_m.def_id);
1011 let impl_params = impl_generics.own_counts().lifetimes;
1013 let trait_generics = tcx.generics_of(trait_m.def_id);
1014 let trait_params = trait_generics.own_counts().lifetimes;
1017 "check_region_bounds_on_impl_item: \
1018 trait_generics={:?} \
1019 impl_generics={:?}",
1020 trait_generics, impl_generics
1023 // Must have same number of early-bound lifetime parameters.
1024 // Unfortunately, if the user screws up the bounds, then this
1025 // will change classification between early and late. E.g.,
1026 // if in trait we have `<'a,'b:'a>`, and in impl we just have
1027 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
1028 // in trait but 0 in the impl. But if we report "expected 2
1029 // but found 0" it's confusing, because it looks like there
1030 // are zero. Since I don't quite know how to phrase things at
1031 // the moment, give a kind of vague error message.
1032 if trait_params != impl_params {
1035 .get_generics(impl_m.def_id.expect_local())
1036 .expect("expected impl item to have generics or else we can't compare them")
1039 let mut generics_span = None;
1040 let mut bounds_span = vec![];
1041 let mut where_span = None;
1042 if let Some(trait_node) = tcx.hir().get_if_local(trait_m.def_id)
1043 && let Some(trait_generics) = trait_node.generics()
1045 generics_span = Some(trait_generics.span);
1046 // FIXME: we could potentially look at the impl's bounds to not point at bounds that
1047 // *are* present in the impl.
1048 for p in trait_generics.predicates {
1049 if let hir::WherePredicate::BoundPredicate(pred) = p {
1050 for b in pred.bounds {
1051 if let hir::GenericBound::Outlives(lt) = b {
1052 bounds_span.push(lt.ident.span);
1057 if let Some(impl_node) = tcx.hir().get_if_local(impl_m.def_id)
1058 && let Some(impl_generics) = impl_node.generics()
1060 let mut impl_bounds = 0;
1061 for p in impl_generics.predicates {
1062 if let hir::WherePredicate::BoundPredicate(pred) = p {
1063 for b in pred.bounds {
1064 if let hir::GenericBound::Outlives(_) = b {
1070 if impl_bounds == bounds_span.len() {
1071 bounds_span = vec![];
1072 } else if impl_generics.has_where_clause_predicates {
1073 where_span = Some(impl_generics.where_clause_span);
1079 .create_err(LifetimesOrBoundsMismatchOnTrait {
1081 item_kind: assoc_item_kind_str(impl_m),
1082 ident: impl_m.ident(tcx),
1087 .emit_unless(delay);
1088 return Err(reported);
1094 #[instrument(level = "debug", skip(infcx))]
1095 fn extract_spans_for_error_reporting<'tcx>(
1096 infcx: &infer::InferCtxt<'tcx>,
1097 terr: TypeError<'_>,
1098 cause: &ObligationCause<'tcx>,
1099 impl_m: &ty::AssocItem,
1100 trait_m: &ty::AssocItem,
1101 ) -> (Span, Option<Span>) {
1102 let tcx = infcx.tcx;
1103 let mut impl_args = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
1104 ImplItemKind::Fn(ref sig, _) => {
1105 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1107 _ => bug!("{:?} is not a method", impl_m),
1110 trait_m.def_id.as_local().map(|def_id| match tcx.hir().expect_trait_item(def_id).kind {
1111 TraitItemKind::Fn(ref sig, _) => {
1112 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1114 _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
1118 TypeError::ArgumentMutability(i) => {
1119 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1121 TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1122 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1124 _ => (cause.span(), tcx.hir().span_if_local(trait_m.def_id)),
1128 fn compare_self_type<'tcx>(
1130 impl_m: &ty::AssocItem,
1132 trait_m: &ty::AssocItem,
1133 impl_trait_ref: ty::TraitRef<'tcx>,
1134 ) -> Result<(), ErrorGuaranteed> {
1135 // Try to give more informative error messages about self typing
1136 // mismatches. Note that any mismatch will also be detected
1137 // below, where we construct a canonical function type that
1138 // includes the self parameter as a normal parameter. It's just
1139 // that the error messages you get out of this code are a bit more
1140 // inscrutable, particularly for cases where one method has no
1143 let self_string = |method: &ty::AssocItem| {
1144 let untransformed_self_ty = match method.container {
1145 ty::ImplContainer => impl_trait_ref.self_ty(),
1146 ty::TraitContainer => tcx.types.self_param,
1148 let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
1149 let param_env = ty::ParamEnv::reveal_all();
1151 let infcx = tcx.infer_ctxt().build();
1152 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1153 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
1154 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
1155 ExplicitSelf::ByValue => "self".to_owned(),
1156 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
1157 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
1158 _ => format!("self: {self_arg_ty}"),
1162 match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
1163 (false, false) | (true, true) => {}
1166 let self_descr = self_string(impl_m);
1167 let mut err = struct_span_err!(
1171 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1175 err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
1176 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1177 err.span_label(span, format!("trait method declared without `{self_descr}`"));
1179 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1181 let reported = err.emit();
1182 return Err(reported);
1186 let self_descr = self_string(trait_m);
1187 let mut err = struct_span_err!(
1191 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1195 err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
1196 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1197 err.span_label(span, format!("`{self_descr}` used in trait"));
1199 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1201 let reported = err.emit();
1202 return Err(reported);
1209 /// Checks that the number of generics on a given assoc item in a trait impl is the same
1210 /// as the number of generics on the respective assoc item in the trait definition.
1212 /// For example this code emits the errors in the following code:
1219 /// impl Trait for () {
1222 /// type Assoc = u32;
1227 /// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
1228 /// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
1229 /// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
1230 fn compare_number_of_generics<'tcx>(
1232 impl_: &ty::AssocItem,
1233 trait_: &ty::AssocItem,
1234 trait_span: Option<Span>,
1236 ) -> Result<(), ErrorGuaranteed> {
1237 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1238 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1240 // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
1241 // in `compare_generic_param_kinds` which will give a nicer error message than something like:
1242 // "expected 1 type parameter, found 0 type parameters"
1243 if (trait_own_counts.types + trait_own_counts.consts)
1244 == (impl_own_counts.types + impl_own_counts.consts)
1250 ("type", trait_own_counts.types, impl_own_counts.types),
1251 ("const", trait_own_counts.consts, impl_own_counts.consts),
1254 let item_kind = assoc_item_kind_str(impl_);
1256 let mut err_occurred = None;
1257 for (kind, trait_count, impl_count) in matchings {
1258 if impl_count != trait_count {
1259 let arg_spans = |kind: ty::AssocKind, generics: &hir::Generics<'_>| {
1260 let mut spans = generics
1263 .filter(|p| match p.kind {
1264 hir::GenericParamKind::Lifetime {
1265 kind: hir::LifetimeParamKind::Elided,
1267 // A fn can have an arbitrary number of extra elided lifetimes for the
1269 !matches!(kind, ty::AssocKind::Fn)
1274 .collect::<Vec<Span>>();
1275 if spans.is_empty() {
1276 spans = vec![generics.span]
1280 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1281 let trait_item = tcx.hir().expect_trait_item(def_id);
1282 let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics);
1283 let impl_trait_spans: Vec<Span> = trait_item
1287 .filter_map(|p| match p.kind {
1288 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1292 (Some(arg_spans), impl_trait_spans)
1294 (trait_span.map(|s| vec![s]), vec![])
1297 let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local());
1298 let impl_item_impl_trait_spans: Vec<Span> = impl_item
1302 .filter_map(|p| match p.kind {
1303 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1307 let spans = arg_spans(impl_.kind, impl_item.generics);
1308 let span = spans.first().copied();
1310 let mut err = tcx.sess.struct_span_err_with_code(
1313 "{} `{}` has {} {kind} parameter{} but its trait \
1314 declaration has {} {kind} parameter{}",
1318 pluralize!(impl_count),
1320 pluralize!(trait_count),
1323 DiagnosticId::Error("E0049".into()),
1326 let mut suffix = None;
1328 if let Some(spans) = trait_spans {
1329 let mut spans = spans.iter();
1330 if let Some(span) = spans.next() {
1334 "expected {} {} parameter{}",
1337 pluralize!(trait_count),
1342 err.span_label(*span, "");
1345 suffix = Some(format!(", expected {trait_count}"));
1348 if let Some(span) = span {
1352 "found {} {} parameter{}{}",
1355 pluralize!(impl_count),
1356 suffix.unwrap_or_else(String::new),
1361 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1362 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1365 let reported = err.emit_unless(delay);
1366 err_occurred = Some(reported);
1370 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1373 fn compare_number_of_method_arguments<'tcx>(
1375 impl_m: &ty::AssocItem,
1377 trait_m: &ty::AssocItem,
1378 trait_item_span: Option<Span>,
1379 ) -> Result<(), ErrorGuaranteed> {
1380 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1381 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1382 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
1383 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
1384 if trait_number_args != impl_number_args {
1385 let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
1386 match tcx.hir().expect_trait_item(def_id).kind {
1387 TraitItemKind::Fn(ref trait_m_sig, _) => {
1388 let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
1389 if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
1393 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1399 _ => bug!("{:?} is not a method", impl_m),
1404 let impl_span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
1405 ImplItemKind::Fn(ref impl_m_sig, _) => {
1406 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
1407 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
1411 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1417 _ => bug!("{:?} is not a method", impl_m),
1419 let mut err = struct_span_err!(
1423 "method `{}` has {} but the declaration in trait `{}` has {}",
1425 potentially_plural_count(impl_number_args, "parameter"),
1426 tcx.def_path_str(trait_m.def_id),
1429 if let Some(trait_span) = trait_span {
1433 "trait requires {}",
1434 potentially_plural_count(trait_number_args, "parameter")
1438 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1443 "expected {}, found {}",
1444 potentially_plural_count(trait_number_args, "parameter"),
1448 let reported = err.emit();
1449 return Err(reported);
1455 fn compare_synthetic_generics<'tcx>(
1457 impl_m: &ty::AssocItem,
1458 trait_m: &ty::AssocItem,
1459 ) -> Result<(), ErrorGuaranteed> {
1460 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
1461 // 1. Better messages for the span labels
1462 // 2. Explanation as to what is going on
1463 // If we get here, we already have the same number of generics, so the zip will
1465 let mut error_found = None;
1466 let impl_m_generics = tcx.generics_of(impl_m.def_id);
1467 let trait_m_generics = tcx.generics_of(trait_m.def_id);
1468 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
1469 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1470 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1472 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
1473 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1474 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1476 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1477 iter::zip(impl_m_type_params, trait_m_type_params)
1479 if impl_synthetic != trait_synthetic {
1480 let impl_def_id = impl_def_id.expect_local();
1481 let impl_span = tcx.def_span(impl_def_id);
1482 let trait_span = tcx.def_span(trait_def_id);
1483 let mut err = struct_span_err!(
1487 "method `{}` has incompatible signature for trait",
1490 err.span_label(trait_span, "declaration in trait here");
1491 match (impl_synthetic, trait_synthetic) {
1492 // The case where the impl method uses `impl Trait` but the trait method uses
1493 // explicit generics
1495 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1497 // try taking the name from the trait impl
1498 // FIXME: this is obviously suboptimal since the name can already be used
1499 // as another generic argument
1500 let new_name = tcx.opt_item_name(trait_def_id)?;
1501 let trait_m = trait_m.def_id.as_local()?;
1502 let trait_m = tcx.hir().expect_trait_item(trait_m);
1504 let impl_m = impl_m.def_id.as_local()?;
1505 let impl_m = tcx.hir().expect_impl_item(impl_m);
1507 // in case there are no generics, take the spot between the function name
1508 // and the opening paren of the argument list
1509 let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1510 // in case there are generics, just replace them
1512 impl_m.generics.span.substitute_dummy(new_generics_span);
1513 // replace with the generics from the trait
1515 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1517 err.multipart_suggestion(
1518 "try changing the `impl Trait` argument to a generic parameter",
1520 // replace `impl Trait` with `T`
1521 (impl_span, new_name.to_string()),
1522 // replace impl method generics with trait method generics
1523 // This isn't quite right, as users might have changed the names
1524 // of the generics, but it works for the common case
1525 (generics_span, new_generics),
1527 Applicability::MaybeIncorrect,
1532 // The case where the trait method uses `impl Trait`, but the impl method uses
1533 // explicit generics.
1535 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1537 let impl_m = impl_m.def_id.as_local()?;
1538 let impl_m = tcx.hir().expect_impl_item(impl_m);
1539 let input_tys = match impl_m.kind {
1540 hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
1541 _ => unreachable!(),
1543 struct Visitor(Option<Span>, hir::def_id::LocalDefId);
1544 impl<'v> intravisit::Visitor<'v> for Visitor {
1545 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
1546 intravisit::walk_ty(self, ty);
1547 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
1549 && let Res::Def(DefKind::TyParam, def_id) = path.res
1550 && def_id == self.1.to_def_id()
1552 self.0 = Some(ty.span);
1556 let mut visitor = Visitor(None, impl_def_id);
1557 for ty in input_tys {
1558 intravisit::Visitor::visit_ty(&mut visitor, ty);
1560 let span = visitor.0?;
1562 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
1563 let bounds = bounds.first()?.span().to(bounds.last()?.span());
1564 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
1566 err.multipart_suggestion(
1567 "try removing the generic parameter and using `impl Trait` instead",
1569 // delete generic parameters
1570 (impl_m.generics.span, String::new()),
1571 // replace param usage with `impl Trait`
1572 (span, format!("impl {bounds}")),
1574 Applicability::MaybeIncorrect,
1579 _ => unreachable!(),
1581 let reported = err.emit();
1582 error_found = Some(reported);
1585 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
1588 /// Checks that all parameters in the generics of a given assoc item in a trait impl have
1589 /// the same kind as the respective generic parameter in the trait def.
1591 /// For example all 4 errors in the following code are emitted here:
1594 /// fn foo<const N: u8>();
1595 /// type bar<const N: u8>;
1596 /// fn baz<const N: u32>();
1600 /// impl Foo for () {
1601 /// fn foo<const N: u64>() {}
1603 /// type bar<const N: u64> {}
1607 /// type blah<const N: i64> = u32;
1612 /// This function does not handle lifetime parameters
1613 fn compare_generic_param_kinds<'tcx>(
1615 impl_item: &ty::AssocItem,
1616 trait_item: &ty::AssocItem,
1618 ) -> Result<(), ErrorGuaranteed> {
1619 assert_eq!(impl_item.kind, trait_item.kind);
1621 let ty_const_params_of = |def_id| {
1622 tcx.generics_of(def_id).params.iter().filter(|param| {
1625 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1630 for (param_impl, param_trait) in
1631 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1633 use GenericParamDefKind::*;
1634 if match (¶m_impl.kind, ¶m_trait.kind) {
1635 (Const { .. }, Const { .. })
1636 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1640 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1641 // this is exhaustive so that anyone adding new generic param kinds knows
1642 // to make sure this error is reported for them.
1643 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1644 (Lifetime { .. }, _) | (_, Lifetime { .. }) => unreachable!(),
1646 let param_impl_span = tcx.def_span(param_impl.def_id);
1647 let param_trait_span = tcx.def_span(param_trait.def_id);
1649 let mut err = struct_span_err!(
1653 "{} `{}` has an incompatible generic parameter for trait `{}`",
1654 assoc_item_kind_str(&impl_item),
1656 &tcx.def_path_str(tcx.parent(trait_item.def_id))
1659 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
1661 format!("{} const parameter of type `{}`", prefix, tcx.type_of(param.def_id))
1663 Type { .. } => format!("{} type parameter", prefix),
1664 Lifetime { .. } => unreachable!(),
1667 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
1668 err.span_label(trait_header_span, "");
1669 err.span_label(param_trait_span, make_param_message("expected", param_trait));
1671 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1672 err.span_label(impl_header_span, "");
1673 err.span_label(param_impl_span, make_param_message("found", param_impl));
1675 let reported = err.emit_unless(delay);
1676 return Err(reported);
1683 /// Use `tcx.compare_impl_const` instead
1684 pub(super) fn compare_impl_const_raw(
1686 (impl_const_item_def, trait_const_item_def): (LocalDefId, DefId),
1687 ) -> Result<(), ErrorGuaranteed> {
1688 let impl_const_item = tcx.associated_item(impl_const_item_def);
1689 let trait_const_item = tcx.associated_item(trait_const_item_def);
1690 let impl_trait_ref =
1691 tcx.impl_trait_ref(impl_const_item.container_id(tcx)).unwrap().subst_identity();
1692 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
1694 let impl_c_span = tcx.def_span(impl_const_item_def.to_def_id());
1696 let infcx = tcx.infer_ctxt().build();
1697 let param_env = tcx.param_env(impl_const_item_def.to_def_id());
1698 let ocx = ObligationCtxt::new(&infcx);
1700 // The below is for the most part highly similar to the procedure
1701 // for methods above. It is simpler in many respects, especially
1702 // because we shouldn't really have to deal with lifetimes or
1703 // predicates. In fact some of this should probably be put into
1704 // shared functions because of DRY violations...
1705 let trait_to_impl_substs = impl_trait_ref.substs;
1707 // Create a parameter environment that represents the implementation's
1709 let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_const_item_def);
1711 // Compute placeholder form of impl and trait const tys.
1712 let impl_ty = tcx.type_of(impl_const_item_def.to_def_id());
1713 let trait_ty = tcx.bound_type_of(trait_const_item_def).subst(tcx, trait_to_impl_substs);
1714 let mut cause = ObligationCause::new(
1717 ObligationCauseCode::CompareImplItemObligation {
1718 impl_item_def_id: impl_const_item_def,
1719 trait_item_def_id: trait_const_item_def,
1720 kind: impl_const_item.kind,
1724 // There is no "body" here, so just pass dummy id.
1725 let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
1727 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1729 let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
1731 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1733 let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
1735 if let Err(terr) = err {
1737 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1741 // Locate the Span containing just the type of the offending impl
1742 match tcx.hir().expect_impl_item(impl_const_item_def).kind {
1743 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
1744 _ => bug!("{:?} is not a impl const", impl_const_item),
1747 let mut diag = struct_span_err!(
1751 "implemented const `{}` has an incompatible type for trait",
1752 trait_const_item.name
1755 let trait_c_span = trait_const_item_def.as_local().map(|trait_c_def_id| {
1756 // Add a label to the Span containing just the type of the const
1757 match tcx.hir().expect_trait_item(trait_c_def_id).kind {
1758 TraitItemKind::Const(ref ty, _) => ty.span,
1759 _ => bug!("{:?} is not a trait const", trait_const_item),
1763 infcx.err_ctxt().note_type_err(
1766 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1767 Some(infer::ValuePairs::Terms(ExpectedFound {
1768 expected: trait_ty.into(),
1769 found: impl_ty.into(),
1775 return Err(diag.emit());
1778 // Check that all obligations are satisfied by the implementation's
1780 let errors = ocx.select_all_or_error();
1781 if !errors.is_empty() {
1782 return Err(infcx.err_ctxt().report_fulfillment_errors(&errors, None));
1785 let outlives_environment = OutlivesEnvironment::new(param_env);
1788 .check_region_obligations_and_report_errors(impl_const_item_def, &outlives_environment)?;
1792 pub(super) fn compare_impl_ty<'tcx>(
1794 impl_ty: &ty::AssocItem,
1796 trait_ty: &ty::AssocItem,
1797 impl_trait_ref: ty::TraitRef<'tcx>,
1798 trait_item_span: Option<Span>,
1800 debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1802 let _: Result<(), ErrorGuaranteed> = (|| {
1803 compare_number_of_generics(tcx, impl_ty, trait_ty, trait_item_span, false)?;
1805 compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
1807 let sp = tcx.def_span(impl_ty.def_id);
1808 compare_type_predicate_entailment(tcx, impl_ty, sp, trait_ty, impl_trait_ref)?;
1810 check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
1814 /// The equivalent of [compare_method_predicate_entailment], but for associated types
1815 /// instead of associated functions.
1816 fn compare_type_predicate_entailment<'tcx>(
1818 impl_ty: &ty::AssocItem,
1820 trait_ty: &ty::AssocItem,
1821 impl_trait_ref: ty::TraitRef<'tcx>,
1822 ) -> Result<(), ErrorGuaranteed> {
1823 let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1824 let trait_to_impl_substs =
1825 impl_substs.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.substs);
1827 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1828 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1830 check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
1832 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1833 if impl_ty_own_bounds.len() == 0 {
1834 // Nothing to check.
1838 // This `HirId` should be used for the `body_id` field on each
1839 // `ObligationCause` (and the `FnCtxt`). This is what
1840 // `regionck_item` expects.
1841 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1842 debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1844 // The predicates declared by the impl definition, the trait and the
1845 // associated type in the trait are assumed.
1846 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1847 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1848 hybrid_preds.predicates.extend(
1850 .instantiate_own(tcx, trait_to_impl_substs)
1851 .map(|(predicate, _)| predicate),
1854 debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1856 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1857 let param_env = ty::ParamEnv::new(
1858 tcx.intern_predicates(&hybrid_preds.predicates),
1860 hir::Constness::NotConst,
1862 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
1863 let infcx = tcx.infer_ctxt().build();
1864 let ocx = ObligationCtxt::new(&infcx);
1866 debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1868 for (predicate, span) in impl_ty_own_bounds {
1869 let cause = ObligationCause::misc(span, impl_ty_hir_id);
1870 let predicate = ocx.normalize(&cause, param_env, predicate);
1872 let cause = ObligationCause::new(
1875 ObligationCauseCode::CompareImplItemObligation {
1876 impl_item_def_id: impl_ty.def_id.expect_local(),
1877 trait_item_def_id: trait_ty.def_id,
1881 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
1884 // Check that all obligations are satisfied by the implementation's
1886 let errors = ocx.select_all_or_error();
1887 if !errors.is_empty() {
1888 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
1889 return Err(reported);
1892 // Finally, resolve all regions. This catches wily misuses of
1893 // lifetime parameters.
1894 let outlives_environment = OutlivesEnvironment::new(param_env);
1895 infcx.err_ctxt().check_region_obligations_and_report_errors(
1896 impl_ty.def_id.expect_local(),
1897 &outlives_environment,
1903 /// Validate that `ProjectionCandidate`s created for this associated type will
1908 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1910 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1911 /// impl is well-formed we have to prove `S: Copy`.
1913 /// For default associated types the normalization is not possible (the value
1914 /// from the impl could be overridden). We also can't normalize generic
1915 /// associated types (yet) because they contain bound parameters.
1916 #[instrument(level = "debug", skip(tcx))]
1917 pub(super) fn check_type_bounds<'tcx>(
1919 trait_ty: &ty::AssocItem,
1920 impl_ty: &ty::AssocItem,
1922 impl_trait_ref: ty::TraitRef<'tcx>,
1923 ) -> Result<(), ErrorGuaranteed> {
1926 // impl<A, B> Foo<u32> for (A, B) {
1930 // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1931 // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1932 // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1933 // the *trait* with the generic associated type parameters (as bound vars).
1935 // A note regarding the use of bound vars here:
1936 // Imagine as an example
1939 // type Member<C: Eq>;
1942 // impl Family for VecFamily {
1943 // type Member<C: Eq> = i32;
1946 // Here, we would generate
1948 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1950 // when we really would like to generate
1952 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1954 // But, this is probably fine, because although the first clause can be used with types C that
1955 // do not implement Eq, for it to cause some kind of problem, there would have to be a
1956 // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1957 // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1958 // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1959 // the trait (notably, that X: Eq and T: Family).
1960 let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1961 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1962 if let Some(def_id) = defs.parent {
1963 let parent_defs = tcx.generics_of(def_id);
1964 InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1965 tcx.mk_param_from_def(param)
1968 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1969 smallvec::SmallVec::with_capacity(defs.count());
1970 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1971 GenericParamDefKind::Type { .. } => {
1972 let kind = ty::BoundTyKind::Param(param.name);
1973 let bound_var = ty::BoundVariableKind::Ty(kind);
1974 bound_vars.push(bound_var);
1975 tcx.mk_ty(ty::Bound(
1977 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1981 GenericParamDefKind::Lifetime => {
1982 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1983 let bound_var = ty::BoundVariableKind::Region(kind);
1984 bound_vars.push(bound_var);
1985 tcx.mk_region(ty::ReLateBound(
1987 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1991 GenericParamDefKind::Const { .. } => {
1992 let bound_var = ty::BoundVariableKind::Const;
1993 bound_vars.push(bound_var);
1995 ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_usize(bound_vars.len() - 1)),
1996 tcx.type_of(param.def_id),
2001 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
2002 let impl_ty_substs = tcx.intern_substs(&substs);
2003 let container_id = impl_ty.container_id(tcx);
2005 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
2006 let impl_ty_value = tcx.type_of(impl_ty.def_id);
2008 let param_env = tcx.param_env(impl_ty.def_id);
2010 // When checking something like
2012 // trait X { type Y: PartialEq<<Self as X>::Y> }
2013 // impl X for T { default type Y = S; }
2015 // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
2016 // we want <T as X>::Y to normalize to S. This is valid because we are
2017 // checking the default value specifically here. Add this equality to the
2018 // ParamEnv for normalization specifically.
2019 let normalize_param_env = {
2020 let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
2021 match impl_ty_value.kind() {
2022 ty::Alias(ty::Projection, proj)
2023 if proj.def_id == trait_ty.def_id && proj.substs == rebased_substs =>
2025 // Don't include this predicate if the projected type is
2026 // exactly the same as the projection. This can occur in
2027 // (somewhat dubious) code like this:
2029 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
2031 _ => predicates.push(
2032 ty::Binder::bind_with_vars(
2033 ty::ProjectionPredicate {
2034 projection_ty: tcx.mk_alias_ty(trait_ty.def_id, rebased_substs),
2035 term: impl_ty_value.into(),
2043 tcx.intern_predicates(&predicates),
2045 param_env.constness(),
2048 debug!(?normalize_param_env);
2050 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
2051 let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
2052 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
2054 let infcx = tcx.infer_ctxt().build();
2055 let ocx = ObligationCtxt::new(&infcx);
2057 let assumed_wf_types =
2058 ocx.assumed_wf_types(param_env, impl_ty_span, impl_ty.def_id.expect_local());
2060 let normalize_cause = ObligationCause::new(
2063 ObligationCauseCode::CheckAssociatedTypeBounds {
2064 impl_item_def_id: impl_ty.def_id.expect_local(),
2065 trait_item_def_id: trait_ty.def_id,
2068 let mk_cause = |span: Span| {
2069 let code = if span.is_dummy() {
2070 traits::ItemObligation(trait_ty.def_id)
2072 traits::BindingObligation(trait_ty.def_id, span)
2074 ObligationCause::new(impl_ty_span, impl_ty_hir_id, code)
2077 let obligations = tcx
2078 .bound_explicit_item_bounds(trait_ty.def_id)
2079 .subst_iter_copied(tcx, rebased_substs)
2080 .map(|(concrete_ty_bound, span)| {
2081 debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
2082 traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2085 debug!("check_type_bounds: item_bounds={:?}", obligations);
2087 for mut obligation in util::elaborate_obligations(tcx, obligations) {
2088 let normalized_predicate =
2089 ocx.normalize(&normalize_cause, normalize_param_env, obligation.predicate);
2090 debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
2091 obligation.predicate = normalized_predicate;
2093 ocx.register_obligation(obligation);
2095 // Check that all obligations are satisfied by the implementation's
2097 let errors = ocx.select_all_or_error();
2098 if !errors.is_empty() {
2099 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
2100 return Err(reported);
2103 // Finally, resolve all regions. This catches wily misuses of
2104 // lifetime parameters.
2105 let implied_bounds = infcx.implied_bounds_tys(param_env, impl_ty_hir_id, assumed_wf_types);
2106 let outlives_environment =
2107 OutlivesEnvironment::with_bounds(param_env, Some(&infcx), implied_bounds);
2109 infcx.err_ctxt().check_region_obligations_and_report_errors(
2110 impl_ty.def_id.expect_local(),
2111 &outlives_environment,
2117 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
2118 match impl_item.kind {
2119 ty::AssocKind::Const => "const",
2120 ty::AssocKind::Fn => "method",
2121 ty::AssocKind::Type => "type",