1 use rustc::hir::map::Map;
2 use rustc::infer::{self, InferOk};
3 use rustc::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
4 use rustc::ty::error::{ExpectedFound, TypeError};
5 use rustc::ty::subst::{InternalSubsts, Subst};
6 use rustc::ty::util::ExplicitSelf;
7 use rustc::ty::{self, GenericParamDefKind, TyCtxt};
8 use rustc::util::common::ErrorReported;
9 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId};
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::intravisit;
13 use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind};
16 use super::{potentially_plural_count, FnCtxt, Inherited};
18 use rustc_error_codes::*;
20 /// Checks that a method from an impl conforms to the signature of
21 /// the same method as declared in the trait.
25 /// - `impl_m`: type of the method we are checking
26 /// - `impl_m_span`: span to use for reporting errors
27 /// - `trait_m`: the method in the trait
28 /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
30 crate fn compare_impl_method<'tcx>(
32 impl_m: &ty::AssocItem,
34 trait_m: &ty::AssocItem,
35 impl_trait_ref: ty::TraitRef<'tcx>,
36 trait_item_span: Option<Span>,
38 debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref);
40 let impl_m_span = tcx.sess.source_map().def_span(impl_m_span);
42 if let Err(ErrorReported) = compare_self_type(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
47 if let Err(ErrorReported) =
48 compare_number_of_generics(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
53 if let Err(ErrorReported) =
54 compare_number_of_method_arguments(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
59 if let Err(ErrorReported) = compare_synthetic_generics(tcx, impl_m, trait_m) {
63 if let Err(ErrorReported) =
64 compare_predicate_entailment(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
70 fn compare_predicate_entailment<'tcx>(
72 impl_m: &ty::AssocItem,
74 trait_m: &ty::AssocItem,
75 impl_trait_ref: ty::TraitRef<'tcx>,
76 ) -> Result<(), ErrorReported> {
77 let trait_to_impl_substs = impl_trait_ref.substs;
79 // This node-id should be used for the `body_id` field on each
80 // `ObligationCause` (and the `FnCtxt`). This is what
81 // `regionck_item` expects.
82 let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id).unwrap();
84 let cause = ObligationCause {
86 body_id: impl_m_hir_id,
87 code: ObligationCauseCode::CompareImplMethodObligation {
88 item_name: impl_m.ident.name,
89 impl_item_def_id: impl_m.def_id,
90 trait_item_def_id: trait_m.def_id,
94 // This code is best explained by example. Consider a trait:
96 // trait Trait<'t,T> {
97 // fn method<'a,M>(t: &'t T, m: &'a M) -> Self;
102 // impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
103 // fn method<'b,N>(t: &'j &'i U, m: &'b N) -> Foo;
106 // We wish to decide if those two method types are compatible.
108 // We start out with trait_to_impl_substs, that maps the trait
109 // type parameters to impl type parameters. This is taken from the
110 // impl trait reference:
112 // trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
114 // We create a mapping `dummy_substs` that maps from the impl type
115 // parameters to fresh types and regions. For type parameters,
116 // this is the identity transform, but we could as well use any
117 // placeholder types. For regions, we convert from bound to free
118 // regions (Note: but only early-bound regions, i.e., those
119 // declared on the impl or used in type parameter bounds).
121 // impl_to_skol_substs = {'i => 'i0, U => U0, N => N0 }
123 // Now we can apply skol_substs to the type of the impl method
124 // to yield a new function type in terms of our fresh, placeholder
127 // <'b> fn(t: &'i0 U0, m: &'b) -> Foo
129 // We now want to extract and substitute the type of the *trait*
130 // method and compare it. To do so, we must create a compound
131 // substitution by combining trait_to_impl_substs and
132 // impl_to_skol_substs, and also adding a mapping for the method
133 // type parameters. We extend the mapping to also include
134 // the method parameters.
136 // trait_to_skol_substs = { T => &'i0 U0, Self => Foo, M => N0 }
138 // Applying this to the trait method type yields:
140 // <'a> fn(t: &'i0 U0, m: &'a) -> Foo
142 // This type is also the same but the name of the bound region ('a
143 // vs 'b). However, the normal subtyping rules on fn types handle
144 // this kind of equivalency just fine.
146 // We now use these substitutions to ensure that all declared bounds are
147 // satisfied by the implementation's method.
149 // We do this by creating a parameter environment which contains a
150 // substitution corresponding to impl_to_skol_substs. We then build
151 // trait_to_skol_substs and use it to convert the predicates contained
152 // in the trait_m.generics to the placeholder form.
154 // Finally we register each of these predicates as an obligation in
155 // a fresh FulfillmentCtxt, and invoke select_all_or_error.
157 // Create mapping from impl to placeholder.
158 let impl_to_skol_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
160 // Create mapping from trait to placeholder.
161 let trait_to_skol_substs =
162 impl_to_skol_substs.rebase_onto(tcx, impl_m.container.id(), trait_to_impl_substs);
163 debug!("compare_impl_method: trait_to_skol_substs={:?}", trait_to_skol_substs);
165 let impl_m_generics = tcx.generics_of(impl_m.def_id);
166 let trait_m_generics = tcx.generics_of(trait_m.def_id);
167 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
168 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
170 // Check region bounds.
171 check_region_bounds_on_impl_item(
180 // Create obligations for each predicate declared by the impl
181 // definition in the context of the trait's parameter
182 // environment. We can't just use `impl_env.caller_bounds`,
183 // however, because we want to replace all late-bound regions with
185 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
186 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
188 debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
190 // This is the only tricky bit of the new way we check implementation methods
191 // We need to build a set of predicates where only the method-level bounds
192 // are from the trait and we assume all other bounds from the implementation
193 // to be previously satisfied.
195 // We then register the obligations from the impl_m and check to see
196 // if all constraints hold.
199 .extend(trait_m_predicates.instantiate_own(tcx, trait_to_skol_substs).predicates);
201 // Construct trait parameter environment and then shift it into the placeholder viewpoint.
202 // The key step here is to update the caller_bounds's predicates to be
203 // the new hybrid bounds we computed.
204 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
205 let param_env = ty::ParamEnv::new(
206 tcx.intern_predicates(&hybrid_preds.predicates),
210 let param_env = traits::normalize_param_env_or_error(
214 normalize_cause.clone(),
217 tcx.infer_ctxt().enter(|infcx| {
218 let inh = Inherited::new(infcx, impl_m.def_id);
219 let infcx = &inh.infcx;
221 debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds);
223 let mut selcx = traits::SelectionContext::new(&infcx);
225 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_skol_substs);
226 let (impl_m_own_bounds, _) = infcx.replace_bound_vars_with_fresh_vars(
228 infer::HigherRankedType,
229 &ty::Binder::bind(impl_m_own_bounds.predicates),
231 for predicate in impl_m_own_bounds {
232 let traits::Normalized { value: predicate, obligations } =
233 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), &predicate);
235 inh.register_predicates(obligations);
236 inh.register_predicate(traits::Obligation::new(cause.clone(), 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 (impl_sig, _) = infcx.replace_bound_vars_with_fresh_vars(
257 infer::HigherRankedType,
258 &tcx.fn_sig(impl_m.def_id),
261 inh.normalize_associated_types_in(impl_m_span, impl_m_hir_id, param_env, &impl_sig);
262 let impl_fty = tcx.mk_fn_ptr(ty::Binder::bind(impl_sig));
263 debug!("compare_impl_method: impl_fty={:?}", impl_fty);
265 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, &tcx.fn_sig(trait_m.def_id));
266 let trait_sig = trait_sig.subst(tcx, trait_to_skol_substs);
268 inh.normalize_associated_types_in(impl_m_span, impl_m_hir_id, param_env, &trait_sig);
269 let trait_fty = tcx.mk_fn_ptr(ty::Binder::bind(trait_sig));
271 debug!("compare_impl_method: trait_fty={:?}", trait_fty);
273 let sub_result = infcx.at(&cause, param_env).sup(trait_fty, impl_fty).map(
274 |InferOk { obligations, .. }| {
275 inh.register_predicates(obligations);
279 if let Err(terr) = sub_result {
280 debug!("sub_types failed: impl ty {:?}, trait ty {:?}", impl_fty, trait_fty);
282 let (impl_err_span, trait_err_span) = extract_spans_for_error_reporting(
283 &infcx, param_env, &terr, &cause, impl_m, impl_sig, trait_m, trait_sig,
286 let cause = ObligationCause { span: impl_err_span, ..cause };
288 let mut diag = struct_span_err!(
292 "method `{}` has an incompatible type for trait",
295 if let TypeError::Mutability = terr {
296 if let Some(trait_err_span) = trait_err_span {
297 if let Ok(trait_err_str) = tcx.sess.source_map().span_to_snippet(trait_err_span)
299 diag.span_suggestion(
301 "consider change the type to match the mutability in trait",
303 Applicability::MachineApplicable,
312 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
313 Some(infer::ValuePairs::Types(ExpectedFound {
320 return Err(ErrorReported);
323 // Check that all obligations are satisfied by the implementation's
325 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
326 infcx.report_fulfillment_errors(errors, None, false);
327 return Err(ErrorReported);
330 // Finally, resolve all regions. This catches wily misuses of
331 // lifetime parameters.
332 let fcx = FnCtxt::new(&inh, param_env, impl_m_hir_id);
333 fcx.regionck_item(impl_m_hir_id, impl_m_span, &[]);
339 fn check_region_bounds_on_impl_item<'tcx>(
342 impl_m: &ty::AssocItem,
343 trait_m: &ty::AssocItem,
344 trait_generics: &ty::Generics,
345 impl_generics: &ty::Generics,
346 ) -> Result<(), ErrorReported> {
347 let trait_params = trait_generics.own_counts().lifetimes;
348 let impl_params = impl_generics.own_counts().lifetimes;
351 "check_region_bounds_on_impl_item: \
352 trait_generics={:?} \
354 trait_generics, impl_generics
357 // Must have same number of early-bound lifetime parameters.
358 // Unfortunately, if the user screws up the bounds, then this
359 // will change classification between early and late. E.g.,
360 // if in trait we have `<'a,'b:'a>`, and in impl we just have
361 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
362 // in trait but 0 in the impl. But if we report "expected 2
363 // but found 0" it's confusing, because it looks like there
364 // are zero. Since I don't quite know how to phrase things at
365 // the moment, give a kind of vague error message.
366 if trait_params != impl_params {
367 let item_kind = assoc_item_kind_str(impl_m);
368 let def_span = tcx.sess.source_map().def_span(span);
369 let span = tcx.hir().get_generics(impl_m.def_id).map(|g| g.span).unwrap_or(def_span);
370 let mut err = struct_span_err!(
374 "lifetime parameters or bounds on {} `{}` do not match the trait declaration",
378 err.span_label(span, &format!("lifetimes do not match {} in trait", item_kind));
379 if let Some(sp) = tcx.hir().span_if_local(trait_m.def_id) {
380 let def_sp = tcx.sess.source_map().def_span(sp);
381 let sp = tcx.hir().get_generics(trait_m.def_id).map(|g| g.span).unwrap_or(def_sp);
384 &format!("lifetimes in impl do not match this {} in trait", item_kind),
388 return Err(ErrorReported);
394 fn extract_spans_for_error_reporting<'a, 'tcx>(
395 infcx: &infer::InferCtxt<'a, 'tcx>,
396 param_env: ty::ParamEnv<'tcx>,
397 terr: &TypeError<'_>,
398 cause: &ObligationCause<'tcx>,
399 impl_m: &ty::AssocItem,
400 impl_sig: ty::FnSig<'tcx>,
401 trait_m: &ty::AssocItem,
402 trait_sig: ty::FnSig<'tcx>,
403 ) -> (Span, Option<Span>) {
405 let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id).unwrap();
406 let (impl_m_output, impl_m_iter) = match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
407 ImplItemKind::Method(ref impl_m_sig, _) => {
408 (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter())
410 _ => bug!("{:?} is not a method", impl_m),
414 TypeError::Mutability => {
415 if let Some(trait_m_hir_id) = tcx.hir().as_local_hir_id(trait_m.def_id) {
416 let trait_m_iter = match tcx.hir().expect_trait_item(trait_m_hir_id).kind {
417 TraitItemKind::Method(ref trait_m_sig, _) => trait_m_sig.decl.inputs.iter(),
418 _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
423 .find(|&(ref impl_arg, ref trait_arg)| {
424 match (&impl_arg.kind, &trait_arg.kind) {
426 &hir::TyKind::Rptr(_, ref impl_mt),
427 &hir::TyKind::Rptr(_, ref trait_mt),
429 | (&hir::TyKind::Ptr(ref impl_mt), &hir::TyKind::Ptr(ref trait_mt)) => {
430 impl_mt.mutbl != trait_mt.mutbl
435 .map(|(ref impl_arg, ref trait_arg)| (impl_arg.span, Some(trait_arg.span)))
436 .unwrap_or_else(|| (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)))
438 (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
441 TypeError::Sorts(ExpectedFound { .. }) => {
442 if let Some(trait_m_hir_id) = tcx.hir().as_local_hir_id(trait_m.def_id) {
443 let (trait_m_output, trait_m_iter) =
444 match tcx.hir().expect_trait_item(trait_m_hir_id).kind {
445 TraitItemKind::Method(ref trait_m_sig, _) => {
446 (&trait_m_sig.decl.output, trait_m_sig.decl.inputs.iter())
448 _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
451 let impl_iter = impl_sig.inputs().iter();
452 let trait_iter = trait_sig.inputs().iter();
458 |(((&impl_arg_ty, &trait_arg_ty), impl_arg), trait_arg)| match infcx
459 .at(&cause, param_env)
460 .sub(trait_arg_ty, impl_arg_ty)
463 Err(_) => Some((impl_arg.span, Some(trait_arg.span))),
469 .at(&cause, param_env)
470 .sup(trait_sig.output(), impl_sig.output())
473 (impl_m_output.span(), Some(trait_m_output.span()))
475 (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
479 (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
482 _ => (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)),
486 fn compare_self_type<'tcx>(
488 impl_m: &ty::AssocItem,
490 trait_m: &ty::AssocItem,
491 impl_trait_ref: ty::TraitRef<'tcx>,
492 ) -> Result<(), ErrorReported> {
493 // Try to give more informative error messages about self typing
494 // mismatches. Note that any mismatch will also be detected
495 // below, where we construct a canonical function type that
496 // includes the self parameter as a normal parameter. It's just
497 // that the error messages you get out of this code are a bit more
498 // inscrutable, particularly for cases where one method has no
501 let self_string = |method: &ty::AssocItem| {
502 let untransformed_self_ty = match method.container {
503 ty::ImplContainer(_) => impl_trait_ref.self_ty(),
504 ty::TraitContainer(_) => tcx.types.self_param,
506 let self_arg_ty = *tcx.fn_sig(method.def_id).input(0).skip_binder();
507 let param_env = ty::ParamEnv::reveal_all();
509 tcx.infer_ctxt().enter(|infcx| {
511 tcx.liberate_late_bound_regions(method.def_id, &ty::Binder::bind(self_arg_ty));
512 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
513 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
514 ExplicitSelf::ByValue => "self".to_owned(),
515 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
516 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
517 _ => format!("self: {}", self_arg_ty),
522 match (trait_m.method_has_self_argument, impl_m.method_has_self_argument) {
523 (false, false) | (true, true) => {}
526 let self_descr = self_string(impl_m);
527 let mut err = struct_span_err!(
531 "method `{}` has a `{}` declaration in the impl, but \
536 err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
537 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
538 err.span_label(span, format!("trait method declared without `{}`", self_descr));
540 err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
543 return Err(ErrorReported);
547 let self_descr = self_string(trait_m);
548 let mut err = struct_span_err!(
552 "method `{}` has a `{}` declaration in the trait, but \
557 err.span_label(impl_m_span, format!("expected `{}` in impl", self_descr));
558 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
559 err.span_label(span, format!("`{}` used in trait", self_descr));
561 err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
564 return Err(ErrorReported);
571 fn compare_number_of_generics<'tcx>(
573 impl_: &ty::AssocItem,
575 trait_: &ty::AssocItem,
576 trait_span: Option<Span>,
577 ) -> Result<(), ErrorReported> {
578 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
579 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
582 ("type", trait_own_counts.types, impl_own_counts.types),
583 ("const", trait_own_counts.consts, impl_own_counts.consts),
586 let item_kind = assoc_item_kind_str(impl_);
588 let mut err_occurred = false;
589 for &(kind, trait_count, impl_count) in &matchings {
590 if impl_count != trait_count {
593 let (trait_spans, impl_trait_spans) =
594 if let Some(trait_hir_id) = tcx.hir().as_local_hir_id(trait_.def_id) {
595 let trait_item = tcx.hir().expect_trait_item(trait_hir_id);
596 if trait_item.generics.params.is_empty() {
597 (Some(vec![trait_item.generics.span]), vec![])
599 let arg_spans: Vec<Span> =
600 trait_item.generics.params.iter().map(|p| p.span).collect();
601 let impl_trait_spans: Vec<Span> = trait_item
605 .filter_map(|p| match p.kind {
606 GenericParamKind::Type {
607 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
613 (Some(arg_spans), impl_trait_spans)
616 (trait_span.map(|s| vec![s]), vec![])
619 let impl_hir_id = tcx.hir().as_local_hir_id(impl_.def_id).unwrap();
620 let impl_item = tcx.hir().expect_impl_item(impl_hir_id);
621 let impl_item_impl_trait_spans: Vec<Span> = impl_item
625 .filter_map(|p| match p.kind {
626 GenericParamKind::Type {
627 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
633 let spans = impl_item.generics.spans();
634 let span = spans.primary_span();
636 let mut err = tcx.sess.struct_span_err_with_code(
639 "{} `{}` has {} {kind} parameter{} but its trait \
640 declaration has {} {kind} parameter{}",
644 pluralize!(impl_count),
646 pluralize!(trait_count),
649 DiagnosticId::Error("E0049".into()),
652 let mut suffix = None;
654 if let Some(spans) = trait_spans {
655 let mut spans = spans.iter();
656 if let Some(span) = spans.next() {
660 "expected {} {} parameter{}",
663 pluralize!(trait_count),
668 err.span_label(*span, "");
671 suffix = Some(format!(", expected {}", trait_count));
674 if let Some(span) = span {
678 "found {} {} parameter{}{}",
681 pluralize!(impl_count),
682 suffix.unwrap_or_else(|| String::new()),
687 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
688 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
695 if err_occurred { Err(ErrorReported) } else { Ok(()) }
698 fn compare_number_of_method_arguments<'tcx>(
700 impl_m: &ty::AssocItem,
702 trait_m: &ty::AssocItem,
703 trait_item_span: Option<Span>,
704 ) -> Result<(), ErrorReported> {
705 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
706 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
707 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
708 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
709 if trait_number_args != impl_number_args {
710 let trait_m_hir_id = tcx.hir().as_local_hir_id(trait_m.def_id);
711 let trait_span = if let Some(trait_id) = trait_m_hir_id {
712 match tcx.hir().expect_trait_item(trait_id).kind {
713 TraitItemKind::Method(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) {
720 trait_m_sig.decl.inputs[0].span.lo(),
729 _ => bug!("{:?} is not a method", impl_m),
734 let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id).unwrap();
735 let impl_span = match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
736 ImplItemKind::Method(ref impl_m_sig, _) => {
737 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
738 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
743 impl_m_sig.decl.inputs[0].span.lo(),
752 _ => bug!("{:?} is not a method", impl_m),
754 let mut err = struct_span_err!(
758 "method `{}` has {} but the declaration in \
761 potentially_plural_count(impl_number_args, "parameter"),
762 tcx.def_path_str(trait_m.def_id),
765 if let Some(trait_span) = trait_span {
770 potentially_plural_count(trait_number_args, "parameter")
774 err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
779 "expected {}, found {}",
780 potentially_plural_count(trait_number_args, "parameter"),
785 return Err(ErrorReported);
791 fn compare_synthetic_generics<'tcx>(
793 impl_m: &ty::AssocItem,
794 trait_m: &ty::AssocItem,
795 ) -> Result<(), ErrorReported> {
796 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
797 // 1. Better messages for the span labels
798 // 2. Explanation as to what is going on
799 // If we get here, we already have the same number of generics, so the zip will
801 let mut error_found = false;
802 let impl_m_generics = tcx.generics_of(impl_m.def_id);
803 let trait_m_generics = tcx.generics_of(trait_m.def_id);
804 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
805 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
806 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
808 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
809 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
810 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
812 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
813 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!(
823 "method `{}` has incompatible signature for trait",
826 err.span_label(trait_span, "declaration in trait here");
827 match (impl_synthetic, trait_synthetic) {
828 // The case where the impl method uses `impl Trait` but the trait method uses
830 (Some(hir::SyntheticTyParamKind::ImplTrait), None) => {
831 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
833 // try taking the name from the trait impl
834 // FIXME: this is obviously suboptimal since the name can already be used
835 // as another generic argument
836 let new_name = tcx.sess.source_map().span_to_snippet(trait_span).ok()?;
837 let trait_m = tcx.hir().as_local_hir_id(trait_m.def_id)?;
838 let trait_m = tcx.hir().trait_item(hir::TraitItemId { hir_id: trait_m });
840 let impl_m = tcx.hir().as_local_hir_id(impl_m.def_id)?;
841 let impl_m = tcx.hir().impl_item(hir::ImplItemId { hir_id: impl_m });
843 // in case there are no generics, take the spot between the function name
844 // and the opening paren of the argument list
845 let new_generics_span =
846 tcx.sess.source_map().generate_fn_name_span(impl_span)?.shrink_to_hi();
847 // in case there are generics, just replace them
849 impl_m.generics.span.substitute_dummy(new_generics_span);
850 // replace with the generics from the trait
852 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
854 err.multipart_suggestion(
855 "try changing the `impl Trait` argument to a generic parameter",
857 // replace `impl Trait` with `T`
858 (impl_span, new_name),
859 // replace impl method generics with trait method generics
860 // This isn't quite right, as users might have changed the names
861 // of the generics, but it works for the common case
862 (generics_span, new_generics),
864 Applicability::MaybeIncorrect,
869 // The case where the trait method uses `impl Trait`, but the impl method uses
870 // explicit generics.
871 (None, Some(hir::SyntheticTyParamKind::ImplTrait)) => {
872 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
874 let impl_m = tcx.hir().as_local_hir_id(impl_m.def_id)?;
875 let impl_m = tcx.hir().impl_item(hir::ImplItemId { hir_id: impl_m });
876 let input_tys = match impl_m.kind {
877 hir::ImplItemKind::Method(ref sig, _) => sig.decl.inputs,
880 struct Visitor(Option<Span>, hir::def_id::DefId);
881 impl<'v> intravisit::Visitor<'v> for Visitor {
882 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
883 intravisit::walk_ty(self, ty);
884 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
887 if let Res::Def(DefKind::TyParam, def_id) = path.res {
888 if def_id == self.1 {
889 self.0 = Some(ty.span);
897 ) -> intravisit::NestedVisitorMap<'_, Self::Map>
899 intravisit::NestedVisitorMap::None
902 let mut visitor = Visitor(None, impl_def_id);
903 for ty in input_tys {
904 intravisit::Visitor::visit_ty(&mut visitor, ty);
906 let span = visitor.0?;
909 impl_m.generics.params.iter().find_map(|param| match param.kind {
910 GenericParamKind::Lifetime { .. } => None,
911 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
912 if param.hir_id == impl_hir_id {
919 let bounds = bounds.first()?.span().to(bounds.last()?.span());
920 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
922 err.multipart_suggestion(
923 "try removing the generic parameter and using `impl Trait` instead",
925 // delete generic parameters
926 (impl_m.generics.span, String::new()),
927 // replace param usage with `impl Trait`
928 (span, format!("impl {}", bounds)),
930 Applicability::MaybeIncorrect,
941 if error_found { Err(ErrorReported) } else { Ok(()) }
944 crate fn compare_const_impl<'tcx>(
946 impl_c: &ty::AssocItem,
948 trait_c: &ty::AssocItem,
949 impl_trait_ref: ty::TraitRef<'tcx>,
951 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
953 tcx.infer_ctxt().enter(|infcx| {
954 let param_env = tcx.param_env(impl_c.def_id);
955 let inh = Inherited::new(infcx, impl_c.def_id);
956 let infcx = &inh.infcx;
958 // The below is for the most part highly similar to the procedure
959 // for methods above. It is simpler in many respects, especially
960 // because we shouldn't really have to deal with lifetimes or
961 // predicates. In fact some of this should probably be put into
962 // shared functions because of DRY violations...
963 let trait_to_impl_substs = impl_trait_ref.substs;
965 // Create a parameter environment that represents the implementation's
967 let impl_c_hir_id = tcx.hir().as_local_hir_id(impl_c.def_id).unwrap();
969 // Compute placeholder form of impl and trait const tys.
970 let impl_ty = tcx.type_of(impl_c.def_id);
971 let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
972 let mut cause = ObligationCause::misc(impl_c_span, impl_c_hir_id);
974 // There is no "body" here, so just pass dummy id.
976 inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, &impl_ty);
978 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
981 inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, &trait_ty);
983 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
986 .at(&cause, param_env)
987 .sup(trait_ty, impl_ty)
988 .map(|ok| inh.register_infer_ok_obligations(ok));
990 if let Err(terr) = err {
992 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
996 // Locate the Span containing just the type of the offending impl
997 match tcx.hir().expect_impl_item(impl_c_hir_id).kind {
998 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
999 _ => bug!("{:?} is not a impl const", impl_c),
1002 let mut diag = struct_span_err!(
1006 "implemented const `{}` has an incompatible type for \
1011 let trait_c_hir_id = tcx.hir().as_local_hir_id(trait_c.def_id);
1012 let trait_c_span = trait_c_hir_id.map(|trait_c_hir_id| {
1013 // Add a label to the Span containing just the type of the const
1014 match tcx.hir().expect_trait_item(trait_c_hir_id).kind {
1015 TraitItemKind::Const(ref ty, _) => ty.span,
1016 _ => bug!("{:?} is not a trait const", trait_c),
1020 infcx.note_type_err(
1023 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1024 Some(infer::ValuePairs::Types(ExpectedFound {
1033 // Check that all obligations are satisfied by the implementation's
1035 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
1036 infcx.report_fulfillment_errors(errors, None, false);
1040 let fcx = FnCtxt::new(&inh, param_env, impl_c_hir_id);
1041 fcx.regionck_item(impl_c_hir_id, impl_c_span, &[]);
1045 crate fn compare_ty_impl<'tcx>(
1047 impl_ty: &ty::AssocItem,
1049 trait_ty: &ty::AssocItem,
1050 impl_trait_ref: ty::TraitRef<'tcx>,
1051 trait_item_span: Option<Span>,
1053 debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1055 let _: Result<(), ErrorReported> = (|| {
1056 compare_number_of_generics(tcx, impl_ty, impl_ty_span, trait_ty, trait_item_span)?;
1058 compare_type_predicate_entailment(tcx, impl_ty, impl_ty_span, trait_ty, impl_trait_ref)
1062 /// The equivalent of [compare_predicate_entailment], but for associated types
1063 /// instead of associated functions.
1064 fn compare_type_predicate_entailment(
1066 impl_ty: &ty::AssocItem,
1068 trait_ty: &ty::AssocItem,
1069 impl_trait_ref: ty::TraitRef<'tcx>,
1070 ) -> Result<(), ErrorReported> {
1071 let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1072 let trait_to_impl_substs =
1073 impl_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1075 let impl_ty_generics = tcx.generics_of(impl_ty.def_id);
1076 let trait_ty_generics = tcx.generics_of(trait_ty.def_id);
1077 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1078 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1080 check_region_bounds_on_impl_item(
1089 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1091 if impl_ty_own_bounds.is_empty() {
1092 // Nothing to check.
1096 // This `HirId` should be used for the `body_id` field on each
1097 // `ObligationCause` (and the `FnCtxt`). This is what
1098 // `regionck_item` expects.
1099 let impl_ty_hir_id = tcx.hir().as_local_hir_id(impl_ty.def_id).unwrap();
1100 let cause = ObligationCause {
1102 body_id: impl_ty_hir_id,
1103 code: ObligationCauseCode::CompareImplTypeObligation {
1104 item_name: impl_ty.ident.name,
1105 impl_item_def_id: impl_ty.def_id,
1106 trait_item_def_id: trait_ty.def_id,
1110 debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1112 // The predicates declared by the impl definition, the trait and the
1113 // associated type in the trait are assumed.
1114 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1115 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1118 .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1120 debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1122 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1123 let param_env = ty::ParamEnv::new(
1124 tcx.intern_predicates(&hybrid_preds.predicates),
1128 let param_env = traits::normalize_param_env_or_error(
1132 normalize_cause.clone(),
1134 tcx.infer_ctxt().enter(|infcx| {
1135 let inh = Inherited::new(infcx, impl_ty.def_id);
1136 let infcx = &inh.infcx;
1138 debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds);
1140 let mut selcx = traits::SelectionContext::new(&infcx);
1142 for predicate in impl_ty_own_bounds.predicates {
1143 let traits::Normalized { value: predicate, obligations } =
1144 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), &predicate);
1146 inh.register_predicates(obligations);
1147 inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
1150 // Check that all obligations are satisfied by the implementation's
1152 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
1153 infcx.report_fulfillment_errors(errors, None, false);
1154 return Err(ErrorReported);
1157 // Finally, resolve all regions. This catches wily misuses of
1158 // lifetime parameters.
1159 let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
1160 fcx.regionck_item(impl_ty_hir_id, impl_ty_span, &[]);
1166 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
1167 match impl_item.kind {
1168 ty::AssocKind::Const => "const",
1169 ty::AssocKind::Method => "method",
1170 ty::AssocKind::Type | ty::AssocKind::OpaqueTy => "type",