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::middle::free_region::FreeRegionMap;
14 use rustc::middle::region::RegionMaps;
15 use rustc::ty::{self, TyCtxt};
16 use rustc::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
17 use rustc::ty::error::{ExpectedFound, TypeError};
18 use rustc::ty::subst::{Subst, Substs};
19 use rustc::util::common::ErrorReported;
23 use super::{Inherited, FnCtxt};
24 use astconv::ExplicitSelf;
26 /// Checks that a method from an impl conforms to the signature of
27 /// the same method as declared in the trait.
31 /// - impl_m: type of the method we are checking
32 /// - impl_m_span: span to use for reporting errors
33 /// - trait_m: the method in the trait
34 /// - impl_trait_ref: the TraitRef corresponding to the trait implementation
36 pub fn compare_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
37 impl_m: &ty::AssociatedItem,
39 trait_m: &ty::AssociatedItem,
40 impl_trait_ref: ty::TraitRef<'tcx>,
41 trait_item_span: Option<Span>,
42 old_broken_mode: bool) {
43 debug!("compare_impl_method(impl_trait_ref={:?})",
46 if let Err(ErrorReported) = compare_self_type(tcx,
54 if let Err(ErrorReported) = compare_number_of_generics(tcx,
62 if let Err(ErrorReported) = compare_number_of_method_arguments(tcx,
70 if let Err(ErrorReported) = compare_predicate_entailment(tcx,
80 fn compare_predicate_entailment<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
81 impl_m: &ty::AssociatedItem,
83 trait_m: &ty::AssociatedItem,
84 impl_trait_ref: ty::TraitRef<'tcx>,
85 old_broken_mode: bool)
86 -> Result<(), ErrorReported> {
87 let trait_to_impl_substs = impl_trait_ref.substs;
89 // This node-id should be used for the `body_id` field on each
90 // `ObligationCause` (and the `FnCtxt`). This is what
91 // `regionck_item` expects.
92 let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
94 let cause = ObligationCause {
96 body_id: impl_m_node_id,
97 code: ObligationCauseCode::CompareImplMethodObligation {
98 item_name: impl_m.name,
99 impl_item_def_id: impl_m.def_id,
100 trait_item_def_id: trait_m.def_id,
101 lint_id: if !old_broken_mode { Some(impl_m_node_id) } else { None },
105 // This code is best explained by example. Consider a trait:
107 // trait Trait<'t,T> {
108 // fn method<'a,M>(t: &'t T, m: &'a M) -> Self;
113 // impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
114 // fn method<'b,N>(t: &'j &'i U, m: &'b N) -> Foo;
117 // We wish to decide if those two method types are compatible.
119 // We start out with trait_to_impl_substs, that maps the trait
120 // type parameters to impl type parameters. This is taken from the
121 // impl trait reference:
123 // trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
125 // We create a mapping `dummy_substs` that maps from the impl type
126 // parameters to fresh types and regions. For type parameters,
127 // this is the identity transform, but we could as well use any
128 // skolemized types. For regions, we convert from bound to free
129 // regions (Note: but only early-bound regions, i.e., those
130 // declared on the impl or used in type parameter bounds).
132 // impl_to_skol_substs = {'i => 'i0, U => U0, N => N0 }
134 // Now we can apply skol_substs to the type of the impl method
135 // to yield a new function type in terms of our fresh, skolemized
138 // <'b> fn(t: &'i0 U0, m: &'b) -> Foo
140 // We now want to extract and substitute the type of the *trait*
141 // method and compare it. To do so, we must create a compound
142 // substitution by combining trait_to_impl_substs and
143 // impl_to_skol_substs, and also adding a mapping for the method
144 // type parameters. We extend the mapping to also include
145 // the method parameters.
147 // trait_to_skol_substs = { T => &'i0 U0, Self => Foo, M => N0 }
149 // Applying this to the trait method type yields:
151 // <'a> fn(t: &'i0 U0, m: &'a) -> Foo
153 // This type is also the same but the name of the bound region ('a
154 // vs 'b). However, the normal subtyping rules on fn types handle
155 // this kind of equivalency just fine.
157 // We now use these substitutions to ensure that all declared bounds are
158 // satisfied by the implementation's method.
160 // We do this by creating a parameter environment which contains a
161 // substitution corresponding to impl_to_skol_substs. We then build
162 // trait_to_skol_substs and use it to convert the predicates contained
163 // in the trait_m.generics to the skolemized form.
165 // Finally we register each of these predicates as an obligation in
166 // a fresh FulfillmentCtxt, and invoke select_all_or_error.
168 // Create mapping from impl to skolemized.
169 let impl_to_skol_substs = Substs::identity_for_item(tcx, impl_m.def_id);
171 // Create mapping from trait to skolemized.
172 let trait_to_skol_substs = impl_to_skol_substs.rebase_onto(tcx,
173 impl_m.container.id(),
174 trait_to_impl_substs);
175 debug!("compare_impl_method: trait_to_skol_substs={:?}",
176 trait_to_skol_substs);
178 let impl_m_generics = tcx.generics_of(impl_m.def_id);
179 let trait_m_generics = tcx.generics_of(trait_m.def_id);
180 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
181 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
183 // Check region bounds.
184 check_region_bounds_on_impl_method(tcx,
189 trait_to_skol_substs)?;
191 // Create obligations for each predicate declared by the impl
192 // definition in the context of the trait's parameter
193 // environment. We can't just use `impl_env.caller_bounds`,
194 // however, because we want to replace all late-bound regions with
196 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
197 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
199 debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
201 // This is the only tricky bit of the new way we check implementation methods
202 // We need to build a set of predicates where only the method-level bounds
203 // are from the trait and we assume all other bounds from the implementation
204 // to be previously satisfied.
206 // We then register the obligations from the impl_m and check to see
207 // if all constraints hold.
208 hybrid_preds.predicates
209 .extend(trait_m_predicates.instantiate_own(tcx, trait_to_skol_substs).predicates);
211 // Construct trait parameter environment and then shift it into the skolemized viewpoint.
212 // The key step here is to update the caller_bounds's predicates to be
213 // the new hybrid bounds we computed.
214 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_node_id);
215 let param_env = ty::ParamEnv::new(tcx.intern_predicates(&hybrid_preds.predicates),
217 let param_env = traits::normalize_param_env_or_error(tcx,
220 normalize_cause.clone());
222 tcx.infer_ctxt().enter(|infcx| {
223 let inh = Inherited::new(infcx, impl_m.def_id);
224 let infcx = &inh.infcx;
226 debug!("compare_impl_method: caller_bounds={:?}",
227 param_env.caller_bounds);
229 let mut selcx = traits::SelectionContext::new(&infcx);
231 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_skol_substs);
232 let (impl_m_own_bounds, _) = infcx.replace_late_bound_regions_with_fresh_var(impl_m_span,
233 infer::HigherRankedType,
234 &ty::Binder(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 skolemized form of impl and trait method tys.
260 infcx.replace_late_bound_regions_with_fresh_var(impl_m_span,
261 infer::HigherRankedType,
262 &tcx.fn_sig(impl_m.def_id));
264 inh.normalize_associated_types_in(impl_m_span,
268 let impl_fty = tcx.mk_fn_ptr(ty::Binder(impl_sig));
269 debug!("compare_impl_method: impl_fty={:?}", impl_fty);
271 let trait_sig = inh.liberate_late_bound_regions(
273 &tcx.fn_sig(trait_m.def_id));
275 trait_sig.subst(tcx, trait_to_skol_substs);
277 inh.normalize_associated_types_in(impl_m_span,
281 let trait_fty = tcx.mk_fn_ptr(ty::Binder(trait_sig));
283 debug!("compare_impl_method: trait_fty={:?}", trait_fty);
285 let sub_result = infcx.at(&cause, param_env)
286 .sup(trait_fty, impl_fty)
287 .map(|InferOk { obligations, .. }| {
288 inh.register_predicates(obligations);
291 if let Err(terr) = sub_result {
292 debug!("sub_types failed: impl ty {:?}, trait ty {:?}",
296 let (impl_err_span, trait_err_span) = extract_spans_for_error_reporting(&infcx,
305 let cause = ObligationCause {
310 let mut diag = struct_span_err!(tcx.sess,
313 "method `{}` has an incompatible type for trait",
316 infcx.note_type_err(&mut diag,
318 trait_err_span.map(|sp| (sp, format!("type in trait"))),
319 Some(infer::ValuePairs::Types(ExpectedFound {
325 return Err(ErrorReported);
328 // Check that all obligations are satisfied by the implementation's
330 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
331 infcx.report_fulfillment_errors(errors, None);
332 return Err(ErrorReported);
335 // Finally, resolve all regions. This catches wily misuses of
336 // lifetime parameters.
338 // FIXME(#18937) -- this is how the code used to
339 // work. This is buggy because the fulfillment cx creates
340 // region obligations that get overlooked. The right
341 // thing to do is the code below. But we keep this old
342 // pass around temporarily.
343 let region_maps = RegionMaps::new();
344 let mut free_regions = FreeRegionMap::new();
345 free_regions.relate_free_regions_from_predicates(¶m_env.caller_bounds);
346 infcx.resolve_regions_and_report_errors(impl_m.def_id, ®ion_maps, &free_regions);
348 let fcx = FnCtxt::new(&inh, param_env, impl_m_node_id);
349 fcx.regionck_item(impl_m_node_id, impl_m_span, &[]);
356 fn check_region_bounds_on_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
358 impl_m: &ty::AssociatedItem,
359 trait_generics: &ty::Generics,
360 impl_generics: &ty::Generics,
361 trait_to_skol_substs: &Substs<'tcx>)
362 -> Result<(), ErrorReported> {
363 let trait_params = &trait_generics.regions[..];
364 let impl_params = &impl_generics.regions[..];
366 debug!("check_region_bounds_on_impl_method: \
367 trait_generics={:?} \
369 trait_to_skol_substs={:?}",
372 trait_to_skol_substs);
374 // Must have same number of early-bound lifetime parameters.
375 // Unfortunately, if the user screws up the bounds, then this
376 // will change classification between early and late. E.g.,
377 // if in trait we have `<'a,'b:'a>`, and in impl we just have
378 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
379 // in trait but 0 in the impl. But if we report "expected 2
380 // but found 0" it's confusing, because it looks like there
381 // are zero. Since I don't quite know how to phrase things at
382 // the moment, give a kind of vague error message.
383 if trait_params.len() != impl_params.len() {
384 struct_span_err!(tcx.sess,
387 "lifetime parameters or bounds on method `{}` do not match the \
390 .span_label(span, "lifetimes do not match trait")
392 return Err(ErrorReported);
398 fn extract_spans_for_error_reporting<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
399 param_env: ty::ParamEnv<'tcx>,
401 cause: &ObligationCause<'tcx>,
402 impl_m: &ty::AssociatedItem,
403 impl_sig: ty::FnSig<'tcx>,
404 trait_m: &ty::AssociatedItem,
405 trait_sig: ty::FnSig<'tcx>)
406 -> (Span, Option<Span>) {
408 let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
409 let (impl_m_output, impl_m_iter) = match tcx.hir.expect_impl_item(impl_m_node_id).node {
410 ImplItemKind::Method(ref impl_m_sig, _) => {
411 (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter())
413 _ => bug!("{:?} is not a method", impl_m),
417 TypeError::Mutability => {
418 if let Some(trait_m_node_id) = tcx.hir.as_local_node_id(trait_m.def_id) {
419 let trait_m_iter = match tcx.hir.expect_trait_item(trait_m_node_id).node {
420 TraitItemKind::Method(ref trait_m_sig, _) => {
421 trait_m_sig.decl.inputs.iter()
423 _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
426 impl_m_iter.zip(trait_m_iter).find(|&(ref impl_arg, ref trait_arg)| {
427 match (&impl_arg.node, &trait_arg.node) {
428 (&hir::TyRptr(_, ref impl_mt), &hir::TyRptr(_, ref trait_mt)) |
429 (&hir::TyPtr(ref impl_mt), &hir::TyPtr(ref trait_mt)) => {
430 impl_mt.mutbl != trait_mt.mutbl
434 }).map(|(ref impl_arg, ref trait_arg)| {
435 (impl_arg.span, Some(trait_arg.span))
437 .unwrap_or_else(|| (cause.span, tcx.hir.span_if_local(trait_m.def_id)))
439 (cause.span, tcx.hir.span_if_local(trait_m.def_id))
442 TypeError::Sorts(ExpectedFound { .. }) => {
443 if let Some(trait_m_node_id) = tcx.hir.as_local_node_id(trait_m.def_id) {
444 let (trait_m_output, trait_m_iter) =
445 match tcx.hir.expect_trait_item(trait_m_node_id).node {
446 TraitItemKind::Method(ref trait_m_sig, _) => {
447 (&trait_m_sig.decl.output, trait_m_sig.decl.inputs.iter())
449 _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
452 let impl_iter = impl_sig.inputs().iter();
453 let trait_iter = trait_sig.inputs().iter();
454 impl_iter.zip(trait_iter)
457 .filter_map(|(((&impl_arg_ty, &trait_arg_ty), impl_arg), trait_arg)| {
458 match infcx.at(&cause, param_env).sub(trait_arg_ty, impl_arg_ty) {
460 Err(_) => Some((impl_arg.span, Some(trait_arg.span))),
466 infcx.at(&cause, param_env)
467 .sup(trait_sig.output(), impl_sig.output())
470 (impl_m_output.span(), Some(trait_m_output.span()))
472 (cause.span, tcx.hir.span_if_local(trait_m.def_id))
476 (cause.span, tcx.hir.span_if_local(trait_m.def_id))
479 _ => (cause.span, tcx.hir.span_if_local(trait_m.def_id)),
483 fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
484 impl_m: &ty::AssociatedItem,
486 trait_m: &ty::AssociatedItem,
487 impl_trait_ref: ty::TraitRef<'tcx>)
488 -> Result<(), ErrorReported>
490 // Try to give more informative error messages about self typing
491 // mismatches. Note that any mismatch will also be detected
492 // below, where we construct a canonical function type that
493 // includes the self parameter as a normal parameter. It's just
494 // that the error messages you get out of this code are a bit more
495 // inscrutable, particularly for cases where one method has no
498 let self_string = |method: &ty::AssociatedItem| {
499 let untransformed_self_ty = match method.container {
500 ty::ImplContainer(_) => impl_trait_ref.self_ty(),
501 ty::TraitContainer(_) => tcx.mk_self_type()
503 let self_arg_ty = *tcx.fn_sig(method.def_id).input(0).skip_binder();
504 match ExplicitSelf::determine(untransformed_self_ty, self_arg_ty) {
505 ExplicitSelf::ByValue => "self".to_string(),
506 ExplicitSelf::ByReference(_, hir::MutImmutable) => "&self".to_string(),
507 ExplicitSelf::ByReference(_, hir::MutMutable) => "&mut self".to_string(),
508 _ => format!("self: {}", self_arg_ty)
512 match (trait_m.method_has_self_argument, impl_m.method_has_self_argument) {
513 (false, false) | (true, true) => {}
516 let self_descr = self_string(impl_m);
517 let mut err = struct_span_err!(tcx.sess,
520 "method `{}` has a `{}` declaration in the impl, but \
524 err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
525 if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
526 err.span_label(span, format!("trait declared without `{}`", self_descr));
529 return Err(ErrorReported);
533 let self_descr = self_string(trait_m);
534 let mut err = struct_span_err!(tcx.sess,
537 "method `{}` has a `{}` declaration in the trait, but \
541 err.span_label(impl_m_span,
542 format!("expected `{}` in impl", self_descr));
543 if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
544 err.span_label(span, format!("`{}` used in trait", self_descr));
546 err.note_trait_signature(trait_m.name.to_string(),
547 trait_m.signature(&tcx));
550 return Err(ErrorReported);
557 fn compare_number_of_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
558 impl_m: &ty::AssociatedItem,
560 trait_m: &ty::AssociatedItem,
561 trait_item_span: Option<Span>)
562 -> Result<(), ErrorReported> {
563 let impl_m_generics = tcx.generics_of(impl_m.def_id);
564 let trait_m_generics = tcx.generics_of(trait_m.def_id);
565 let num_impl_m_type_params = impl_m_generics.types.len();
566 let num_trait_m_type_params = trait_m_generics.types.len();
567 if num_impl_m_type_params != num_trait_m_type_params {
568 let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
569 let span = match tcx.hir.expect_impl_item(impl_m_node_id).node {
570 ImplItemKind::Method(ref impl_m_sig, _) => {
571 if impl_m_sig.generics.is_parameterized() {
572 impl_m_sig.generics.span
577 _ => bug!("{:?} is not a method", impl_m),
580 let mut err = struct_span_err!(tcx.sess,
583 "method `{}` has {} type parameter{} but its trait \
584 declaration has {} type parameter{}",
586 num_impl_m_type_params,
587 if num_impl_m_type_params == 1 { "" } else { "s" },
588 num_trait_m_type_params,
589 if num_trait_m_type_params == 1 {
595 let mut suffix = None;
597 if let Some(span) = trait_item_span {
599 format!("expected {}",
600 &if num_trait_m_type_params != 1 {
601 format!("{} type parameters", num_trait_m_type_params)
603 format!("{} type parameter", num_trait_m_type_params)
606 suffix = Some(format!(", expected {}", num_trait_m_type_params));
610 format!("found {}{}",
611 &if num_impl_m_type_params != 1 {
612 format!("{} type parameters", num_impl_m_type_params)
614 format!("1 type parameter")
616 suffix.as_ref().map(|s| &s[..]).unwrap_or("")));
620 return Err(ErrorReported);
626 fn compare_number_of_method_arguments<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
627 impl_m: &ty::AssociatedItem,
629 trait_m: &ty::AssociatedItem,
630 trait_item_span: Option<Span>)
631 -> Result<(), ErrorReported> {
632 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
633 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
634 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
635 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
636 if trait_number_args != impl_number_args {
637 let trait_m_node_id = tcx.hir.as_local_node_id(trait_m.def_id);
638 let trait_span = if let Some(trait_id) = trait_m_node_id {
639 match tcx.hir.expect_trait_item(trait_id).node {
640 TraitItemKind::Method(ref trait_m_sig, _) => {
641 if let Some(arg) = trait_m_sig.decl.inputs.get(if trait_number_args > 0 {
642 trait_number_args - 1
651 _ => bug!("{:?} is not a method", impl_m),
656 let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
657 let impl_span = match tcx.hir.expect_impl_item(impl_m_node_id).node {
658 ImplItemKind::Method(ref impl_m_sig, _) => {
659 if let Some(arg) = impl_m_sig.decl.inputs.get(if impl_number_args > 0 {
669 _ => bug!("{:?} is not a method", impl_m),
671 let mut err = struct_span_err!(tcx.sess,
674 "method `{}` has {} parameter{} but the declaration in \
678 if impl_number_args == 1 { "" } else { "s" },
679 tcx.item_path_str(trait_m.def_id),
681 if let Some(trait_span) = trait_span {
682 err.span_label(trait_span,
683 format!("trait requires {}",
684 &if trait_number_args != 1 {
685 format!("{} parameters", trait_number_args)
687 format!("{} parameter", trait_number_args)
690 err.note_trait_signature(trait_m.name.to_string(),
691 trait_m.signature(&tcx));
693 err.span_label(impl_span,
694 format!("expected {}, found {}",
695 &if trait_number_args != 1 {
696 format!("{} parameters", trait_number_args)
698 format!("{} parameter", trait_number_args)
702 return Err(ErrorReported);
708 pub fn compare_const_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
709 impl_c: &ty::AssociatedItem,
711 trait_c: &ty::AssociatedItem,
712 impl_trait_ref: ty::TraitRef<'tcx>) {
713 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
715 tcx.infer_ctxt().enter(|infcx| {
716 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
717 let inh = Inherited::new(infcx, impl_c.def_id);
718 let infcx = &inh.infcx;
720 // The below is for the most part highly similar to the procedure
721 // for methods above. It is simpler in many respects, especially
722 // because we shouldn't really have to deal with lifetimes or
723 // predicates. In fact some of this should probably be put into
724 // shared functions because of DRY violations...
725 let trait_to_impl_substs = impl_trait_ref.substs;
727 // Create a parameter environment that represents the implementation's
729 let impl_c_node_id = tcx.hir.as_local_node_id(impl_c.def_id).unwrap();
731 // Compute skolemized form of impl and trait const tys.
732 let impl_ty = tcx.type_of(impl_c.def_id);
733 let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
734 let mut cause = ObligationCause::misc(impl_c_span, impl_c_node_id);
736 // There is no "body" here, so just pass dummy id.
737 let impl_ty = inh.normalize_associated_types_in(impl_c_span,
742 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
744 let trait_ty = inh.normalize_associated_types_in(impl_c_span,
749 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
751 let err = infcx.at(&cause, param_env)
752 .sup(trait_ty, impl_ty)
753 .map(|ok| inh.register_infer_ok_obligations(ok));
755 if let Err(terr) = err {
756 debug!("checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
760 // Locate the Span containing just the type of the offending impl
761 match tcx.hir.expect_impl_item(impl_c_node_id).node {
762 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
763 _ => bug!("{:?} is not a impl const", impl_c),
766 let mut diag = struct_span_err!(tcx.sess,
769 "implemented const `{}` has an incompatible type for \
773 let trait_c_node_id = tcx.hir.as_local_node_id(trait_c.def_id);
774 let trait_c_span = trait_c_node_id.map(|trait_c_node_id| {
775 // Add a label to the Span containing just the type of the const
776 match tcx.hir.expect_trait_item(trait_c_node_id).node {
777 TraitItemKind::Const(ref ty, _) => ty.span,
778 _ => bug!("{:?} is not a trait const", trait_c),
782 infcx.note_type_err(&mut diag,
784 trait_c_span.map(|span| (span, format!("type in trait"))),
785 Some(infer::ValuePairs::Types(ExpectedFound {
793 // Check that all obligations are satisfied by the implementation's
795 if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
796 infcx.report_fulfillment_errors(errors, None);
800 let fcx = FnCtxt::new(&inh, param_env, impl_c_node_id);
801 fcx.regionck_item(impl_c_node_id, impl_c_span, &[]);