1 use rustc::hir::{self, GenericParamKind, ImplItemKind, TraitItemKind};
2 use rustc::hir::def::{Res, DefKind};
3 use rustc::infer::{self, InferOk};
4 use rustc::ty::{self, TyCtxt, GenericParamDefKind};
5 use rustc::ty::util::ExplicitSelf;
6 use rustc::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
7 use rustc::ty::error::{ExpectedFound, TypeError};
8 use rustc::ty::subst::{Subst, InternalSubsts, SubstsRef};
9 use rustc::util::common::ErrorReported;
10 use errors::{Applicability, DiagnosticId};
13 use syntax::errors::pluralise;
15 use super::{Inherited, FnCtxt, potentially_plural_count};
17 /// Checks that a method from an impl conforms to the signature of
18 /// the same method as declared in the trait.
22 /// - `impl_m`: type of the method we are checking
23 /// - `impl_m_span`: span to use for reporting errors
24 /// - `trait_m`: the method in the trait
25 /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
27 pub fn compare_impl_method<'tcx>(
29 impl_m: &ty::AssocItem,
31 trait_m: &ty::AssocItem,
32 impl_trait_ref: ty::TraitRef<'tcx>,
33 trait_item_span: Option<Span>,
35 debug!("compare_impl_method(impl_trait_ref={:?})",
38 let impl_m_span = tcx.sess.source_map().def_span(impl_m_span);
40 if let Err(ErrorReported) = compare_self_type(tcx,
48 if let Err(ErrorReported) = compare_number_of_generics(tcx,
56 if let Err(ErrorReported) = compare_number_of_method_arguments(tcx,
64 if let Err(ErrorReported) = compare_synthetic_generics(tcx,
70 if let Err(ErrorReported) = compare_predicate_entailment(tcx,
79 fn compare_predicate_entailment<'tcx>(
81 impl_m: &ty::AssocItem,
83 trait_m: &ty::AssocItem,
84 impl_trait_ref: ty::TraitRef<'tcx>,
85 ) -> Result<(), ErrorReported> {
86 let trait_to_impl_substs = impl_trait_ref.substs;
88 // This node-id should be used for the `body_id` field on each
89 // `ObligationCause` (and the `FnCtxt`). This is what
90 // `regionck_item` expects.
91 let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id).unwrap();
93 let cause = ObligationCause {
95 body_id: impl_m_hir_id,
96 code: ObligationCauseCode::CompareImplMethodObligation {
97 item_name: impl_m.ident.name,
98 impl_item_def_id: impl_m.def_id,
99 trait_item_def_id: trait_m.def_id,
103 // This code is best explained by example. Consider a trait:
105 // trait Trait<'t,T> {
106 // fn method<'a,M>(t: &'t T, m: &'a M) -> Self;
111 // impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
112 // fn method<'b,N>(t: &'j &'i U, m: &'b N) -> Foo;
115 // We wish to decide if those two method types are compatible.
117 // We start out with trait_to_impl_substs, that maps the trait
118 // type parameters to impl type parameters. This is taken from the
119 // impl trait reference:
121 // trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
123 // We create a mapping `dummy_substs` that maps from the impl type
124 // parameters to fresh types and regions. For type parameters,
125 // this is the identity transform, but we could as well use any
126 // placeholder types. For regions, we convert from bound to free
127 // regions (Note: but only early-bound regions, i.e., those
128 // declared on the impl or used in type parameter bounds).
130 // impl_to_skol_substs = {'i => 'i0, U => U0, N => N0 }
132 // Now we can apply skol_substs to the type of the impl method
133 // to yield a new function type in terms of our fresh, placeholder
136 // <'b> fn(t: &'i0 U0, m: &'b) -> Foo
138 // We now want to extract and substitute the type of the *trait*
139 // method and compare it. To do so, we must create a compound
140 // substitution by combining trait_to_impl_substs and
141 // impl_to_skol_substs, and also adding a mapping for the method
142 // type parameters. We extend the mapping to also include
143 // the method parameters.
145 // trait_to_skol_substs = { T => &'i0 U0, Self => Foo, M => N0 }
147 // Applying this to the trait method type yields:
149 // <'a> fn(t: &'i0 U0, m: &'a) -> Foo
151 // This type is also the same but the name of the bound region ('a
152 // vs 'b). However, the normal subtyping rules on fn types handle
153 // this kind of equivalency just fine.
155 // We now use these substitutions to ensure that all declared bounds are
156 // satisfied by the implementation's method.
158 // We do this by creating a parameter environment which contains a
159 // substitution corresponding to impl_to_skol_substs. We then build
160 // trait_to_skol_substs and use it to convert the predicates contained
161 // in the trait_m.generics to the placeholder form.
163 // Finally we register each of these predicates as an obligation in
164 // a fresh FulfillmentCtxt, and invoke select_all_or_error.
166 // Create mapping from impl to placeholder.
167 let impl_to_skol_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
169 // Create mapping from trait to placeholder.
170 let trait_to_skol_substs = impl_to_skol_substs.rebase_onto(tcx,
171 impl_m.container.id(),
172 trait_to_impl_substs);
173 debug!("compare_impl_method: trait_to_skol_substs={:?}",
174 trait_to_skol_substs);
176 let impl_m_generics = tcx.generics_of(impl_m.def_id);
177 let trait_m_generics = tcx.generics_of(trait_m.def_id);
178 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
179 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
181 // Check region bounds.
182 check_region_bounds_on_impl_method(tcx,
188 trait_to_skol_substs)?;
190 // Create obligations for each predicate declared by the impl
191 // definition in the context of the trait's parameter
192 // environment. We can't just use `impl_env.caller_bounds`,
193 // however, because we want to replace all late-bound regions with
195 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
196 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
198 debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
200 // This is the only tricky bit of the new way we check implementation methods
201 // We need to build a set of predicates where only the method-level bounds
202 // are from the trait and we assume all other bounds from the implementation
203 // to be previously satisfied.
205 // We then register the obligations from the impl_m and check to see
206 // if all constraints hold.
207 hybrid_preds.predicates.extend(
208 trait_m_predicates.instantiate_own(tcx, trait_to_skol_substs).predicates);
210 // Construct trait parameter environment and then shift it into the placeholder viewpoint.
211 // The key step here is to update the caller_bounds's predicates to be
212 // the new hybrid bounds we computed.
213 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
214 let param_env = ty::ParamEnv::new(
215 tcx.intern_predicates(&hybrid_preds.predicates),
219 let param_env = traits::normalize_param_env_or_error(tcx,
222 normalize_cause.clone());
224 tcx.infer_ctxt().enter(|infcx| {
225 let inh = Inherited::new(infcx, impl_m.def_id);
226 let infcx = &inh.infcx;
228 debug!("compare_impl_method: caller_bounds={:?}",
229 param_env.caller_bounds);
231 let mut selcx = traits::SelectionContext::new(&infcx);
233 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_skol_substs);
234 let (impl_m_own_bounds, _) = infcx.replace_bound_vars_with_fresh_vars(
236 infer::HigherRankedType,
237 &ty::Binder::bind(impl_m_own_bounds.predicates)
239 for predicate in impl_m_own_bounds {
240 let traits::Normalized { value: predicate, obligations } =
241 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), &predicate);
243 inh.register_predicates(obligations);
244 inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
247 // We now need to check that the signature of the impl method is
248 // compatible with that of the trait method. We do this by
249 // checking that `impl_fty <: trait_fty`.
251 // FIXME. Unfortunately, this doesn't quite work right now because
252 // associated type normalization is not integrated into subtype
253 // checks. For the comparison to be valid, we need to
254 // normalize the associated types in the impl/trait methods
255 // first. However, because function types bind regions, just
256 // calling `normalize_associated_types_in` would have no effect on
257 // any associated types appearing in the fn arguments or return
260 // Compute placeholder form of impl and trait method tys.
263 let (impl_sig, _) = infcx.replace_bound_vars_with_fresh_vars(
265 infer::HigherRankedType,
266 &tcx.fn_sig(impl_m.def_id)
269 inh.normalize_associated_types_in(impl_m_span,
273 let impl_fty = tcx.mk_fn_ptr(ty::Binder::bind(impl_sig));
274 debug!("compare_impl_method: impl_fty={:?}", impl_fty);
276 let trait_sig = tcx.liberate_late_bound_regions(
278 &tcx.fn_sig(trait_m.def_id));
280 trait_sig.subst(tcx, trait_to_skol_substs);
282 inh.normalize_associated_types_in(impl_m_span,
286 let trait_fty = tcx.mk_fn_ptr(ty::Binder::bind(trait_sig));
288 debug!("compare_impl_method: trait_fty={:?}", trait_fty);
290 let sub_result = infcx.at(&cause, param_env)
291 .sup(trait_fty, impl_fty)
292 .map(|InferOk { obligations, .. }| {
293 inh.register_predicates(obligations);
296 if let Err(terr) = sub_result {
297 debug!("sub_types failed: impl ty {:?}, trait ty {:?}",
301 let (impl_err_span, trait_err_span) = extract_spans_for_error_reporting(&infcx,
310 let cause = ObligationCause {
315 let mut diag = struct_span_err!(tcx.sess,
318 "method `{}` has an incompatible type for trait",
320 if let TypeError::Mutability = terr {
321 if let Some(trait_err_span) = trait_err_span {
322 if let Ok(trait_err_str) = tcx.sess.source_map()
323 .span_to_snippet(trait_err_span) {
324 diag.span_suggestion(
326 "consider change the type to match the mutability in trait",
328 Applicability::MachineApplicable,
334 infcx.note_type_err(&mut diag,
336 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
337 Some(infer::ValuePairs::Types(ExpectedFound {
343 return Err(ErrorReported);
346 // Check that all obligations are satisfied by the implementation's
348 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
349 infcx.report_fulfillment_errors(errors, None, false);
350 return Err(ErrorReported);
353 // Finally, resolve all regions. This catches wily misuses of
354 // lifetime parameters.
355 let fcx = FnCtxt::new(&inh, param_env, impl_m_hir_id);
356 fcx.regionck_item(impl_m_hir_id, impl_m_span, &[]);
362 fn check_region_bounds_on_impl_method<'tcx>(
365 impl_m: &ty::AssocItem,
366 trait_m: &ty::AssocItem,
367 trait_generics: &ty::Generics,
368 impl_generics: &ty::Generics,
369 trait_to_skol_substs: SubstsRef<'tcx>,
370 ) -> Result<(), ErrorReported> {
371 let trait_params = trait_generics.own_counts().lifetimes;
372 let impl_params = impl_generics.own_counts().lifetimes;
374 debug!("check_region_bounds_on_impl_method: \
375 trait_generics={:?} \
377 trait_to_skol_substs={:?}",
380 trait_to_skol_substs);
382 // Must have same number of early-bound lifetime parameters.
383 // Unfortunately, if the user screws up the bounds, then this
384 // will change classification between early and late. E.g.,
385 // if in trait we have `<'a,'b:'a>`, and in impl we just have
386 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
387 // in trait but 0 in the impl. But if we report "expected 2
388 // but found 0" it's confusing, because it looks like there
389 // are zero. Since I don't quite know how to phrase things at
390 // the moment, give a kind of vague error message.
391 if trait_params != impl_params {
392 let def_span = tcx.sess.source_map().def_span(span);
393 let span = tcx.hir().get_generics(impl_m.def_id).map(|g| g.span).unwrap_or(def_span);
394 let mut err = struct_span_err!(
398 "lifetime parameters or bounds on method `{}` do not match the trait declaration",
401 err.span_label(span, "lifetimes do not match method in trait");
402 if let Some(sp) = tcx.hir().span_if_local(trait_m.def_id) {
403 let def_sp = tcx.sess.source_map().def_span(sp);
404 let sp = tcx.hir().get_generics(trait_m.def_id).map(|g| g.span).unwrap_or(def_sp);
405 err.span_label(sp, "lifetimes in impl do not match this method in trait");
408 return Err(ErrorReported);
414 fn extract_spans_for_error_reporting<'a, 'tcx>(
415 infcx: &infer::InferCtxt<'a, 'tcx>,
416 param_env: ty::ParamEnv<'tcx>,
417 terr: &TypeError<'_>,
418 cause: &ObligationCause<'tcx>,
419 impl_m: &ty::AssocItem,
420 impl_sig: ty::FnSig<'tcx>,
421 trait_m: &ty::AssocItem,
422 trait_sig: ty::FnSig<'tcx>,
423 ) -> (Span, Option<Span>) {
425 let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id).unwrap();
426 let (impl_m_output, impl_m_iter) = match tcx.hir()
427 .expect_impl_item(impl_m_hir_id)
429 ImplItemKind::Method(ref impl_m_sig, _) => {
430 (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter())
432 _ => bug!("{:?} is not a method", impl_m),
436 TypeError::Mutability => {
437 if let Some(trait_m_hir_id) = tcx.hir().as_local_hir_id(trait_m.def_id) {
438 let trait_m_iter = match tcx.hir()
439 .expect_trait_item(trait_m_hir_id)
441 TraitItemKind::Method(ref trait_m_sig, _) => {
442 trait_m_sig.decl.inputs.iter()
444 _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
447 impl_m_iter.zip(trait_m_iter).find(|&(ref impl_arg, ref trait_arg)| {
448 match (&impl_arg.kind, &trait_arg.kind) {
449 (&hir::TyKind::Rptr(_, ref impl_mt), &hir::TyKind::Rptr(_, ref trait_mt)) |
450 (&hir::TyKind::Ptr(ref impl_mt), &hir::TyKind::Ptr(ref trait_mt)) => {
451 impl_mt.mutbl != trait_mt.mutbl
455 }).map(|(ref impl_arg, ref trait_arg)| {
456 (impl_arg.span, Some(trait_arg.span))
458 .unwrap_or_else(|| (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)))
460 (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
463 TypeError::Sorts(ExpectedFound { .. }) => {
464 if let Some(trait_m_hir_id) = tcx.hir().as_local_hir_id(trait_m.def_id) {
465 let (trait_m_output, trait_m_iter) =
466 match tcx.hir().expect_trait_item(trait_m_hir_id).kind {
467 TraitItemKind::Method(ref trait_m_sig, _) => {
468 (&trait_m_sig.decl.output, trait_m_sig.decl.inputs.iter())
470 _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
473 let impl_iter = impl_sig.inputs().iter();
474 let trait_iter = trait_sig.inputs().iter();
475 impl_iter.zip(trait_iter)
478 .filter_map(|(((&impl_arg_ty, &trait_arg_ty), impl_arg), trait_arg)|
479 match infcx.at(&cause, param_env).sub(trait_arg_ty, impl_arg_ty) {
481 Err(_) => Some((impl_arg.span, Some(trait_arg.span))),
487 infcx.at(&cause, param_env)
488 .sup(trait_sig.output(), impl_sig.output())
491 (impl_m_output.span(), Some(trait_m_output.span()))
493 (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
497 (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
500 _ => (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)),
504 fn compare_self_type<'tcx>(
506 impl_m: &ty::AssocItem,
508 trait_m: &ty::AssocItem,
509 impl_trait_ref: ty::TraitRef<'tcx>,
510 ) -> Result<(), ErrorReported> {
511 // Try to give more informative error messages about self typing
512 // mismatches. Note that any mismatch will also be detected
513 // below, where we construct a canonical function type that
514 // includes the self parameter as a normal parameter. It's just
515 // that the error messages you get out of this code are a bit more
516 // inscrutable, particularly for cases where one method has no
519 let self_string = |method: &ty::AssocItem| {
520 let untransformed_self_ty = match method.container {
521 ty::ImplContainer(_) => impl_trait_ref.self_ty(),
522 ty::TraitContainer(_) => tcx.types.self_param
524 let self_arg_ty = *tcx.fn_sig(method.def_id).input(0).skip_binder();
525 let param_env = ty::ParamEnv::reveal_all();
527 tcx.infer_ctxt().enter(|infcx| {
528 let self_arg_ty = tcx.liberate_late_bound_regions(
530 &ty::Binder::bind(self_arg_ty)
532 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
533 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
534 ExplicitSelf::ByValue => "self".to_owned(),
535 ExplicitSelf::ByReference(_, hir::MutImmutable) => "&self".to_owned(),
536 ExplicitSelf::ByReference(_, hir::MutMutable) => "&mut self".to_owned(),
537 _ => format!("self: {}", self_arg_ty)
542 match (trait_m.method_has_self_argument, impl_m.method_has_self_argument) {
543 (false, false) | (true, true) => {}
546 let self_descr = self_string(impl_m);
547 let mut err = struct_span_err!(tcx.sess,
550 "method `{}` has a `{}` declaration in the impl, but \
554 err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
555 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
556 err.span_label(span, format!("trait method declared without `{}`", self_descr));
558 err.note_trait_signature(trait_m.ident.to_string(),
559 trait_m.signature(tcx));
562 return Err(ErrorReported);
566 let self_descr = self_string(trait_m);
567 let mut err = struct_span_err!(tcx.sess,
570 "method `{}` has a `{}` declaration in the trait, but \
574 err.span_label(impl_m_span, format!("expected `{}` in impl", self_descr));
575 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
576 err.span_label(span, format!("`{}` used in trait", self_descr));
578 err.note_trait_signature(trait_m.ident.to_string(),
579 trait_m.signature(tcx));
582 return Err(ErrorReported);
589 fn compare_number_of_generics<'tcx>(
591 impl_: &ty::AssocItem,
593 trait_: &ty::AssocItem,
594 trait_span: Option<Span>,
595 ) -> Result<(), ErrorReported> {
596 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
597 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
600 ("type", trait_own_counts.types, impl_own_counts.types),
601 ("const", trait_own_counts.consts, impl_own_counts.consts),
604 let mut err_occurred = false;
605 for &(kind, trait_count, impl_count) in &matchings {
606 if impl_count != trait_count {
612 ) = if let Some(trait_hir_id) = tcx.hir().as_local_hir_id(trait_.def_id) {
613 let trait_item = tcx.hir().expect_trait_item(trait_hir_id);
614 if trait_item.generics.params.is_empty() {
615 (Some(vec![trait_item.generics.span]), vec![])
617 let arg_spans: Vec<Span> = trait_item.generics.params.iter()
620 let impl_trait_spans: Vec<Span> = trait_item.generics.params.iter()
621 .filter_map(|p| match p.kind {
622 GenericParamKind::Type {
623 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
627 (Some(arg_spans), impl_trait_spans)
630 (trait_span.map(|s| vec![s]), vec![])
633 let impl_hir_id = tcx.hir().as_local_hir_id(impl_.def_id).unwrap();
634 let impl_item = tcx.hir().expect_impl_item(impl_hir_id);
635 let impl_item_impl_trait_spans: Vec<Span> = impl_item.generics.params.iter()
636 .filter_map(|p| match p.kind {
637 GenericParamKind::Type {
638 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
642 let spans = impl_item.generics.spans();
643 let span = spans.primary_span();
645 let mut err = tcx.sess.struct_span_err_with_code(
648 "method `{}` has {} {kind} parameter{} but its trait \
649 declaration has {} {kind} parameter{}",
652 pluralise!(impl_count),
654 pluralise!(trait_count),
657 DiagnosticId::Error("E0049".into()),
660 let mut suffix = None;
662 if let Some(spans) = trait_spans {
663 let mut spans = spans.iter();
664 if let Some(span) = spans.next() {
665 err.span_label(*span, format!(
666 "expected {} {} parameter{}",
669 pluralise!(trait_count),
673 err.span_label(*span, "");
676 suffix = Some(format!(", expected {}", trait_count));
679 if let Some(span) = span {
680 err.span_label(span, format!(
681 "found {} {} parameter{}{}",
684 pluralise!(impl_count),
685 suffix.unwrap_or_else(|| String::new()),
689 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
690 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
704 fn compare_number_of_method_arguments<'tcx>(
706 impl_m: &ty::AssocItem,
708 trait_m: &ty::AssocItem,
709 trait_item_span: Option<Span>,
710 ) -> Result<(), ErrorReported> {
711 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
712 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
713 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
714 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
715 if trait_number_args != impl_number_args {
716 let trait_m_hir_id = tcx.hir().as_local_hir_id(trait_m.def_id);
717 let trait_span = if let Some(trait_id) = trait_m_hir_id {
718 match tcx.hir().expect_trait_item(trait_id).kind {
719 TraitItemKind::Method(ref trait_m_sig, _) => {
720 let pos = if trait_number_args > 0 {
721 trait_number_args - 1
725 if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
729 Span::new(trait_m_sig.decl.inputs[0].span.lo(),
737 _ => bug!("{:?} is not a method", impl_m),
742 let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id).unwrap();
743 let impl_span = match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
744 ImplItemKind::Method(ref impl_m_sig, _) => {
745 let pos = if impl_number_args > 0 {
750 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
754 Span::new(impl_m_sig.decl.inputs[0].span.lo(),
762 _ => bug!("{:?} is not a method", impl_m),
764 let mut err = struct_span_err!(tcx.sess,
767 "method `{}` has {} but the declaration in \
770 potentially_plural_count(impl_number_args, "parameter"),
771 tcx.def_path_str(trait_m.def_id),
773 if let Some(trait_span) = trait_span {
774 err.span_label(trait_span, format!("trait requires {}",
775 potentially_plural_count(trait_number_args, "parameter")));
777 err.note_trait_signature(trait_m.ident.to_string(),
778 trait_m.signature(tcx));
780 err.span_label(impl_span, format!("expected {}, found {}",
781 potentially_plural_count(trait_number_args, "parameter"), impl_number_args));
783 return Err(ErrorReported);
789 fn compare_synthetic_generics<'tcx>(
791 impl_m: &ty::AssocItem,
792 trait_m: &ty::AssocItem,
793 ) -> Result<(), ErrorReported> {
794 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
795 // 1. Better messages for the span labels
796 // 2. Explanation as to what is going on
797 // If we get here, we already have the same number of generics, so the zip will
799 let mut error_found = false;
800 let impl_m_generics = tcx.generics_of(impl_m.def_id);
801 let trait_m_generics = tcx.generics_of(trait_m.def_id);
802 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
803 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
804 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
806 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| {
808 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
809 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
812 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic))
813 in impl_m_type_params.zip(trait_m_type_params)
815 if impl_synthetic != trait_synthetic {
816 let impl_hir_id = tcx.hir().as_local_hir_id(impl_def_id).unwrap();
817 let impl_span = tcx.hir().span(impl_hir_id);
818 let trait_span = tcx.def_span(trait_def_id);
819 let mut err = struct_span_err!(tcx.sess,
822 "method `{}` has incompatible signature for trait",
824 err.span_label(trait_span, "declaration in trait here");
825 match (impl_synthetic, trait_synthetic) {
826 // The case where the impl method uses `impl Trait` but the trait method uses
828 (Some(hir::SyntheticTyParamKind::ImplTrait), None) => {
829 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
831 // try taking the name from the trait impl
832 // FIXME: this is obviously suboptimal since the name can already be used
833 // as another generic argument
837 .span_to_snippet(trait_span)
839 let trait_m = tcx.hir().as_local_hir_id(trait_m.def_id)?;
840 let trait_m = tcx.hir().trait_item(hir::TraitItemId { hir_id: trait_m });
842 let impl_m = tcx.hir().as_local_hir_id(impl_m.def_id)?;
843 let impl_m = tcx.hir().impl_item(hir::ImplItemId { hir_id: impl_m });
845 // in case there are no generics, take the spot between the function name
846 // and the opening paren of the argument list
847 let new_generics_span = tcx
850 .generate_fn_name_span(impl_span)?
852 // in case there are generics, just replace them
853 let generics_span = impl_m
856 .substitute_dummy(new_generics_span);
857 // replace with the generics from the trait
858 let new_generics = tcx
861 .span_to_snippet(trait_m.generics.span)
864 err.multipart_suggestion(
865 "try changing the `impl Trait` argument to a generic parameter",
867 // replace `impl Trait` with `T`
868 (impl_span, new_name),
869 // replace impl method generics with trait method generics
870 // This isn't quite right, as users might have changed the names
871 // of the generics, but it works for the common case
872 (generics_span, new_generics),
874 Applicability::MaybeIncorrect,
879 // The case where the trait method uses `impl Trait`, but the impl method uses
880 // explicit generics.
881 (None, Some(hir::SyntheticTyParamKind::ImplTrait)) => {
882 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
884 let impl_m = tcx.hir().as_local_hir_id(impl_m.def_id)?;
885 let impl_m = tcx.hir().impl_item(hir::ImplItemId { hir_id: impl_m });
886 let input_tys = match impl_m.kind {
887 hir::ImplItemKind::Method(ref sig, _) => &sig.decl.inputs,
890 struct Visitor(Option<Span>, hir::def_id::DefId);
891 impl<'v> hir::intravisit::Visitor<'v> for Visitor {
892 fn visit_ty(&mut self, ty: &'v hir::Ty) {
893 hir::intravisit::walk_ty(self, ty);
894 if let hir::TyKind::Path(
895 hir::QPath::Resolved(None, ref path)) = ty.kind
897 if let Res::Def(DefKind::TyParam, def_id) = path.res {
898 if def_id == self.1 {
899 self.0 = Some(ty.span);
904 fn nested_visit_map<'this>(
906 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
907 hir::intravisit::NestedVisitorMap::None
910 let mut visitor = Visitor(None, impl_def_id);
911 for ty in input_tys {
912 hir::intravisit::Visitor::visit_ty(&mut visitor, ty);
914 let span = visitor.0?;
916 let bounds = impl_m.generics.params.iter().find_map(|param| {
918 GenericParamKind::Lifetime { .. } => None,
919 GenericParamKind::Type { .. } |
920 GenericParamKind::Const { .. } => {
921 if param.hir_id == impl_hir_id {
929 let bounds = bounds.first()?.span().to(bounds.last()?.span());
933 .span_to_snippet(bounds)
936 err.multipart_suggestion(
937 "try removing the generic parameter and using `impl Trait` instead",
939 // delete generic parameters
940 (impl_m.generics.span, String::new()),
941 // replace param usage with `impl Trait`
942 (span, format!("impl {}", bounds)),
944 Applicability::MaybeIncorrect,
962 pub fn compare_const_impl<'tcx>(
964 impl_c: &ty::AssocItem,
966 trait_c: &ty::AssocItem,
967 impl_trait_ref: ty::TraitRef<'tcx>,
969 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
971 tcx.infer_ctxt().enter(|infcx| {
972 let param_env = tcx.param_env(impl_c.def_id);
973 let inh = Inherited::new(infcx, impl_c.def_id);
974 let infcx = &inh.infcx;
976 // The below is for the most part highly similar to the procedure
977 // for methods above. It is simpler in many respects, especially
978 // because we shouldn't really have to deal with lifetimes or
979 // predicates. In fact some of this should probably be put into
980 // shared functions because of DRY violations...
981 let trait_to_impl_substs = impl_trait_ref.substs;
983 // Create a parameter environment that represents the implementation's
985 let impl_c_hir_id = tcx.hir().as_local_hir_id(impl_c.def_id).unwrap();
987 // Compute placeholder form of impl and trait const tys.
988 let impl_ty = tcx.type_of(impl_c.def_id);
989 let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
990 let mut cause = ObligationCause::misc(impl_c_span, impl_c_hir_id);
992 // There is no "body" here, so just pass dummy id.
993 let impl_ty = inh.normalize_associated_types_in(impl_c_span,
998 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1000 let trait_ty = inh.normalize_associated_types_in(impl_c_span,
1005 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1007 let err = infcx.at(&cause, param_env)
1008 .sup(trait_ty, impl_ty)
1009 .map(|ok| inh.register_infer_ok_obligations(ok));
1011 if let Err(terr) = err {
1012 debug!("checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1016 // Locate the Span containing just the type of the offending impl
1017 match tcx.hir().expect_impl_item(impl_c_hir_id).kind {
1018 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
1019 _ => bug!("{:?} is not a impl const", impl_c),
1022 let mut diag = struct_span_err!(tcx.sess,
1025 "implemented const `{}` has an incompatible type for \
1029 let trait_c_hir_id = tcx.hir().as_local_hir_id(trait_c.def_id);
1030 let trait_c_span = trait_c_hir_id.map(|trait_c_hir_id| {
1031 // Add a label to the Span containing just the type of the const
1032 match tcx.hir().expect_trait_item(trait_c_hir_id).kind {
1033 TraitItemKind::Const(ref ty, _) => ty.span,
1034 _ => bug!("{:?} is not a trait const", trait_c),
1038 infcx.note_type_err(&mut diag,
1040 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1041 Some(infer::ValuePairs::Types(ExpectedFound {
1049 // Check that all obligations are satisfied by the implementation's
1051 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
1052 infcx.report_fulfillment_errors(errors, None, false);
1056 let fcx = FnCtxt::new(&inh, param_env, impl_c_hir_id);
1057 fcx.regionck_item(impl_c_hir_id, impl_c_span, &[]);