1 use rustc::hir::{self, GenericParamKind, ImplItemKind, TraitItemKind};
2 use rustc::infer::{self, InferOk};
3 use rustc::ty::{self, TyCtxt, GenericParamDefKind};
4 use rustc::ty::util::ExplicitSelf;
5 use rustc::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
6 use rustc::ty::error::{ExpectedFound, TypeError};
7 use rustc::ty::subst::{Subst, Substs};
8 use rustc::util::common::ErrorReported;
9 use errors::Applicability;
13 use super::{Inherited, FnCtxt, potentially_plural_count};
15 /// Checks that a method from an impl conforms to the signature of
16 /// the same method as declared in the trait.
20 /// - `impl_m`: type of the method we are checking
21 /// - `impl_m_span`: span to use for reporting errors
22 /// - `trait_m`: the method in the trait
23 /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
25 pub fn compare_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
26 impl_m: &ty::AssociatedItem,
28 trait_m: &ty::AssociatedItem,
29 impl_trait_ref: ty::TraitRef<'tcx>,
30 trait_item_span: Option<Span>) {
31 debug!("compare_impl_method(impl_trait_ref={:?})",
34 let impl_m_span = tcx.sess.source_map().def_span(impl_m_span);
36 if let Err(ErrorReported) = compare_self_type(tcx,
44 if let Err(ErrorReported) = compare_number_of_generics(tcx,
52 if let Err(ErrorReported) = compare_number_of_method_arguments(tcx,
60 if let Err(ErrorReported) = compare_synthetic_generics(tcx,
66 if let Err(ErrorReported) = compare_predicate_entailment(tcx,
75 fn compare_predicate_entailment<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
76 impl_m: &ty::AssociatedItem,
78 trait_m: &ty::AssociatedItem,
79 impl_trait_ref: ty::TraitRef<'tcx>)
80 -> Result<(), ErrorReported> {
81 let trait_to_impl_substs = impl_trait_ref.substs;
83 // This node-id should be used for the `body_id` field on each
84 // `ObligationCause` (and the `FnCtxt`). This is what
85 // `regionck_item` expects.
86 let impl_m_node_id = tcx.hir().as_local_node_id(impl_m.def_id).unwrap();
87 let impl_m_hir_id = tcx.hir().node_to_hir_id(impl_m_node_id);
89 let cause = ObligationCause {
91 body_id: impl_m_hir_id,
92 code: ObligationCauseCode::CompareImplMethodObligation {
93 item_name: impl_m.ident.name,
94 impl_item_def_id: impl_m.def_id,
95 trait_item_def_id: trait_m.def_id,
99 // This code is best explained by example. Consider a trait:
101 // trait Trait<'t,T> {
102 // fn method<'a,M>(t: &'t T, m: &'a M) -> Self;
107 // impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
108 // fn method<'b,N>(t: &'j &'i U, m: &'b N) -> Foo;
111 // We wish to decide if those two method types are compatible.
113 // We start out with trait_to_impl_substs, that maps the trait
114 // type parameters to impl type parameters. This is taken from the
115 // impl trait reference:
117 // trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
119 // We create a mapping `dummy_substs` that maps from the impl type
120 // parameters to fresh types and regions. For type parameters,
121 // this is the identity transform, but we could as well use any
122 // placeholder types. For regions, we convert from bound to free
123 // regions (Note: but only early-bound regions, i.e., those
124 // declared on the impl or used in type parameter bounds).
126 // impl_to_skol_substs = {'i => 'i0, U => U0, N => N0 }
128 // Now we can apply skol_substs to the type of the impl method
129 // to yield a new function type in terms of our fresh, placeholder
132 // <'b> fn(t: &'i0 U0, m: &'b) -> Foo
134 // We now want to extract and substitute the type of the *trait*
135 // method and compare it. To do so, we must create a compound
136 // substitution by combining trait_to_impl_substs and
137 // impl_to_skol_substs, and also adding a mapping for the method
138 // type parameters. We extend the mapping to also include
139 // the method parameters.
141 // trait_to_skol_substs = { T => &'i0 U0, Self => Foo, M => N0 }
143 // Applying this to the trait method type yields:
145 // <'a> fn(t: &'i0 U0, m: &'a) -> Foo
147 // This type is also the same but the name of the bound region ('a
148 // vs 'b). However, the normal subtyping rules on fn types handle
149 // this kind of equivalency just fine.
151 // We now use these substitutions to ensure that all declared bounds are
152 // satisfied by the implementation's method.
154 // We do this by creating a parameter environment which contains a
155 // substitution corresponding to impl_to_skol_substs. We then build
156 // trait_to_skol_substs and use it to convert the predicates contained
157 // in the trait_m.generics to the placeholder form.
159 // Finally we register each of these predicates as an obligation in
160 // a fresh FulfillmentCtxt, and invoke select_all_or_error.
162 // Create mapping from impl to placeholder.
163 let impl_to_skol_substs = Substs::identity_for_item(tcx, impl_m.def_id);
165 // Create mapping from trait to placeholder.
166 let trait_to_skol_substs = impl_to_skol_substs.rebase_onto(tcx,
167 impl_m.container.id(),
168 trait_to_impl_substs);
169 debug!("compare_impl_method: trait_to_skol_substs={:?}",
170 trait_to_skol_substs);
172 let impl_m_generics = tcx.generics_of(impl_m.def_id);
173 let trait_m_generics = tcx.generics_of(trait_m.def_id);
174 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
175 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
177 // Check region bounds.
178 check_region_bounds_on_impl_method(tcx,
184 trait_to_skol_substs)?;
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.
203 hybrid_preds.predicates.extend(
204 trait_m_predicates.instantiate_own(tcx, trait_to_skol_substs).predicates);
206 // Construct trait parameter environment and then shift it into the placeholder viewpoint.
207 // The key step here is to update the caller_bounds's predicates to be
208 // the new hybrid bounds we computed.
209 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
210 let param_env = ty::ParamEnv::new(
211 tcx.intern_predicates(&hybrid_preds.predicates),
215 let param_env = traits::normalize_param_env_or_error(tcx,
218 normalize_cause.clone());
220 tcx.infer_ctxt().enter(|infcx| {
221 let inh = Inherited::new(infcx, impl_m.def_id);
222 let infcx = &inh.infcx;
224 debug!("compare_impl_method: caller_bounds={:?}",
225 param_env.caller_bounds);
227 let mut selcx = traits::SelectionContext::new(&infcx);
229 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_skol_substs);
230 let (impl_m_own_bounds, _) = infcx.replace_bound_vars_with_fresh_vars(
232 infer::HigherRankedType,
233 &ty::Binder::bind(impl_m_own_bounds.predicates)
235 for predicate in impl_m_own_bounds {
236 let traits::Normalized { value: predicate, obligations } =
237 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), &predicate);
239 inh.register_predicates(obligations);
240 inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
243 // We now need to check that the signature of the impl method is
244 // compatible with that of the trait method. We do this by
245 // checking that `impl_fty <: trait_fty`.
247 // FIXME. Unfortunately, this doesn't quite work right now because
248 // associated type normalization is not integrated into subtype
249 // checks. For the comparison to be valid, we need to
250 // normalize the associated types in the impl/trait methods
251 // first. However, because function types bind regions, just
252 // calling `normalize_associated_types_in` would have no effect on
253 // any associated types appearing in the fn arguments or return
256 // Compute placeholder form of impl and trait method tys.
259 let (impl_sig, _) = infcx.replace_bound_vars_with_fresh_vars(
261 infer::HigherRankedType,
262 &tcx.fn_sig(impl_m.def_id)
265 inh.normalize_associated_types_in(impl_m_span,
269 let impl_fty = tcx.mk_fn_ptr(ty::Binder::bind(impl_sig));
270 debug!("compare_impl_method: impl_fty={:?}", impl_fty);
272 let trait_sig = tcx.liberate_late_bound_regions(
274 &tcx.fn_sig(trait_m.def_id));
276 trait_sig.subst(tcx, trait_to_skol_substs);
278 inh.normalize_associated_types_in(impl_m_span,
282 let trait_fty = tcx.mk_fn_ptr(ty::Binder::bind(trait_sig));
284 debug!("compare_impl_method: trait_fty={:?}", trait_fty);
286 let sub_result = infcx.at(&cause, param_env)
287 .sup(trait_fty, impl_fty)
288 .map(|InferOk { obligations, .. }| {
289 inh.register_predicates(obligations);
292 if let Err(terr) = sub_result {
293 debug!("sub_types failed: impl ty {:?}, trait ty {:?}",
297 let (impl_err_span, trait_err_span) = extract_spans_for_error_reporting(&infcx,
306 let cause = ObligationCause {
311 let mut diag = struct_span_err!(tcx.sess,
314 "method `{}` has an incompatible type for trait",
316 if let TypeError::Mutability = terr {
317 if let Some(trait_err_span) = trait_err_span {
318 if let Ok(trait_err_str) = tcx.sess.source_map()
319 .span_to_snippet(trait_err_span) {
320 diag.span_suggestion(
322 "consider change the type to match the mutability in trait",
324 Applicability::MachineApplicable,
330 infcx.note_type_err(&mut diag,
332 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
333 Some(infer::ValuePairs::Types(ExpectedFound {
339 return Err(ErrorReported);
342 // Check that all obligations are satisfied by the implementation's
344 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
345 infcx.report_fulfillment_errors(errors, None, false);
346 return Err(ErrorReported);
349 // Finally, resolve all regions. This catches wily misuses of
350 // lifetime parameters.
351 let fcx = FnCtxt::new(&inh, param_env, impl_m_hir_id);
352 fcx.regionck_item(impl_m_hir_id, impl_m_span, &[]);
358 fn check_region_bounds_on_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
360 impl_m: &ty::AssociatedItem,
361 trait_m: &ty::AssociatedItem,
362 trait_generics: &ty::Generics,
363 impl_generics: &ty::Generics,
364 trait_to_skol_substs: &Substs<'tcx>)
365 -> Result<(), ErrorReported> {
366 let trait_params = trait_generics.own_counts().lifetimes;
367 let impl_params = impl_generics.own_counts().lifetimes;
369 debug!("check_region_bounds_on_impl_method: \
370 trait_generics={:?} \
372 trait_to_skol_substs={:?}",
375 trait_to_skol_substs);
377 // Must have same number of early-bound lifetime parameters.
378 // Unfortunately, if the user screws up the bounds, then this
379 // will change classification between early and late. E.g.,
380 // if in trait we have `<'a,'b:'a>`, and in impl we just have
381 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
382 // in trait but 0 in the impl. But if we report "expected 2
383 // but found 0" it's confusing, because it looks like there
384 // are zero. Since I don't quite know how to phrase things at
385 // the moment, give a kind of vague error message.
386 if trait_params != impl_params {
387 let def_span = tcx.sess.source_map().def_span(span);
388 let span = tcx.hir().get_generics_span(impl_m.def_id).unwrap_or(def_span);
389 let mut err = struct_span_err!(
393 "lifetime parameters or bounds on method `{}` do not match the trait declaration",
396 err.span_label(span, "lifetimes do not match method in trait");
397 if let Some(sp) = tcx.hir().span_if_local(trait_m.def_id) {
398 let def_sp = tcx.sess.source_map().def_span(sp);
399 let sp = tcx.hir().get_generics_span(trait_m.def_id).unwrap_or(def_sp);
400 err.span_label(sp, "lifetimes in impl do not match this method in trait");
403 return Err(ErrorReported);
409 fn extract_spans_for_error_reporting<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
410 param_env: ty::ParamEnv<'tcx>,
412 cause: &ObligationCause<'tcx>,
413 impl_m: &ty::AssociatedItem,
414 impl_sig: ty::FnSig<'tcx>,
415 trait_m: &ty::AssociatedItem,
416 trait_sig: ty::FnSig<'tcx>)
417 -> (Span, Option<Span>) {
419 let impl_m_node_id = tcx.hir().as_local_node_id(impl_m.def_id).unwrap();
420 let (impl_m_output, impl_m_iter) = match tcx.hir().expect_impl_item(impl_m_node_id).node {
421 ImplItemKind::Method(ref impl_m_sig, _) => {
422 (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter())
424 _ => bug!("{:?} is not a method", impl_m),
428 TypeError::Mutability => {
429 if let Some(trait_m_node_id) = tcx.hir().as_local_node_id(trait_m.def_id) {
430 let trait_m_iter = match tcx.hir().expect_trait_item(trait_m_node_id).node {
431 TraitItemKind::Method(ref trait_m_sig, _) => {
432 trait_m_sig.decl.inputs.iter()
434 _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
437 impl_m_iter.zip(trait_m_iter).find(|&(ref impl_arg, ref trait_arg)| {
438 match (&impl_arg.node, &trait_arg.node) {
439 (&hir::TyKind::Rptr(_, ref impl_mt), &hir::TyKind::Rptr(_, ref trait_mt)) |
440 (&hir::TyKind::Ptr(ref impl_mt), &hir::TyKind::Ptr(ref trait_mt)) => {
441 impl_mt.mutbl != trait_mt.mutbl
445 }).map(|(ref impl_arg, ref trait_arg)| {
446 (impl_arg.span, Some(trait_arg.span))
448 .unwrap_or_else(|| (cause.span(&tcx), tcx.hir().span_if_local(trait_m.def_id)))
450 (cause.span(&tcx), tcx.hir().span_if_local(trait_m.def_id))
453 TypeError::Sorts(ExpectedFound { .. }) => {
454 if let Some(trait_m_node_id) = tcx.hir().as_local_node_id(trait_m.def_id) {
455 let (trait_m_output, trait_m_iter) =
456 match tcx.hir().expect_trait_item(trait_m_node_id).node {
457 TraitItemKind::Method(ref trait_m_sig, _) => {
458 (&trait_m_sig.decl.output, trait_m_sig.decl.inputs.iter())
460 _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
463 let impl_iter = impl_sig.inputs().iter();
464 let trait_iter = trait_sig.inputs().iter();
465 impl_iter.zip(trait_iter)
468 .filter_map(|(((&impl_arg_ty, &trait_arg_ty), impl_arg), trait_arg)|
469 match infcx.at(&cause, param_env).sub(trait_arg_ty, impl_arg_ty) {
471 Err(_) => Some((impl_arg.span, Some(trait_arg.span))),
477 infcx.at(&cause, param_env)
478 .sup(trait_sig.output(), impl_sig.output())
481 (impl_m_output.span(), Some(trait_m_output.span()))
483 (cause.span(&tcx), tcx.hir().span_if_local(trait_m.def_id))
487 (cause.span(&tcx), tcx.hir().span_if_local(trait_m.def_id))
490 _ => (cause.span(&tcx), tcx.hir().span_if_local(trait_m.def_id)),
494 fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
495 impl_m: &ty::AssociatedItem,
497 trait_m: &ty::AssociatedItem,
498 impl_trait_ref: ty::TraitRef<'tcx>)
499 -> Result<(), ErrorReported>
501 // Try to give more informative error messages about self typing
502 // mismatches. Note that any mismatch will also be detected
503 // below, where we construct a canonical function type that
504 // includes the self parameter as a normal parameter. It's just
505 // that the error messages you get out of this code are a bit more
506 // inscrutable, particularly for cases where one method has no
509 let self_string = |method: &ty::AssociatedItem| {
510 let untransformed_self_ty = match method.container {
511 ty::ImplContainer(_) => impl_trait_ref.self_ty(),
512 ty::TraitContainer(_) => tcx.mk_self_type()
514 let self_arg_ty = *tcx.fn_sig(method.def_id).input(0).skip_binder();
515 let param_env = ty::ParamEnv::reveal_all();
517 tcx.infer_ctxt().enter(|infcx| {
518 let self_arg_ty = tcx.liberate_late_bound_regions(
520 &ty::Binder::bind(self_arg_ty)
522 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
523 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
524 ExplicitSelf::ByValue => "self".to_owned(),
525 ExplicitSelf::ByReference(_, hir::MutImmutable) => "&self".to_owned(),
526 ExplicitSelf::ByReference(_, hir::MutMutable) => "&mut self".to_owned(),
527 _ => format!("self: {}", self_arg_ty)
532 match (trait_m.method_has_self_argument, impl_m.method_has_self_argument) {
533 (false, false) | (true, true) => {}
536 let self_descr = self_string(impl_m);
537 let mut err = struct_span_err!(tcx.sess,
540 "method `{}` has a `{}` declaration in the impl, but \
544 err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
545 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
546 err.span_label(span, format!("trait method declared without `{}`", self_descr));
548 err.note_trait_signature(trait_m.ident.to_string(),
549 trait_m.signature(&tcx));
552 return Err(ErrorReported);
556 let self_descr = self_string(trait_m);
557 let mut err = struct_span_err!(tcx.sess,
560 "method `{}` has a `{}` declaration in the trait, but \
564 err.span_label(impl_m_span, format!("expected `{}` in impl", self_descr));
565 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
566 err.span_label(span, format!("`{}` used in trait", self_descr));
568 err.note_trait_signature(trait_m.ident.to_string(),
569 trait_m.signature(&tcx));
572 return Err(ErrorReported);
579 fn compare_number_of_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
580 impl_m: &ty::AssociatedItem,
582 trait_m: &ty::AssociatedItem,
583 trait_item_span: Option<Span>)
584 -> Result<(), ErrorReported> {
585 let impl_m_generics = tcx.generics_of(impl_m.def_id);
586 let trait_m_generics = tcx.generics_of(trait_m.def_id);
587 let num_impl_m_type_params = impl_m_generics.own_counts().types;
588 let num_trait_m_type_params = trait_m_generics.own_counts().types;
590 if num_impl_m_type_params != num_trait_m_type_params {
591 let impl_m_node_id = tcx.hir().as_local_node_id(impl_m.def_id).unwrap();
592 let impl_m_item = tcx.hir().expect_impl_item(impl_m_node_id);
593 let span = if impl_m_item.generics.params.is_empty()
594 || impl_m_item.generics.span.is_dummy() // impl Trait in argument position (#55374)
598 impl_m_item.generics.span
601 let mut err = struct_span_err!(tcx.sess, span, E0049,
602 "method `{}` has {} but its trait declaration has {}",
604 potentially_plural_count(num_impl_m_type_params, "type parameter"),
605 potentially_plural_count(num_trait_m_type_params, "type parameter")
608 let mut suffix = None;
610 if let Some(span) = trait_item_span {
611 err.span_label(span, format!("expected {}",
612 potentially_plural_count(num_trait_m_type_params, "type parameter")));
614 suffix = Some(format!(", expected {}", num_trait_m_type_params));
618 format!("found {}{}",
619 potentially_plural_count(num_impl_m_type_params, "type parameter"),
620 suffix.as_ref().map(|s| &s[..]).unwrap_or("")));
624 return Err(ErrorReported);
630 fn compare_number_of_method_arguments<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
631 impl_m: &ty::AssociatedItem,
633 trait_m: &ty::AssociatedItem,
634 trait_item_span: Option<Span>)
635 -> Result<(), ErrorReported> {
636 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
637 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
638 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
639 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
640 if trait_number_args != impl_number_args {
641 let trait_m_node_id = tcx.hir().as_local_node_id(trait_m.def_id);
642 let trait_span = if let Some(trait_id) = trait_m_node_id {
643 match tcx.hir().expect_trait_item(trait_id).node {
644 TraitItemKind::Method(ref trait_m_sig, _) => {
645 let pos = if trait_number_args > 0 {
646 trait_number_args - 1
650 if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
654 Span::new(trait_m_sig.decl.inputs[0].span.lo(),
662 _ => bug!("{:?} is not a method", impl_m),
667 let impl_m_node_id = tcx.hir().as_local_node_id(impl_m.def_id).unwrap();
668 let impl_span = match tcx.hir().expect_impl_item(impl_m_node_id).node {
669 ImplItemKind::Method(ref impl_m_sig, _) => {
670 let pos = if impl_number_args > 0 {
675 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
679 Span::new(impl_m_sig.decl.inputs[0].span.lo(),
687 _ => bug!("{:?} is not a method", impl_m),
689 let mut err = struct_span_err!(tcx.sess,
692 "method `{}` has {} but the declaration in \
695 potentially_plural_count(impl_number_args, "parameter"),
696 tcx.item_path_str(trait_m.def_id),
698 if let Some(trait_span) = trait_span {
699 err.span_label(trait_span, format!("trait requires {}",
700 potentially_plural_count(trait_number_args, "parameter")));
702 err.note_trait_signature(trait_m.ident.to_string(),
703 trait_m.signature(&tcx));
705 err.span_label(impl_span, format!("expected {}, found {}",
706 potentially_plural_count(trait_number_args, "parameter"), impl_number_args));
708 return Err(ErrorReported);
714 fn compare_synthetic_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
715 impl_m: &ty::AssociatedItem,
716 trait_m: &ty::AssociatedItem)
717 -> Result<(), ErrorReported> {
718 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
719 // 1. Better messages for the span labels
720 // 2. Explanation as to what is going on
721 // If we get here, we already have the same number of generics, so the zip will
723 let mut error_found = false;
724 let impl_m_generics = tcx.generics_of(impl_m.def_id);
725 let trait_m_generics = tcx.generics_of(trait_m.def_id);
726 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
727 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
728 GenericParamDefKind::Lifetime => None,
730 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| {
732 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
733 GenericParamDefKind::Lifetime => None,
736 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic))
737 in impl_m_type_params.zip(trait_m_type_params)
739 if impl_synthetic != trait_synthetic {
740 let impl_hir_id = tcx.hir().as_local_hir_id(impl_def_id).unwrap();
741 let impl_span = tcx.hir().span_by_hir_id(impl_hir_id);
742 let trait_span = tcx.def_span(trait_def_id);
743 let mut err = struct_span_err!(tcx.sess,
746 "method `{}` has incompatible signature for trait",
748 err.span_label(trait_span, "declaration in trait here");
749 match (impl_synthetic, trait_synthetic) {
750 // The case where the impl method uses `impl Trait` but the trait method uses
752 (Some(hir::SyntheticTyParamKind::ImplTrait), None) => {
753 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
755 // try taking the name from the trait impl
756 // FIXME: this is obviously suboptimal since the name can already be used
757 // as another generic argument
761 .span_to_snippet(trait_span)
763 let trait_m = tcx.hir().as_local_node_id(trait_m.def_id)?;
764 let trait_m = tcx.hir().trait_item(hir::TraitItemId { node_id: trait_m });
766 let impl_m = tcx.hir().as_local_node_id(impl_m.def_id)?;
767 let impl_m = tcx.hir().impl_item(hir::ImplItemId { node_id: impl_m });
769 // in case there are no generics, take the spot between the function name
770 // and the opening paren of the argument list
771 let new_generics_span = tcx
774 .generate_fn_name_span(impl_span)?
776 // in case there are generics, just replace them
777 let generics_span = impl_m
780 .substitute_dummy(new_generics_span);
781 // replace with the generics from the trait
782 let new_generics = tcx
785 .span_to_snippet(trait_m.generics.span)
788 err.multipart_suggestion(
789 "try changing the `impl Trait` argument to a generic parameter",
791 // replace `impl Trait` with `T`
792 (impl_span, new_name),
793 // replace impl method generics with trait method generics
794 // This isn't quite right, as users might have changed the names
795 // of the generics, but it works for the common case
796 (generics_span, new_generics),
798 Applicability::MaybeIncorrect,
803 // The case where the trait method uses `impl Trait`, but the impl method uses
804 // explicit generics.
805 (None, Some(hir::SyntheticTyParamKind::ImplTrait)) => {
806 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
808 let impl_m = tcx.hir().as_local_node_id(impl_m.def_id)?;
809 let impl_m = tcx.hir().impl_item(hir::ImplItemId { node_id: impl_m });
810 let input_tys = match impl_m.node {
811 hir::ImplItemKind::Method(ref sig, _) => &sig.decl.inputs,
814 struct Visitor(Option<Span>, hir::def_id::DefId);
815 impl<'v> hir::intravisit::Visitor<'v> for Visitor {
816 fn visit_ty(&mut self, ty: &'v hir::Ty) {
817 hir::intravisit::walk_ty(self, ty);
818 if let hir::TyKind::Path(
819 hir::QPath::Resolved(None, ref path)) = ty.node
821 if let hir::def::Def::TyParam(def_id) = path.def {
822 if def_id == self.1 {
823 self.0 = Some(ty.span);
828 fn nested_visit_map<'this>(
830 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
831 hir::intravisit::NestedVisitorMap::None
834 let mut visitor = Visitor(None, impl_def_id);
835 for ty in input_tys {
836 hir::intravisit::Visitor::visit_ty(&mut visitor, ty);
838 let span = visitor.0?;
840 let bounds = impl_m.generics.params.iter().find_map(|param| {
842 GenericParamKind::Lifetime { .. } => None,
843 GenericParamKind::Type { .. } |
844 GenericParamKind::Const { .. } => {
845 if param.hir_id == impl_node_id {
853 let bounds = bounds.first()?.span().to(bounds.last()?.span());
857 .span_to_snippet(bounds)
860 err.multipart_suggestion(
861 "try removing the generic parameter and using `impl Trait` instead",
863 // delete generic parameters
864 (impl_m.generics.span, String::new()),
865 // replace param usage with `impl Trait`
866 (span, format!("impl {}", bounds)),
868 Applicability::MaybeIncorrect,
886 pub fn compare_const_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
887 impl_c: &ty::AssociatedItem,
889 trait_c: &ty::AssociatedItem,
890 impl_trait_ref: ty::TraitRef<'tcx>) {
891 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
893 tcx.infer_ctxt().enter(|infcx| {
894 let param_env = ty::ParamEnv::empty();
895 let inh = Inherited::new(infcx, impl_c.def_id);
896 let infcx = &inh.infcx;
898 // The below is for the most part highly similar to the procedure
899 // for methods above. It is simpler in many respects, especially
900 // because we shouldn't really have to deal with lifetimes or
901 // predicates. In fact some of this should probably be put into
902 // shared functions because of DRY violations...
903 let trait_to_impl_substs = impl_trait_ref.substs;
905 // Create a parameter environment that represents the implementation's
907 let impl_c_node_id = tcx.hir().as_local_node_id(impl_c.def_id).unwrap();
908 let impl_c_hir_id = tcx.hir().node_to_hir_id(impl_c_node_id);
910 // Compute placeholder form of impl and trait const tys.
911 let impl_ty = tcx.type_of(impl_c.def_id);
912 let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
913 let mut cause = ObligationCause::misc(impl_c_span, impl_c_hir_id);
915 // There is no "body" here, so just pass dummy id.
916 let impl_ty = inh.normalize_associated_types_in(impl_c_span,
921 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
923 let trait_ty = inh.normalize_associated_types_in(impl_c_span,
928 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
930 let err = infcx.at(&cause, param_env)
931 .sup(trait_ty, impl_ty)
932 .map(|ok| inh.register_infer_ok_obligations(ok));
934 if let Err(terr) = err {
935 debug!("checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
939 // Locate the Span containing just the type of the offending impl
940 match tcx.hir().expect_impl_item(impl_c_node_id).node {
941 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
942 _ => bug!("{:?} is not a impl const", impl_c),
945 let mut diag = struct_span_err!(tcx.sess,
948 "implemented const `{}` has an incompatible type for \
952 let trait_c_node_id = tcx.hir().as_local_node_id(trait_c.def_id);
953 let trait_c_span = trait_c_node_id.map(|trait_c_node_id| {
954 // Add a label to the Span containing just the type of the const
955 match tcx.hir().expect_trait_item(trait_c_node_id).node {
956 TraitItemKind::Const(ref ty, _) => ty.span,
957 _ => bug!("{:?} is not a trait const", trait_c),
961 infcx.note_type_err(&mut diag,
963 trait_c_span.map(|span| (span, "type in trait".to_owned())),
964 Some(infer::ValuePairs::Types(ExpectedFound {
972 // Check that all obligations are satisfied by the implementation's
974 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
975 infcx.report_fulfillment_errors(errors, None, false);
979 let fcx = FnCtxt::new(&inh, param_env, impl_c_hir_id);
980 fcx.regionck_item(impl_c_hir_id, impl_c_span, &[]);