1 use crate::errors::LifetimesOrBoundsMismatchOnTrait;
2 use rustc_data_structures::stable_set::FxHashSet;
3 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, ErrorReported};
5 use rustc_hir::def::{DefKind, Res};
6 use rustc_hir::intravisit;
7 use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind};
8 use rustc_infer::infer::{self, InferOk, TyCtxtInferExt};
9 use rustc_infer::traits::util;
11 use rustc_middle::ty::error::{ExpectedFound, TypeError};
12 use rustc_middle::ty::subst::{InternalSubsts, Subst};
13 use rustc_middle::ty::util::ExplicitSelf;
14 use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt};
16 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
17 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
20 use super::{potentially_plural_count, FnCtxt, Inherited};
22 /// Checks that a method from an impl conforms to the signature of
23 /// the same method as declared in the trait.
27 /// - `impl_m`: type of the method we are checking
28 /// - `impl_m_span`: span to use for reporting errors
29 /// - `trait_m`: the method in the trait
30 /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
32 crate fn compare_impl_method<'tcx>(
34 impl_m: &ty::AssocItem,
36 trait_m: &ty::AssocItem,
37 impl_trait_ref: ty::TraitRef<'tcx>,
38 trait_item_span: Option<Span>,
40 debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref);
42 let impl_m_span = tcx.sess.source_map().guess_head_span(impl_m_span);
44 if let Err(ErrorReported) = compare_self_type(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
49 if let Err(ErrorReported) =
50 compare_number_of_generics(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
55 if let Err(ErrorReported) =
56 compare_number_of_method_arguments(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
61 if let Err(ErrorReported) = compare_synthetic_generics(tcx, impl_m, trait_m) {
65 if let Err(ErrorReported) =
66 compare_predicate_entailment(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
71 if let Err(ErrorReported) = compare_const_param_types(tcx, impl_m, trait_m, trait_item_span) {
76 fn compare_predicate_entailment<'tcx>(
78 impl_m: &ty::AssocItem,
80 trait_m: &ty::AssocItem,
81 impl_trait_ref: ty::TraitRef<'tcx>,
82 ) -> Result<(), ErrorReported> {
83 let trait_to_impl_substs = impl_trait_ref.substs;
85 // This node-id should be used for the `body_id` field on each
86 // `ObligationCause` (and the `FnCtxt`). This is what
87 // `regionck_item` expects.
88 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
90 // We sometimes modify the span further down.
91 let mut cause = ObligationCause::new(
94 ObligationCauseCode::CompareImplMethodObligation {
95 impl_item_def_id: impl_m.def_id,
96 trait_item_def_id: trait_m.def_id,
100 // This code is best explained by example. Consider a trait:
102 // trait Trait<'t, T> {
103 // fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
108 // impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
109 // fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo;
112 // We wish to decide if those two method types are compatible.
114 // We start out with trait_to_impl_substs, that maps the trait
115 // type parameters to impl type parameters. This is taken from the
116 // impl trait reference:
118 // trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
120 // We create a mapping `dummy_substs` that maps from the impl type
121 // parameters to fresh types and regions. For type parameters,
122 // this is the identity transform, but we could as well use any
123 // placeholder types. For regions, we convert from bound to free
124 // regions (Note: but only early-bound regions, i.e., those
125 // declared on the impl or used in type parameter bounds).
127 // impl_to_placeholder_substs = {'i => 'i0, U => U0, N => N0 }
129 // Now we can apply placeholder_substs to the type of the impl method
130 // to yield a new function type in terms of our fresh, placeholder
133 // <'b> fn(t: &'i0 U0, m: &'b) -> Foo
135 // We now want to extract and substitute the type of the *trait*
136 // method and compare it. To do so, we must create a compound
137 // substitution by combining trait_to_impl_substs and
138 // impl_to_placeholder_substs, and also adding a mapping for the method
139 // type parameters. We extend the mapping to also include
140 // the method parameters.
142 // trait_to_placeholder_substs = { T => &'i0 U0, Self => Foo, M => N0 }
144 // Applying this to the trait method type yields:
146 // <'a> fn(t: &'i0 U0, m: &'a) -> Foo
148 // This type is also the same but the name of the bound region ('a
149 // vs 'b). However, the normal subtyping rules on fn types handle
150 // this kind of equivalency just fine.
152 // We now use these substitutions to ensure that all declared bounds are
153 // satisfied by the implementation's method.
155 // We do this by creating a parameter environment which contains a
156 // substitution corresponding to impl_to_placeholder_substs. We then build
157 // trait_to_placeholder_substs and use it to convert the predicates contained
158 // in the trait_m.generics to the placeholder form.
160 // Finally we register each of these predicates as an obligation in
161 // a fresh FulfillmentCtxt, and invoke select_all_or_error.
163 // Create mapping from impl to placeholder.
164 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
166 // Create mapping from trait to placeholder.
167 let trait_to_placeholder_substs =
168 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container.id(), trait_to_impl_substs);
169 debug!("compare_impl_method: trait_to_placeholder_substs={:?}", trait_to_placeholder_substs);
171 let impl_m_generics = tcx.generics_of(impl_m.def_id);
172 let trait_m_generics = tcx.generics_of(trait_m.def_id);
173 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
174 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
176 // Check region bounds.
177 check_region_bounds_on_impl_item(
186 // Create obligations for each predicate declared by the impl
187 // definition in the context of the trait's parameter
188 // environment. We can't just use `impl_env.caller_bounds`,
189 // however, because we want to replace all late-bound regions with
191 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
192 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
194 debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
196 // This is the only tricky bit of the new way we check implementation methods
197 // We need to build a set of predicates where only the method-level bounds
198 // are from the trait and we assume all other bounds from the implementation
199 // to be previously satisfied.
201 // We then register the obligations from the impl_m and check to see
202 // if all constraints hold.
205 .extend(trait_m_predicates.instantiate_own(tcx, trait_to_placeholder_substs).predicates);
207 // Construct trait parameter environment and then shift it into the placeholder viewpoint.
208 // The key step here is to update the caller_bounds's predicates to be
209 // the new hybrid bounds we computed.
210 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
211 let param_env = ty::ParamEnv::new(
212 tcx.intern_predicates(&hybrid_preds.predicates),
214 hir::Constness::NotConst,
217 traits::normalize_param_env_or_error(tcx, impl_m.def_id, param_env, normalize_cause);
219 tcx.infer_ctxt().enter(|infcx| {
220 let inh = Inherited::new(infcx, impl_m.def_id.expect_local());
221 let infcx = &inh.infcx;
223 debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds());
225 let mut selcx = traits::SelectionContext::new(&infcx);
227 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs);
228 for (predicate, span) in iter::zip(impl_m_own_bounds.predicates, impl_m_own_bounds.spans) {
229 let normalize_cause = traits::ObligationCause::misc(span, impl_m_hir_id);
230 let traits::Normalized { value: predicate, obligations } =
231 traits::normalize(&mut selcx, param_env, normalize_cause, predicate);
233 inh.register_predicates(obligations);
234 let mut cause = cause.clone();
236 inh.register_predicate(traits::Obligation::new(cause, param_env, predicate));
239 // We now need to check that the signature of the impl method is
240 // compatible with that of the trait method. We do this by
241 // checking that `impl_fty <: trait_fty`.
243 // FIXME. Unfortunately, this doesn't quite work right now because
244 // associated type normalization is not integrated into subtype
245 // checks. For the comparison to be valid, we need to
246 // normalize the associated types in the impl/trait methods
247 // first. However, because function types bind regions, just
248 // calling `normalize_associated_types_in` would have no effect on
249 // any associated types appearing in the fn arguments or return
252 // Compute placeholder form of impl and trait method tys.
255 let mut wf_tys = FxHashSet::default();
257 let (impl_sig, _) = infcx.replace_bound_vars_with_fresh_vars(
259 infer::HigherRankedType,
260 tcx.fn_sig(impl_m.def_id),
263 inh.normalize_associated_types_in(impl_m_span, impl_m_hir_id, param_env, impl_sig);
264 let impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(impl_sig));
265 debug!("compare_impl_method: impl_fty={:?}", impl_fty);
267 // First liberate late bound regions and subst placeholders
268 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, tcx.fn_sig(trait_m.def_id));
269 let trait_sig = trait_sig.subst(tcx, trait_to_placeholder_substs);
271 inh.normalize_associated_types_in(impl_m_span, impl_m_hir_id, param_env, trait_sig);
272 // Add the resulting inputs and output as well-formed.
273 wf_tys.extend(trait_sig.inputs_and_output.iter());
274 let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));
276 debug!("compare_impl_method: trait_fty={:?}", trait_fty);
278 let sub_result = infcx.at(&cause, param_env).sup(trait_fty, impl_fty).map(
279 |InferOk { obligations, .. }| {
280 // FIXME: We'd want to keep more accurate spans than "the method signature" when
281 // processing the comparison between the trait and impl fn, but we sadly lose them
282 // and point at the whole signature when a trait bound or specific input or output
283 // type would be more appropriate. In other places we have a `Vec<Span>`
284 // corresponding to their `Vec<Predicate>`, but we don't have that here.
285 // Fixing this would improve the output of test `issue-83765.rs`.
286 inh.register_predicates(obligations);
290 if let Err(terr) = sub_result {
291 debug!("sub_types failed: impl ty {:?}, trait ty {:?}", impl_fty, trait_fty);
293 let (impl_err_span, trait_err_span) =
294 extract_spans_for_error_reporting(&infcx, &terr, &cause, impl_m, trait_m);
296 cause.span = impl_err_span;
298 let mut diag = struct_span_err!(
302 "method `{}` has an incompatible type for trait",
306 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
307 if trait_m.fn_has_self_parameter =>
309 let ty = trait_sig.inputs()[0];
310 let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty())
312 ExplicitSelf::ByValue => "self".to_owned(),
313 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
314 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => {
315 "&mut self".to_owned()
317 _ => format!("self: {}", ty),
320 // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
321 // span points only at the type `Box<Self`>, but we want to cover the whole
322 // argument pattern and type.
323 let span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
324 ImplItemKind::Fn(ref sig, body) => tcx
326 .body_param_names(body)
327 .zip(sig.decl.inputs.iter())
328 .map(|(param, ty)| param.span.to(ty.span))
330 .unwrap_or(impl_err_span),
331 _ => bug!("{:?} is not a method", impl_m),
334 diag.span_suggestion(
336 "change the self-receiver type to match the trait",
338 Applicability::MachineApplicable,
341 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
342 if trait_sig.inputs().len() == *i {
343 // Suggestion to change output type. We do not suggest in `async` functions
344 // to avoid complex logic or incorrect output.
345 match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
346 ImplItemKind::Fn(ref sig, _)
347 if sig.header.asyncness == hir::IsAsync::NotAsync =>
349 let msg = "change the output type to match the trait";
350 let ap = Applicability::MachineApplicable;
351 match sig.decl.output {
352 hir::FnRetTy::DefaultReturn(sp) => {
353 let sugg = format!("-> {} ", trait_sig.output());
354 diag.span_suggestion_verbose(sp, msg, sugg, ap);
356 hir::FnRetTy::Return(hir_ty) => {
357 let sugg = trait_sig.output().to_string();
358 diag.span_suggestion(hir_ty.span, msg, sugg, ap);
364 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
365 diag.span_suggestion(
367 "change the parameter type to match the trait",
368 trait_ty.to_string(),
369 Applicability::MachineApplicable,
379 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
380 Some(infer::ValuePairs::Terms(ExpectedFound {
381 expected: trait_fty.into(),
382 found: impl_fty.into(),
388 return Err(ErrorReported);
391 // Check that all obligations are satisfied by the implementation's
393 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
394 if !errors.is_empty() {
395 infcx.report_fulfillment_errors(&errors, None, false);
396 return Err(ErrorReported);
399 // Finally, resolve all regions. This catches wily misuses of
400 // lifetime parameters.
401 let fcx = FnCtxt::new(&inh, param_env, impl_m_hir_id);
402 fcx.regionck_item(impl_m_hir_id, impl_m_span, wf_tys);
408 fn check_region_bounds_on_impl_item<'tcx>(
411 impl_m: &ty::AssocItem,
412 trait_m: &ty::AssocItem,
413 trait_generics: &ty::Generics,
414 impl_generics: &ty::Generics,
415 ) -> Result<(), ErrorReported> {
416 let trait_params = trait_generics.own_counts().lifetimes;
417 let impl_params = impl_generics.own_counts().lifetimes;
420 "check_region_bounds_on_impl_item: \
421 trait_generics={:?} \
423 trait_generics, impl_generics
426 // Must have same number of early-bound lifetime parameters.
427 // Unfortunately, if the user screws up the bounds, then this
428 // will change classification between early and late. E.g.,
429 // if in trait we have `<'a,'b:'a>`, and in impl we just have
430 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
431 // in trait but 0 in the impl. But if we report "expected 2
432 // but found 0" it's confusing, because it looks like there
433 // are zero. Since I don't quite know how to phrase things at
434 // the moment, give a kind of vague error message.
435 if trait_params != impl_params {
436 let item_kind = assoc_item_kind_str(impl_m);
437 let def_span = tcx.sess.source_map().guess_head_span(span);
441 .and_then(|did| tcx.hir().get_generics(did))
442 .map_or(def_span, |g| g.span);
443 let generics_span = tcx.hir().span_if_local(trait_m.def_id).map(|sp| {
444 let def_sp = tcx.sess.source_map().guess_head_span(sp);
448 .and_then(|did| tcx.hir().get_generics(did))
449 .map_or(def_sp, |g| g.span)
452 tcx.sess.emit_err(LifetimesOrBoundsMismatchOnTrait {
455 ident: impl_m.ident(tcx),
458 return Err(ErrorReported);
464 #[instrument(level = "debug", skip(infcx))]
465 fn extract_spans_for_error_reporting<'a, 'tcx>(
466 infcx: &infer::InferCtxt<'a, 'tcx>,
467 terr: &TypeError<'_>,
468 cause: &ObligationCause<'tcx>,
469 impl_m: &ty::AssocItem,
470 trait_m: &ty::AssocItem,
471 ) -> (Span, Option<Span>) {
473 let mut impl_args = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
474 ImplItemKind::Fn(ref sig, _) => {
475 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
477 _ => bug!("{:?} is not a method", impl_m),
480 trait_m.def_id.as_local().map(|def_id| match tcx.hir().expect_trait_item(def_id).kind {
481 TraitItemKind::Fn(ref sig, _) => {
482 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
484 _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
488 TypeError::ArgumentMutability(i) => {
489 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
491 TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
492 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
494 _ => (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)),
498 fn compare_self_type<'tcx>(
500 impl_m: &ty::AssocItem,
502 trait_m: &ty::AssocItem,
503 impl_trait_ref: ty::TraitRef<'tcx>,
504 ) -> Result<(), ErrorReported> {
505 // Try to give more informative error messages about self typing
506 // mismatches. Note that any mismatch will also be detected
507 // below, where we construct a canonical function type that
508 // includes the self parameter as a normal parameter. It's just
509 // that the error messages you get out of this code are a bit more
510 // inscrutable, particularly for cases where one method has no
513 let self_string = |method: &ty::AssocItem| {
514 let untransformed_self_ty = match method.container {
515 ty::ImplContainer(_) => impl_trait_ref.self_ty(),
516 ty::TraitContainer(_) => tcx.types.self_param,
518 let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
519 let param_env = ty::ParamEnv::reveal_all();
521 tcx.infer_ctxt().enter(|infcx| {
522 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
523 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
524 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
525 ExplicitSelf::ByValue => "self".to_owned(),
526 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
527 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
528 _ => format!("self: {}", self_arg_ty),
533 match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
534 (false, false) | (true, true) => {}
537 let self_descr = self_string(impl_m);
538 let mut err = struct_span_err!(
542 "method `{}` has a `{}` declaration in the impl, but not in the trait",
546 err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
547 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
548 err.span_label(span, format!("trait method declared without `{}`", self_descr));
550 err.note_trait_signature(trait_m.name.to_string(), trait_m.signature(tcx));
553 return Err(ErrorReported);
557 let self_descr = self_string(trait_m);
558 let mut err = struct_span_err!(
562 "method `{}` has a `{}` declaration in the trait, but not in the impl",
566 err.span_label(impl_m_span, format!("expected `{}` in impl", self_descr));
567 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
568 err.span_label(span, format!("`{}` used in trait", self_descr));
570 err.note_trait_signature(trait_m.name.to_string(), trait_m.signature(tcx));
573 return Err(ErrorReported);
580 fn compare_number_of_generics<'tcx>(
582 impl_: &ty::AssocItem,
584 trait_: &ty::AssocItem,
585 trait_span: Option<Span>,
586 ) -> Result<(), ErrorReported> {
587 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
588 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
591 ("type", trait_own_counts.types, impl_own_counts.types),
592 ("const", trait_own_counts.consts, impl_own_counts.consts),
595 let item_kind = assoc_item_kind_str(impl_);
597 let mut err_occurred = false;
598 for (kind, trait_count, impl_count) in matchings {
599 if impl_count != trait_count {
602 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
603 let trait_item = tcx.hir().expect_trait_item(def_id);
604 if trait_item.generics.params.is_empty() {
605 (Some(vec![trait_item.generics.span]), vec![])
607 let arg_spans: Vec<Span> =
608 trait_item.generics.params.iter().map(|p| p.span).collect();
609 let impl_trait_spans: Vec<Span> = trait_item
613 .filter_map(|p| match p.kind {
614 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
618 (Some(arg_spans), impl_trait_spans)
621 (trait_span.map(|s| vec![s]), vec![])
624 let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local());
625 let impl_item_impl_trait_spans: Vec<Span> = impl_item
629 .filter_map(|p| match p.kind {
630 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
634 let spans = impl_item.generics.spans();
635 let span = spans.primary_span();
637 let mut err = tcx.sess.struct_span_err_with_code(
640 "{} `{}` has {} {kind} parameter{} but its trait \
641 declaration has {} {kind} parameter{}",
645 pluralize!(impl_count),
647 pluralize!(trait_count),
650 DiagnosticId::Error("E0049".into()),
653 let mut suffix = None;
655 if let Some(spans) = trait_spans {
656 let mut spans = spans.iter();
657 if let Some(span) = spans.next() {
661 "expected {} {} parameter{}",
664 pluralize!(trait_count),
669 err.span_label(*span, "");
672 suffix = Some(format!(", expected {}", trait_count));
675 if let Some(span) = span {
679 "found {} {} parameter{}{}",
682 pluralize!(impl_count),
683 suffix.unwrap_or_else(String::new),
688 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
689 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
696 if err_occurred { Err(ErrorReported) } else { Ok(()) }
699 fn compare_number_of_method_arguments<'tcx>(
701 impl_m: &ty::AssocItem,
703 trait_m: &ty::AssocItem,
704 trait_item_span: Option<Span>,
705 ) -> Result<(), ErrorReported> {
706 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
707 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
708 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
709 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
710 if trait_number_args != impl_number_args {
711 let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
712 match tcx.hir().expect_trait_item(def_id).kind {
713 TraitItemKind::Fn(ref trait_m_sig, _) => {
714 let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
715 if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
719 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
725 _ => bug!("{:?} is not a method", impl_m),
730 let impl_span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
731 ImplItemKind::Fn(ref impl_m_sig, _) => {
732 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
733 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
737 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
743 _ => bug!("{:?} is not a method", impl_m),
745 let mut err = struct_span_err!(
749 "method `{}` has {} but the declaration in trait `{}` has {}",
751 potentially_plural_count(impl_number_args, "parameter"),
752 tcx.def_path_str(trait_m.def_id),
755 if let Some(trait_span) = trait_span {
760 potentially_plural_count(trait_number_args, "parameter")
764 err.note_trait_signature(trait_m.name.to_string(), trait_m.signature(tcx));
769 "expected {}, found {}",
770 potentially_plural_count(trait_number_args, "parameter"),
775 return Err(ErrorReported);
781 fn compare_synthetic_generics<'tcx>(
783 impl_m: &ty::AssocItem,
784 trait_m: &ty::AssocItem,
785 ) -> Result<(), ErrorReported> {
786 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
787 // 1. Better messages for the span labels
788 // 2. Explanation as to what is going on
789 // If we get here, we already have the same number of generics, so the zip will
791 let mut error_found = false;
792 let impl_m_generics = tcx.generics_of(impl_m.def_id);
793 let trait_m_generics = tcx.generics_of(trait_m.def_id);
794 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
795 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
796 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
798 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
799 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
800 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
802 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
803 iter::zip(impl_m_type_params, trait_m_type_params)
805 if impl_synthetic != trait_synthetic {
806 let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_def_id.expect_local());
807 let impl_span = tcx.hir().span(impl_hir_id);
808 let trait_span = tcx.def_span(trait_def_id);
809 let mut err = struct_span_err!(
813 "method `{}` has incompatible signature for trait",
816 err.span_label(trait_span, "declaration in trait here");
817 match (impl_synthetic, trait_synthetic) {
818 // The case where the impl method uses `impl Trait` but the trait method uses
821 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
823 // try taking the name from the trait impl
824 // FIXME: this is obviously suboptimal since the name can already be used
825 // as another generic argument
826 let new_name = tcx.sess.source_map().span_to_snippet(trait_span).ok()?;
827 let trait_m = trait_m.def_id.as_local()?;
828 let trait_m = tcx.hir().trait_item(hir::TraitItemId { def_id: trait_m });
830 let impl_m = impl_m.def_id.as_local()?;
831 let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
833 // in case there are no generics, take the spot between the function name
834 // and the opening paren of the argument list
835 let new_generics_span =
836 tcx.sess.source_map().generate_fn_name_span(impl_span)?.shrink_to_hi();
837 // in case there are generics, just replace them
839 impl_m.generics.span.substitute_dummy(new_generics_span);
840 // replace with the generics from the trait
842 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
844 err.multipart_suggestion(
845 "try changing the `impl Trait` argument to a generic parameter",
847 // replace `impl Trait` with `T`
848 (impl_span, new_name),
849 // replace impl method generics with trait method generics
850 // This isn't quite right, as users might have changed the names
851 // of the generics, but it works for the common case
852 (generics_span, new_generics),
854 Applicability::MaybeIncorrect,
859 // The case where the trait method uses `impl Trait`, but the impl method uses
860 // explicit generics.
862 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
864 let impl_m = impl_m.def_id.as_local()?;
865 let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
866 let input_tys = match impl_m.kind {
867 hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
870 struct Visitor(Option<Span>, hir::def_id::DefId);
871 impl<'v> intravisit::Visitor<'v> for Visitor {
872 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
873 intravisit::walk_ty(self, ty);
874 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
877 if let Res::Def(DefKind::TyParam, def_id) = path.res {
878 if def_id == self.1 {
879 self.0 = Some(ty.span);
885 let mut visitor = Visitor(None, impl_def_id);
886 for ty in input_tys {
887 intravisit::Visitor::visit_ty(&mut visitor, ty);
889 let span = visitor.0?;
892 impl_m.generics.params.iter().find_map(|param| match param.kind {
893 GenericParamKind::Lifetime { .. } => None,
894 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
895 if param.hir_id == impl_hir_id {
902 let bounds = bounds.first()?.span().to(bounds.last()?.span());
903 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
905 err.multipart_suggestion(
906 "try removing the generic parameter and using `impl Trait` instead",
908 // delete generic parameters
909 (impl_m.generics.span, String::new()),
910 // replace param usage with `impl Trait`
911 (span, format!("impl {}", bounds)),
913 Applicability::MaybeIncorrect,
924 if error_found { Err(ErrorReported) } else { Ok(()) }
927 fn compare_const_param_types<'tcx>(
929 impl_m: &ty::AssocItem,
930 trait_m: &ty::AssocItem,
931 trait_item_span: Option<Span>,
932 ) -> Result<(), ErrorReported> {
933 let const_params_of = |def_id| {
934 tcx.generics_of(def_id).params.iter().filter_map(|param| match param.kind {
935 GenericParamDefKind::Const { .. } => Some(param.def_id),
939 let const_params_impl = const_params_of(impl_m.def_id);
940 let const_params_trait = const_params_of(trait_m.def_id);
942 for (const_param_impl, const_param_trait) in iter::zip(const_params_impl, const_params_trait) {
943 let impl_ty = tcx.type_of(const_param_impl);
944 let trait_ty = tcx.type_of(const_param_trait);
945 if impl_ty != trait_ty {
946 let (impl_span, impl_ident) = match tcx.hir().get_if_local(const_param_impl) {
947 Some(hir::Node::GenericParam(hir::GenericParam { span, name, .. })) => (
950 hir::ParamName::Plain(ident) => Some(ident),
955 "expected GenericParam, found {:?}",
956 other.map_or_else(|| "nothing".to_string(), |n| format!("{:?}", n))
959 let trait_span = match tcx.hir().get_if_local(const_param_trait) {
960 Some(hir::Node::GenericParam(hir::GenericParam { span, .. })) => Some(span),
963 let mut err = struct_span_err!(
967 "method `{}` has an incompatible const parameter type for trait",
971 trait_span.map_or_else(|| trait_item_span.unwrap_or(*impl_span), |span| *span),
973 "the const parameter{} has type `{}`, but the declaration \
974 in trait `{}` has type `{}`",
975 &impl_ident.map_or_else(|| "".to_string(), |ident| format!(" `{}`", ident)),
977 tcx.def_path_str(trait_m.def_id),
982 return Err(ErrorReported);
989 crate fn compare_const_impl<'tcx>(
991 impl_c: &ty::AssocItem,
993 trait_c: &ty::AssocItem,
994 impl_trait_ref: ty::TraitRef<'tcx>,
996 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
998 tcx.infer_ctxt().enter(|infcx| {
999 let param_env = tcx.param_env(impl_c.def_id);
1000 let inh = Inherited::new(infcx, impl_c.def_id.expect_local());
1001 let infcx = &inh.infcx;
1003 // The below is for the most part highly similar to the procedure
1004 // for methods above. It is simpler in many respects, especially
1005 // because we shouldn't really have to deal with lifetimes or
1006 // predicates. In fact some of this should probably be put into
1007 // shared functions because of DRY violations...
1008 let trait_to_impl_substs = impl_trait_ref.substs;
1010 // Create a parameter environment that represents the implementation's
1012 let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_c.def_id.expect_local());
1014 // Compute placeholder form of impl and trait const tys.
1015 let impl_ty = tcx.type_of(impl_c.def_id);
1016 let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
1017 let mut cause = ObligationCause::new(
1020 ObligationCauseCode::CompareImplConstObligation,
1023 // There is no "body" here, so just pass dummy id.
1025 inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, impl_ty);
1027 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1030 inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, trait_ty);
1032 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1035 .at(&cause, param_env)
1036 .sup(trait_ty, impl_ty)
1037 .map(|ok| inh.register_infer_ok_obligations(ok));
1039 if let Err(terr) = err {
1041 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1045 // Locate the Span containing just the type of the offending impl
1046 match tcx.hir().expect_impl_item(impl_c.def_id.expect_local()).kind {
1047 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
1048 _ => bug!("{:?} is not a impl const", impl_c),
1051 let mut diag = struct_span_err!(
1055 "implemented const `{}` has an incompatible type for trait",
1059 let trait_c_span = trait_c.def_id.as_local().map(|trait_c_def_id| {
1060 // Add a label to the Span containing just the type of the const
1061 match tcx.hir().expect_trait_item(trait_c_def_id).kind {
1062 TraitItemKind::Const(ref ty, _) => ty.span,
1063 _ => bug!("{:?} is not a trait const", trait_c),
1067 infcx.note_type_err(
1070 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1071 Some(infer::ValuePairs::Terms(ExpectedFound {
1072 expected: trait_ty.into(),
1073 found: impl_ty.into(),
1081 // Check that all obligations are satisfied by the implementation's
1083 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
1084 if !errors.is_empty() {
1085 infcx.report_fulfillment_errors(&errors, None, false);
1089 let fcx = FnCtxt::new(&inh, param_env, impl_c_hir_id);
1090 fcx.regionck_item(impl_c_hir_id, impl_c_span, FxHashSet::default());
1094 crate fn compare_ty_impl<'tcx>(
1096 impl_ty: &ty::AssocItem,
1098 trait_ty: &ty::AssocItem,
1099 impl_trait_ref: ty::TraitRef<'tcx>,
1100 trait_item_span: Option<Span>,
1102 debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1104 let _: Result<(), ErrorReported> = (|| {
1105 compare_number_of_generics(tcx, impl_ty, impl_ty_span, trait_ty, trait_item_span)?;
1107 let sp = tcx.def_span(impl_ty.def_id);
1108 compare_type_predicate_entailment(tcx, impl_ty, sp, trait_ty, impl_trait_ref)?;
1110 check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
1114 /// The equivalent of [compare_predicate_entailment], but for associated types
1115 /// instead of associated functions.
1116 fn compare_type_predicate_entailment<'tcx>(
1118 impl_ty: &ty::AssocItem,
1120 trait_ty: &ty::AssocItem,
1121 impl_trait_ref: ty::TraitRef<'tcx>,
1122 ) -> Result<(), ErrorReported> {
1123 let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1124 let trait_to_impl_substs =
1125 impl_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1127 let impl_ty_generics = tcx.generics_of(impl_ty.def_id);
1128 let trait_ty_generics = tcx.generics_of(trait_ty.def_id);
1129 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1130 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1132 check_region_bounds_on_impl_item(
1141 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1143 if impl_ty_own_bounds.is_empty() {
1144 // Nothing to check.
1148 // This `HirId` should be used for the `body_id` field on each
1149 // `ObligationCause` (and the `FnCtxt`). This is what
1150 // `regionck_item` expects.
1151 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1152 let cause = ObligationCause::new(
1155 ObligationCauseCode::CompareImplTypeObligation {
1156 impl_item_def_id: impl_ty.def_id,
1157 trait_item_def_id: trait_ty.def_id,
1161 debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1163 // The predicates declared by the impl definition, the trait and the
1164 // associated type in the trait are assumed.
1165 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1166 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1169 .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1171 debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1173 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1174 let param_env = ty::ParamEnv::new(
1175 tcx.intern_predicates(&hybrid_preds.predicates),
1177 hir::Constness::NotConst,
1179 let param_env = traits::normalize_param_env_or_error(
1183 normalize_cause.clone(),
1185 tcx.infer_ctxt().enter(|infcx| {
1186 let inh = Inherited::new(infcx, impl_ty.def_id.expect_local());
1187 let infcx = &inh.infcx;
1189 debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1191 let mut selcx = traits::SelectionContext::new(&infcx);
1193 for predicate in impl_ty_own_bounds.predicates {
1194 let traits::Normalized { value: predicate, obligations } =
1195 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), predicate);
1197 inh.register_predicates(obligations);
1198 inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
1201 // Check that all obligations are satisfied by the implementation's
1203 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
1204 if !errors.is_empty() {
1205 infcx.report_fulfillment_errors(&errors, None, false);
1206 return Err(ErrorReported);
1209 // Finally, resolve all regions. This catches wily misuses of
1210 // lifetime parameters.
1211 let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
1212 fcx.regionck_item(impl_ty_hir_id, impl_ty_span, FxHashSet::default());
1218 /// Validate that `ProjectionCandidate`s created for this associated type will
1223 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1225 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1226 /// impl is well-formed we have to prove `S: Copy`.
1228 /// For default associated types the normalization is not possible (the value
1229 /// from the impl could be overridden). We also can't normalize generic
1230 /// associated types (yet) because they contain bound parameters.
1231 #[tracing::instrument(level = "debug", skip(tcx))]
1232 pub fn check_type_bounds<'tcx>(
1234 trait_ty: &ty::AssocItem,
1235 impl_ty: &ty::AssocItem,
1237 impl_trait_ref: ty::TraitRef<'tcx>,
1238 ) -> Result<(), ErrorReported> {
1241 // impl<A, B> Foo<u32> for (A, B) {
1245 // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1246 // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1247 // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1248 // the *trait* with the generic associated type parameters (as bound vars).
1250 // A note regarding the use of bound vars here:
1251 // Imagine as an example
1254 // type Member<C: Eq>;
1257 // impl Family for VecFamily {
1258 // type Member<C: Eq> = i32;
1261 // Here, we would generate
1263 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1265 // when we really would like to generate
1267 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1269 // But, this is probably fine, because although the first clause can be used with types C that
1270 // do not implement Eq, for it to cause some kind of problem, there would have to be a
1271 // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1272 // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1273 // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1274 // the trait (notably, that X: Eq and T: Family).
1275 let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1276 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1277 if let Some(def_id) = defs.parent {
1278 let parent_defs = tcx.generics_of(def_id);
1279 InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1280 tcx.mk_param_from_def(param)
1283 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1284 smallvec::SmallVec::with_capacity(defs.count());
1285 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1286 GenericParamDefKind::Type { .. } => {
1287 let kind = ty::BoundTyKind::Param(param.name);
1288 let bound_var = ty::BoundVariableKind::Ty(kind);
1289 bound_vars.push(bound_var);
1290 tcx.mk_ty(ty::Bound(
1292 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1296 GenericParamDefKind::Lifetime => {
1297 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1298 let bound_var = ty::BoundVariableKind::Region(kind);
1299 bound_vars.push(bound_var);
1300 tcx.mk_region(ty::ReLateBound(
1302 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1306 GenericParamDefKind::Const { .. } => {
1307 let bound_var = ty::BoundVariableKind::Const;
1308 bound_vars.push(bound_var);
1309 tcx.mk_const(ty::ConstS {
1310 ty: tcx.type_of(param.def_id),
1311 val: ty::ConstKind::Bound(
1313 ty::BoundVar::from_usize(bound_vars.len() - 1),
1319 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
1320 let impl_ty_substs = tcx.intern_substs(&substs);
1322 let rebased_substs =
1323 impl_ty_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1324 let impl_ty_value = tcx.type_of(impl_ty.def_id);
1326 let param_env = tcx.param_env(impl_ty.def_id);
1328 // When checking something like
1330 // trait X { type Y: PartialEq<<Self as X>::Y> }
1331 // impl X for T { default type Y = S; }
1333 // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
1334 // we want <T as X>::Y to normalize to S. This is valid because we are
1335 // checking the default value specifically here. Add this equality to the
1336 // ParamEnv for normalization specifically.
1337 let normalize_param_env = {
1338 let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
1339 match impl_ty_value.kind() {
1340 ty::Projection(proj)
1341 if proj.item_def_id == trait_ty.def_id && proj.substs == rebased_substs =>
1343 // Don't include this predicate if the projected type is
1344 // exactly the same as the projection. This can occur in
1345 // (somewhat dubious) code like this:
1347 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
1349 _ => predicates.push(
1350 ty::Binder::bind_with_vars(
1351 ty::ProjectionPredicate {
1352 projection_ty: ty::ProjectionTy {
1353 item_def_id: trait_ty.def_id,
1354 substs: rebased_substs,
1356 term: impl_ty_value.into(),
1364 tcx.intern_predicates(&predicates),
1366 param_env.constness(),
1369 debug!(?normalize_param_env);
1371 let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1372 let rebased_substs =
1373 impl_ty_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1375 tcx.infer_ctxt().enter(move |infcx| {
1376 let inh = Inherited::new(infcx, impl_ty.def_id.expect_local());
1377 let infcx = &inh.infcx;
1378 let mut selcx = traits::SelectionContext::new(&infcx);
1380 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1381 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1382 let mk_cause = |span: Span| {
1383 let code = if span.is_dummy() {
1384 traits::MiscObligation
1386 traits::BindingObligation(trait_ty.def_id, span)
1388 ObligationCause::new(impl_ty_span, impl_ty_hir_id, code)
1391 let obligations = tcx
1392 .explicit_item_bounds(trait_ty.def_id)
1394 .map(|&(bound, span)| {
1396 let concrete_ty_bound = bound.subst(tcx, rebased_substs);
1397 debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
1399 traits::Obligation::new(mk_cause(span), param_env, concrete_ty_bound)
1402 debug!("check_type_bounds: item_bounds={:?}", obligations);
1404 for mut obligation in util::elaborate_obligations(tcx, obligations) {
1405 let traits::Normalized { value: normalized_predicate, obligations } = traits::normalize(
1407 normalize_param_env,
1408 normalize_cause.clone(),
1409 obligation.predicate,
1411 debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
1412 obligation.predicate = normalized_predicate;
1414 inh.register_predicates(obligations);
1415 inh.register_predicate(obligation);
1418 // Check that all obligations are satisfied by the implementation's
1420 let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx);
1421 if !errors.is_empty() {
1422 infcx.report_fulfillment_errors(&errors, None, false);
1423 return Err(ErrorReported);
1426 // Finally, resolve all regions. This catches wily misuses of
1427 // lifetime parameters.
1428 let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
1429 let implied_bounds = match impl_ty.container {
1430 ty::TraitContainer(_) => FxHashSet::default(),
1431 ty::ImplContainer(def_id) => fcx.impl_implied_bounds(def_id, impl_ty_span),
1433 fcx.regionck_item(impl_ty_hir_id, impl_ty_span, implied_bounds);
1439 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
1440 match impl_item.kind {
1441 ty::AssocKind::Const => "const",
1442 ty::AssocKind::Fn => "method",
1443 ty::AssocKind::Type => "type",