1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use rustc::hir::{self, ImplItemKind, TraitItemKind};
12 use rustc::infer::{self, InferOk};
13 use rustc::ty::{self, TyCtxt};
14 use rustc::ty::util::ExplicitSelf;
15 use rustc::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
16 use rustc::ty::error::{ExpectedFound, TypeError};
17 use rustc::ty::subst::{Subst, Substs};
18 use rustc::util::common::ErrorReported;
22 use super::{Inherited, FnCtxt};
24 /// Checks that a method from an impl conforms to the signature of
25 /// the same method as declared in the trait.
29 /// - impl_m: type of the method we are checking
30 /// - impl_m_span: span to use for reporting errors
31 /// - trait_m: the method in the trait
32 /// - impl_trait_ref: the TraitRef corresponding to the trait implementation
34 pub fn compare_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
35 impl_m: &ty::AssociatedItem,
37 trait_m: &ty::AssociatedItem,
38 impl_trait_ref: ty::TraitRef<'tcx>,
39 trait_item_span: Option<Span>) {
40 debug!("compare_impl_method(impl_trait_ref={:?})",
43 let impl_m_span = tcx.sess.codemap().def_span(impl_m_span);
45 if let Err(ErrorReported) = compare_self_type(tcx,
53 if let Err(ErrorReported) = compare_number_of_generics(tcx,
61 if let Err(ErrorReported) = compare_number_of_method_arguments(tcx,
69 if let Err(ErrorReported) = compare_synthetic_generics(tcx,
77 if let Err(ErrorReported) = compare_predicate_entailment(tcx,
86 fn compare_predicate_entailment<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
87 impl_m: &ty::AssociatedItem,
89 trait_m: &ty::AssociatedItem,
90 impl_trait_ref: ty::TraitRef<'tcx>)
91 -> Result<(), ErrorReported> {
92 let trait_to_impl_substs = impl_trait_ref.substs;
94 // This node-id should be used for the `body_id` field on each
95 // `ObligationCause` (and the `FnCtxt`). This is what
96 // `regionck_item` expects.
97 let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
99 let cause = ObligationCause {
101 body_id: impl_m_node_id,
102 code: ObligationCauseCode::CompareImplMethodObligation {
103 item_name: impl_m.name,
104 impl_item_def_id: impl_m.def_id,
105 trait_item_def_id: trait_m.def_id,
109 // This code is best explained by example. Consider a trait:
111 // trait Trait<'t,T> {
112 // fn method<'a,M>(t: &'t T, m: &'a M) -> Self;
117 // impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
118 // fn method<'b,N>(t: &'j &'i U, m: &'b N) -> Foo;
121 // We wish to decide if those two method types are compatible.
123 // We start out with trait_to_impl_substs, that maps the trait
124 // type parameters to impl type parameters. This is taken from the
125 // impl trait reference:
127 // trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
129 // We create a mapping `dummy_substs` that maps from the impl type
130 // parameters to fresh types and regions. For type parameters,
131 // this is the identity transform, but we could as well use any
132 // skolemized types. For regions, we convert from bound to free
133 // regions (Note: but only early-bound regions, i.e., those
134 // declared on the impl or used in type parameter bounds).
136 // impl_to_skol_substs = {'i => 'i0, U => U0, N => N0 }
138 // Now we can apply skol_substs to the type of the impl method
139 // to yield a new function type in terms of our fresh, skolemized
142 // <'b> fn(t: &'i0 U0, m: &'b) -> Foo
144 // We now want to extract and substitute the type of the *trait*
145 // method and compare it. To do so, we must create a compound
146 // substitution by combining trait_to_impl_substs and
147 // impl_to_skol_substs, and also adding a mapping for the method
148 // type parameters. We extend the mapping to also include
149 // the method parameters.
151 // trait_to_skol_substs = { T => &'i0 U0, Self => Foo, M => N0 }
153 // Applying this to the trait method type yields:
155 // <'a> fn(t: &'i0 U0, m: &'a) -> Foo
157 // This type is also the same but the name of the bound region ('a
158 // vs 'b). However, the normal subtyping rules on fn types handle
159 // this kind of equivalency just fine.
161 // We now use these substitutions to ensure that all declared bounds are
162 // satisfied by the implementation's method.
164 // We do this by creating a parameter environment which contains a
165 // substitution corresponding to impl_to_skol_substs. We then build
166 // trait_to_skol_substs and use it to convert the predicates contained
167 // in the trait_m.generics to the skolemized form.
169 // Finally we register each of these predicates as an obligation in
170 // a fresh FulfillmentCtxt, and invoke select_all_or_error.
172 // Create mapping from impl to skolemized.
173 let impl_to_skol_substs = Substs::identity_for_item(tcx, impl_m.def_id);
175 // Create mapping from trait to skolemized.
176 let trait_to_skol_substs = impl_to_skol_substs.rebase_onto(tcx,
177 impl_m.container.id(),
178 trait_to_impl_substs);
179 debug!("compare_impl_method: trait_to_skol_substs={:?}",
180 trait_to_skol_substs);
182 let impl_m_generics = tcx.generics_of(impl_m.def_id);
183 let trait_m_generics = tcx.generics_of(trait_m.def_id);
184 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
185 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
187 // Check region bounds.
188 check_region_bounds_on_impl_method(tcx,
194 trait_to_skol_substs)?;
196 // Create obligations for each predicate declared by the impl
197 // definition in the context of the trait's parameter
198 // environment. We can't just use `impl_env.caller_bounds`,
199 // however, because we want to replace all late-bound regions with
201 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
202 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
204 debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
206 // This is the only tricky bit of the new way we check implementation methods
207 // We need to build a set of predicates where only the method-level bounds
208 // are from the trait and we assume all other bounds from the implementation
209 // to be previously satisfied.
211 // We then register the obligations from the impl_m and check to see
212 // if all constraints hold.
213 hybrid_preds.predicates
214 .extend(trait_m_predicates.instantiate_own(tcx, trait_to_skol_substs).predicates);
216 // Construct trait parameter environment and then shift it into the skolemized viewpoint.
217 // The key step here is to update the caller_bounds's predicates to be
218 // the new hybrid bounds we computed.
219 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_node_id);
220 let param_env = ty::ParamEnv::new(tcx.intern_predicates(&hybrid_preds.predicates),
222 let param_env = traits::normalize_param_env_or_error(tcx,
225 normalize_cause.clone());
227 tcx.infer_ctxt().enter(|infcx| {
228 let inh = Inherited::new(infcx, impl_m.def_id);
229 let infcx = &inh.infcx;
231 debug!("compare_impl_method: caller_bounds={:?}",
232 param_env.caller_bounds);
234 let mut selcx = traits::SelectionContext::new(&infcx);
236 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_skol_substs);
237 let (impl_m_own_bounds, _) = infcx.replace_late_bound_regions_with_fresh_var(impl_m_span,
238 infer::HigherRankedType,
239 &ty::Binder(impl_m_own_bounds.predicates));
240 for predicate in impl_m_own_bounds {
241 let traits::Normalized { value: predicate, obligations } =
242 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), &predicate);
244 inh.register_predicates(obligations);
245 inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
248 // We now need to check that the signature of the impl method is
249 // compatible with that of the trait method. We do this by
250 // checking that `impl_fty <: trait_fty`.
252 // FIXME. Unfortunately, this doesn't quite work right now because
253 // associated type normalization is not integrated into subtype
254 // checks. For the comparison to be valid, we need to
255 // normalize the associated types in the impl/trait methods
256 // first. However, because function types bind regions, just
257 // calling `normalize_associated_types_in` would have no effect on
258 // any associated types appearing in the fn arguments or return
261 // Compute skolemized form of impl and trait method tys.
265 infcx.replace_late_bound_regions_with_fresh_var(impl_m_span,
266 infer::HigherRankedType,
267 &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(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(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",
321 infcx.note_type_err(&mut diag,
323 trait_err_span.map(|sp| (sp, format!("type in trait"))),
324 Some(infer::ValuePairs::Types(ExpectedFound {
330 return Err(ErrorReported);
333 // Check that all obligations are satisfied by the implementation's
335 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
336 infcx.report_fulfillment_errors(errors, None);
337 return Err(ErrorReported);
340 // Finally, resolve all regions. This catches wily misuses of
341 // lifetime parameters.
342 let fcx = FnCtxt::new(&inh, param_env, impl_m_node_id);
343 fcx.regionck_item(impl_m_node_id, impl_m_span, &[]);
349 fn check_region_bounds_on_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
351 impl_m: &ty::AssociatedItem,
352 trait_m: &ty::AssociatedItem,
353 trait_generics: &ty::Generics,
354 impl_generics: &ty::Generics,
355 trait_to_skol_substs: &Substs<'tcx>)
356 -> Result<(), ErrorReported> {
357 let span = tcx.sess.codemap().def_span(span);
358 let trait_params = &trait_generics.regions[..];
359 let impl_params = &impl_generics.regions[..];
361 debug!("check_region_bounds_on_impl_method: \
362 trait_generics={:?} \
364 trait_to_skol_substs={:?}",
367 trait_to_skol_substs);
369 // Must have same number of early-bound lifetime parameters.
370 // Unfortunately, if the user screws up the bounds, then this
371 // will change classification between early and late. E.g.,
372 // if in trait we have `<'a,'b:'a>`, and in impl we just have
373 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
374 // in trait but 0 in the impl. But if we report "expected 2
375 // but found 0" it's confusing, because it looks like there
376 // are zero. Since I don't quite know how to phrase things at
377 // the moment, give a kind of vague error message.
378 if trait_params.len() != impl_params.len() {
379 let mut err = struct_span_err!(tcx.sess,
382 "lifetime parameters or bounds on method `{}` do not match \
383 the trait declaration",
385 err.span_label(span, "lifetimes do not match method in trait");
386 if let Some(sp) = tcx.hir.span_if_local(trait_m.def_id) {
387 err.span_label(tcx.sess.codemap().def_span(sp),
388 "lifetimes in impl do not match this method in trait");
391 return Err(ErrorReported);
397 fn extract_spans_for_error_reporting<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
398 param_env: ty::ParamEnv<'tcx>,
400 cause: &ObligationCause<'tcx>,
401 impl_m: &ty::AssociatedItem,
402 impl_sig: ty::FnSig<'tcx>,
403 trait_m: &ty::AssociatedItem,
404 trait_sig: ty::FnSig<'tcx>)
405 -> (Span, Option<Span>) {
407 let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
408 let (impl_m_output, impl_m_iter) = match tcx.hir.expect_impl_item(impl_m_node_id).node {
409 ImplItemKind::Method(ref impl_m_sig, _) => {
410 (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter())
412 _ => bug!("{:?} is not a method", impl_m),
416 TypeError::Mutability => {
417 if let Some(trait_m_node_id) = tcx.hir.as_local_node_id(trait_m.def_id) {
418 let trait_m_iter = match tcx.hir.expect_trait_item(trait_m_node_id).node {
419 TraitItemKind::Method(ref trait_m_sig, _) => {
420 trait_m_sig.decl.inputs.iter()
422 _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
425 impl_m_iter.zip(trait_m_iter).find(|&(ref impl_arg, ref trait_arg)| {
426 match (&impl_arg.node, &trait_arg.node) {
427 (&hir::TyRptr(_, ref impl_mt), &hir::TyRptr(_, ref trait_mt)) |
428 (&hir::TyPtr(ref impl_mt), &hir::TyPtr(ref trait_mt)) => {
429 impl_mt.mutbl != trait_mt.mutbl
433 }).map(|(ref impl_arg, ref trait_arg)| {
434 (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_node_id) = tcx.hir.as_local_node_id(trait_m.def_id) {
443 let (trait_m_output, trait_m_iter) =
444 match tcx.hir.expect_trait_item(trait_m_node_id).node {
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();
453 impl_iter.zip(trait_iter)
456 .filter_map(|(((&impl_arg_ty, &trait_arg_ty), impl_arg), trait_arg)| {
457 match infcx.at(&cause, param_env).sub(trait_arg_ty, impl_arg_ty) {
459 Err(_) => Some((impl_arg.span, Some(trait_arg.span))),
465 infcx.at(&cause, param_env)
466 .sup(trait_sig.output(), impl_sig.output())
469 (impl_m_output.span(), Some(trait_m_output.span()))
471 (cause.span(&tcx), tcx.hir.span_if_local(trait_m.def_id))
475 (cause.span(&tcx), tcx.hir.span_if_local(trait_m.def_id))
478 _ => (cause.span(&tcx), tcx.hir.span_if_local(trait_m.def_id)),
482 fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
483 impl_m: &ty::AssociatedItem,
485 trait_m: &ty::AssociatedItem,
486 impl_trait_ref: ty::TraitRef<'tcx>)
487 -> Result<(), ErrorReported>
489 // Try to give more informative error messages about self typing
490 // mismatches. Note that any mismatch will also be detected
491 // below, where we construct a canonical function type that
492 // includes the self parameter as a normal parameter. It's just
493 // that the error messages you get out of this code are a bit more
494 // inscrutable, particularly for cases where one method has no
497 let self_string = |method: &ty::AssociatedItem| {
498 let untransformed_self_ty = match method.container {
499 ty::ImplContainer(_) => impl_trait_ref.self_ty(),
500 ty::TraitContainer(_) => tcx.mk_self_type()
502 let self_arg_ty = *tcx.fn_sig(method.def_id).input(0).skip_binder();
503 let param_env = ty::ParamEnv::empty(Reveal::All);
505 tcx.infer_ctxt().enter(|infcx| {
506 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
507 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
508 ExplicitSelf::ByValue => "self".to_string(),
509 ExplicitSelf::ByReference(_, hir::MutImmutable) => "&self".to_string(),
510 ExplicitSelf::ByReference(_, hir::MutMutable) => "&mut self".to_string(),
511 _ => format!("self: {}", self_arg_ty)
516 match (trait_m.method_has_self_argument, impl_m.method_has_self_argument) {
517 (false, false) | (true, true) => {}
520 let self_descr = self_string(impl_m);
521 let mut err = struct_span_err!(tcx.sess,
524 "method `{}` has a `{}` declaration in the impl, but \
528 err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
529 if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
530 err.span_label(span, format!("trait method declared without `{}`", self_descr));
532 err.note_trait_signature(trait_m.name.to_string(),
533 trait_m.signature(&tcx));
536 return Err(ErrorReported);
540 let self_descr = self_string(trait_m);
541 let mut err = struct_span_err!(tcx.sess,
544 "method `{}` has a `{}` declaration in the trait, but \
548 err.span_label(impl_m_span, format!("expected `{}` in impl", self_descr));
549 if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
550 err.span_label(span, format!("`{}` used in trait", self_descr));
552 err.note_trait_signature(trait_m.name.to_string(),
553 trait_m.signature(&tcx));
556 return Err(ErrorReported);
563 fn compare_number_of_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
564 impl_m: &ty::AssociatedItem,
566 trait_m: &ty::AssociatedItem,
567 trait_item_span: Option<Span>)
568 -> Result<(), ErrorReported> {
569 let impl_m_generics = tcx.generics_of(impl_m.def_id);
570 let trait_m_generics = tcx.generics_of(trait_m.def_id);
571 let num_impl_m_type_params = impl_m_generics.types.len();
572 let num_trait_m_type_params = trait_m_generics.types.len();
573 if num_impl_m_type_params != num_trait_m_type_params {
574 let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
575 let impl_m_item = tcx.hir.expect_impl_item(impl_m_node_id);
576 let span = if impl_m_item.generics.params.is_empty() {
579 impl_m_item.generics.span
582 let mut err = struct_span_err!(tcx.sess,
585 "method `{}` has {} type parameter{} but its trait \
586 declaration has {} type parameter{}",
588 num_impl_m_type_params,
589 if num_impl_m_type_params == 1 { "" } else { "s" },
590 num_trait_m_type_params,
591 if num_trait_m_type_params == 1 {
597 let mut suffix = None;
599 if let Some(span) = trait_item_span {
601 format!("expected {}",
602 &if num_trait_m_type_params != 1 {
603 format!("{} type parameters", num_trait_m_type_params)
605 format!("{} type parameter", num_trait_m_type_params)
608 suffix = Some(format!(", expected {}", num_trait_m_type_params));
612 format!("found {}{}",
613 &if num_impl_m_type_params != 1 {
614 format!("{} type parameters", num_impl_m_type_params)
616 format!("1 type parameter")
618 suffix.as_ref().map(|s| &s[..]).unwrap_or("")));
622 return Err(ErrorReported);
628 fn compare_number_of_method_arguments<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
629 impl_m: &ty::AssociatedItem,
631 trait_m: &ty::AssociatedItem,
632 trait_item_span: Option<Span>)
633 -> Result<(), ErrorReported> {
634 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
635 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
636 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
637 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
638 if trait_number_args != impl_number_args {
639 let trait_m_node_id = tcx.hir.as_local_node_id(trait_m.def_id);
640 let trait_span = if let Some(trait_id) = trait_m_node_id {
641 match tcx.hir.expect_trait_item(trait_id).node {
642 TraitItemKind::Method(ref trait_m_sig, _) => {
643 if let Some(arg) = trait_m_sig.decl.inputs.get(if trait_number_args > 0 {
644 trait_number_args - 1
653 _ => bug!("{:?} is not a method", impl_m),
658 let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
659 let impl_span = match tcx.hir.expect_impl_item(impl_m_node_id).node {
660 ImplItemKind::Method(ref impl_m_sig, _) => {
661 if let Some(arg) = impl_m_sig.decl.inputs.get(if impl_number_args > 0 {
671 _ => bug!("{:?} is not a method", impl_m),
673 let mut err = struct_span_err!(tcx.sess,
676 "method `{}` has {} parameter{} but the declaration in \
680 if impl_number_args == 1 { "" } else { "s" },
681 tcx.item_path_str(trait_m.def_id),
683 if let Some(trait_span) = trait_span {
684 err.span_label(trait_span,
685 format!("trait requires {}",
686 &if trait_number_args != 1 {
687 format!("{} parameters", trait_number_args)
689 format!("{} parameter", trait_number_args)
692 err.note_trait_signature(trait_m.name.to_string(),
693 trait_m.signature(&tcx));
695 err.span_label(impl_span,
696 format!("expected {}, found {}",
697 &if trait_number_args != 1 {
698 format!("{} parameters", trait_number_args)
700 format!("{} parameter", trait_number_args)
704 return Err(ErrorReported);
710 fn compare_synthetic_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
711 impl_m: &ty::AssociatedItem,
712 _impl_m_span: Span, // FIXME necessary?
713 trait_m: &ty::AssociatedItem,
714 _trait_item_span: Option<Span>) // FIXME necessary?
715 -> Result<(), ErrorReported> {
716 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
717 // 1. Better messages for the span lables
718 // 2. Explanation as to what is going on
719 // 3. Correct the function signature for what we actually use
720 // If we get here, we already have the same number of generics, so the zip will
722 let mut error_found = false;
723 let impl_m_generics = tcx.generics_of(impl_m.def_id);
724 let trait_m_generics = tcx.generics_of(trait_m.def_id);
725 for (impl_ty, trait_ty) in impl_m_generics.types.iter().zip(trait_m_generics.types.iter()) {
726 if impl_ty.synthetic != trait_ty.synthetic {
727 let impl_node_id = tcx.hir.as_local_node_id(impl_ty.def_id).unwrap();
728 let impl_span = tcx.hir.span(impl_node_id);
729 let trait_node_id = tcx.hir.as_local_node_id(trait_ty.def_id).unwrap();
730 let trait_span = tcx.hir.span(trait_node_id);
731 let mut err = struct_span_err!(tcx.sess,
734 "method `{}` has incompatible signature for trait",
736 err.span_label(trait_span, "annotation in trait");
737 err.span_label(impl_span, "annotation in impl");
749 pub fn compare_const_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
750 impl_c: &ty::AssociatedItem,
752 trait_c: &ty::AssociatedItem,
753 impl_trait_ref: ty::TraitRef<'tcx>) {
754 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
756 tcx.infer_ctxt().enter(|infcx| {
757 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
758 let inh = Inherited::new(infcx, impl_c.def_id);
759 let infcx = &inh.infcx;
761 // The below is for the most part highly similar to the procedure
762 // for methods above. It is simpler in many respects, especially
763 // because we shouldn't really have to deal with lifetimes or
764 // predicates. In fact some of this should probably be put into
765 // shared functions because of DRY violations...
766 let trait_to_impl_substs = impl_trait_ref.substs;
768 // Create a parameter environment that represents the implementation's
770 let impl_c_node_id = tcx.hir.as_local_node_id(impl_c.def_id).unwrap();
772 // Compute skolemized form of impl and trait const tys.
773 let impl_ty = tcx.type_of(impl_c.def_id);
774 let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
775 let mut cause = ObligationCause::misc(impl_c_span, impl_c_node_id);
777 // There is no "body" here, so just pass dummy id.
778 let impl_ty = inh.normalize_associated_types_in(impl_c_span,
783 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
785 let trait_ty = inh.normalize_associated_types_in(impl_c_span,
790 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
792 let err = infcx.at(&cause, param_env)
793 .sup(trait_ty, impl_ty)
794 .map(|ok| inh.register_infer_ok_obligations(ok));
796 if let Err(terr) = err {
797 debug!("checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
801 // Locate the Span containing just the type of the offending impl
802 match tcx.hir.expect_impl_item(impl_c_node_id).node {
803 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
804 _ => bug!("{:?} is not a impl const", impl_c),
807 let mut diag = struct_span_err!(tcx.sess,
810 "implemented const `{}` has an incompatible type for \
814 let trait_c_node_id = tcx.hir.as_local_node_id(trait_c.def_id);
815 let trait_c_span = trait_c_node_id.map(|trait_c_node_id| {
816 // Add a label to the Span containing just the type of the const
817 match tcx.hir.expect_trait_item(trait_c_node_id).node {
818 TraitItemKind::Const(ref ty, _) => ty.span,
819 _ => bug!("{:?} is not a trait const", trait_c),
823 infcx.note_type_err(&mut diag,
825 trait_c_span.map(|span| (span, format!("type in trait"))),
826 Some(infer::ValuePairs::Types(ExpectedFound {
834 // Check that all obligations are satisfied by the implementation's
836 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
837 infcx.report_fulfillment_errors(errors, None);
841 let fcx = FnCtxt::new(&inh, param_env, impl_c_node_id);
842 fcx.regionck_item(impl_c_node_id, impl_c_span, &[]);