]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/compare_method.rs
Rollup merge of #35830 - matthew-piziak:not-example, r=steveklabnik
[rust.git] / src / librustc_typeck / check / compare_method.rs
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.
4 //
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.
10
11 use middle::free_region::FreeRegionMap;
12 use rustc::infer::{self, InferOk, TypeOrigin};
13 use rustc::ty;
14 use rustc::traits::{self, Reveal};
15 use rustc::ty::error::{ExpectedFound, TypeError};
16 use rustc::ty::subst::{Subst, Substs};
17 use rustc::hir::{ImplItemKind, TraitItem_, Ty_};
18
19 use syntax::ast;
20 use syntax_pos::Span;
21
22 use CrateCtxt;
23 use super::assoc;
24
25 /// Checks that a method from an impl conforms to the signature of
26 /// the same method as declared in the trait.
27 ///
28 /// # Parameters
29 ///
30 /// - impl_m: type of the method we are checking
31 /// - impl_m_span: span to use for reporting errors
32 /// - impl_m_body_id: id of the method body
33 /// - trait_m: the method in the trait
34 /// - impl_trait_ref: the TraitRef corresponding to the trait implementation
35
36 pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
37                                      impl_m: &ty::Method<'tcx>,
38                                      impl_m_span: Span,
39                                      impl_m_body_id: ast::NodeId,
40                                      trait_m: &ty::Method<'tcx>,
41                                      impl_trait_ref: &ty::TraitRef<'tcx>) {
42     debug!("compare_impl_method(impl_trait_ref={:?})",
43            impl_trait_ref);
44
45     debug!("compare_impl_method: impl_trait_ref (liberated) = {:?}",
46            impl_trait_ref);
47
48     let tcx = ccx.tcx;
49
50     let trait_to_impl_substs = &impl_trait_ref.substs;
51
52     // Try to give more informative error messages about self typing
53     // mismatches.  Note that any mismatch will also be detected
54     // below, where we construct a canonical function type that
55     // includes the self parameter as a normal parameter.  It's just
56     // that the error messages you get out of this code are a bit more
57     // inscrutable, particularly for cases where one method has no
58     // self.
59     match (&trait_m.explicit_self, &impl_m.explicit_self) {
60         (&ty::ExplicitSelfCategory::Static,
61          &ty::ExplicitSelfCategory::Static) => {}
62         (&ty::ExplicitSelfCategory::Static, _) => {
63             let mut err = struct_span_err!(tcx.sess, impl_m_span, E0185,
64                 "method `{}` has a `{}` declaration in the impl, \
65                         but not in the trait",
66                         trait_m.name,
67                         impl_m.explicit_self);
68             err.span_label(impl_m_span, &format!("`{}` used in impl",
69                                                  impl_m.explicit_self));
70             if let Some(span) = tcx.map.span_if_local(trait_m.def_id) {
71                 err.span_label(span, &format!("trait declared without `{}`",
72                                               impl_m.explicit_self));
73             }
74             err.emit();
75             return;
76         }
77         (_, &ty::ExplicitSelfCategory::Static) => {
78             let mut err = struct_span_err!(tcx.sess, impl_m_span, E0186,
79                 "method `{}` has a `{}` declaration in the trait, \
80                         but not in the impl",
81                         trait_m.name,
82                         trait_m.explicit_self);
83             err.span_label(impl_m_span, &format!("expected `{}` in impl",
84                                                   trait_m.explicit_self));
85             if let Some(span) = tcx.map.span_if_local(trait_m.def_id) {
86                 err.span_label(span, & format!("`{}` used in trait",
87                                                trait_m.explicit_self));
88             }
89             err.emit();
90             return;
91         }
92         _ => {
93             // Let the type checker catch other errors below
94         }
95     }
96
97     let num_impl_m_type_params = impl_m.generics.types.len();
98     let num_trait_m_type_params = trait_m.generics.types.len();
99     if num_impl_m_type_params != num_trait_m_type_params {
100         span_err!(tcx.sess, impl_m_span, E0049,
101             "method `{}` has {} type parameter{} \
102              but its trait declaration has {} type parameter{}",
103             trait_m.name,
104             num_impl_m_type_params,
105             if num_impl_m_type_params == 1 {""} else {"s"},
106             num_trait_m_type_params,
107             if num_trait_m_type_params == 1 {""} else {"s"});
108         return;
109     }
110
111     if impl_m.fty.sig.0.inputs.len() != trait_m.fty.sig.0.inputs.len() {
112         span_err!(tcx.sess, impl_m_span, E0050,
113             "method `{}` has {} parameter{} \
114              but the declaration in trait `{}` has {}",
115             trait_m.name,
116             impl_m.fty.sig.0.inputs.len(),
117             if impl_m.fty.sig.0.inputs.len() == 1 {""} else {"s"},
118             tcx.item_path_str(trait_m.def_id),
119             trait_m.fty.sig.0.inputs.len());
120         return;
121     }
122
123     // This code is best explained by example. Consider a trait:
124     //
125     //     trait Trait<'t,T> {
126     //          fn method<'a,M>(t: &'t T, m: &'a M) -> Self;
127     //     }
128     //
129     // And an impl:
130     //
131     //     impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
132     //          fn method<'b,N>(t: &'j &'i U, m: &'b N) -> Foo;
133     //     }
134     //
135     // We wish to decide if those two method types are compatible.
136     //
137     // We start out with trait_to_impl_substs, that maps the trait
138     // type parameters to impl type parameters. This is taken from the
139     // impl trait reference:
140     //
141     //     trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
142     //
143     // We create a mapping `dummy_substs` that maps from the impl type
144     // parameters to fresh types and regions. For type parameters,
145     // this is the identity transform, but we could as well use any
146     // skolemized types. For regions, we convert from bound to free
147     // regions (Note: but only early-bound regions, i.e., those
148     // declared on the impl or used in type parameter bounds).
149     //
150     //     impl_to_skol_substs = {'i => 'i0, U => U0, N => N0 }
151     //
152     // Now we can apply skol_substs to the type of the impl method
153     // to yield a new function type in terms of our fresh, skolemized
154     // types:
155     //
156     //     <'b> fn(t: &'i0 U0, m: &'b) -> Foo
157     //
158     // We now want to extract and substitute the type of the *trait*
159     // method and compare it. To do so, we must create a compound
160     // substitution by combining trait_to_impl_substs and
161     // impl_to_skol_substs, and also adding a mapping for the method
162     // type parameters. We extend the mapping to also include
163     // the method parameters.
164     //
165     //     trait_to_skol_substs = { T => &'i0 U0, Self => Foo, M => N0 }
166     //
167     // Applying this to the trait method type yields:
168     //
169     //     <'a> fn(t: &'i0 U0, m: &'a) -> Foo
170     //
171     // This type is also the same but the name of the bound region ('a
172     // vs 'b).  However, the normal subtyping rules on fn types handle
173     // this kind of equivalency just fine.
174     //
175     // We now use these substitutions to ensure that all declared bounds are
176     // satisfied by the implementation's method.
177     //
178     // We do this by creating a parameter environment which contains a
179     // substitution corresponding to impl_to_skol_substs. We then build
180     // trait_to_skol_substs and use it to convert the predicates contained
181     // in the trait_m.generics to the skolemized form.
182     //
183     // Finally we register each of these predicates as an obligation in
184     // a fresh FulfillmentCtxt, and invoke select_all_or_error.
185
186     // Create a parameter environment that represents the implementation's
187     // method.
188     let impl_m_node_id = tcx.map.as_local_node_id(impl_m.def_id).unwrap();
189     let impl_param_env = ty::ParameterEnvironment::for_item(tcx, impl_m_node_id);
190
191     // Create mapping from impl to skolemized.
192     let impl_to_skol_substs = &impl_param_env.free_substs;
193
194     // Create mapping from trait to skolemized.
195     let trait_to_skol_substs =
196         impl_to_skol_substs.rebase_onto(tcx, impl_m.container_id(),
197                                         trait_to_impl_substs.subst(tcx, impl_to_skol_substs));
198     debug!("compare_impl_method: trait_to_skol_substs={:?}",
199            trait_to_skol_substs);
200
201     // Check region bounds. FIXME(@jroesch) refactor this away when removing
202     // ParamBounds.
203     if !check_region_bounds_on_impl_method(ccx,
204                                            impl_m_span,
205                                            impl_m,
206                                            &trait_m.generics,
207                                            &impl_m.generics,
208                                            trait_to_skol_substs,
209                                            impl_to_skol_substs) {
210         return;
211     }
212
213     tcx.infer_ctxt(None, None, Reveal::NotSpecializable).enter(|mut infcx| {
214         let mut fulfillment_cx = traits::FulfillmentContext::new();
215
216         // Create obligations for each predicate declared by the impl
217         // definition in the context of the trait's parameter
218         // environment. We can't just use `impl_env.caller_bounds`,
219         // however, because we want to replace all late-bound regions with
220         // region variables.
221         let impl_predicates = tcx.lookup_predicates(impl_m.predicates.parent.unwrap());
222         let mut hybrid_preds = impl_predicates.instantiate(tcx, impl_to_skol_substs);
223
224         debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
225
226         // This is the only tricky bit of the new way we check implementation methods
227         // We need to build a set of predicates where only the method-level bounds
228         // are from the trait and we assume all other bounds from the implementation
229         // to be previously satisfied.
230         //
231         // We then register the obligations from the impl_m and check to see
232         // if all constraints hold.
233         hybrid_preds.predicates.extend(
234             trait_m.predicates.instantiate_own(tcx, trait_to_skol_substs).predicates);
235
236         // Construct trait parameter environment and then shift it into the skolemized viewpoint.
237         // The key step here is to update the caller_bounds's predicates to be
238         // the new hybrid bounds we computed.
239         let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_body_id);
240         let trait_param_env = impl_param_env.with_caller_bounds(hybrid_preds.predicates);
241         let trait_param_env = traits::normalize_param_env_or_error(tcx,
242                                                                    trait_param_env,
243                                                                    normalize_cause.clone());
244         // FIXME(@jroesch) this seems ugly, but is a temporary change
245         infcx.parameter_environment = trait_param_env;
246
247         debug!("compare_impl_method: caller_bounds={:?}",
248             infcx.parameter_environment.caller_bounds);
249
250         let mut selcx = traits::SelectionContext::new(&infcx);
251
252         let impl_m_own_bounds = impl_m.predicates.instantiate_own(tcx, impl_to_skol_substs);
253         let (impl_m_own_bounds, _) =
254             infcx.replace_late_bound_regions_with_fresh_var(
255                 impl_m_span,
256                 infer::HigherRankedType,
257                 &ty::Binder(impl_m_own_bounds.predicates));
258         for predicate in impl_m_own_bounds {
259             let traits::Normalized { value: predicate, .. } =
260                 traits::normalize(&mut selcx, normalize_cause.clone(), &predicate);
261
262             let cause = traits::ObligationCause {
263                 span: impl_m_span,
264                 body_id: impl_m_body_id,
265                 code: traits::ObligationCauseCode::CompareImplMethodObligation
266             };
267
268             fulfillment_cx.register_predicate_obligation(
269                 &infcx,
270                 traits::Obligation::new(cause, predicate));
271         }
272
273         // We now need to check that the signature of the impl method is
274         // compatible with that of the trait method. We do this by
275         // checking that `impl_fty <: trait_fty`.
276         //
277         // FIXME. Unfortunately, this doesn't quite work right now because
278         // associated type normalization is not integrated into subtype
279         // checks. For the comparison to be valid, we need to
280         // normalize the associated types in the impl/trait methods
281         // first. However, because function types bind regions, just
282         // calling `normalize_associated_types_in` would have no effect on
283         // any associated types appearing in the fn arguments or return
284         // type.
285
286         // Compute skolemized form of impl and trait method tys.
287         let tcx = infcx.tcx;
288         let origin = TypeOrigin::MethodCompatCheck(impl_m_span);
289
290         let (impl_sig, _) =
291             infcx.replace_late_bound_regions_with_fresh_var(impl_m_span,
292                                                             infer::HigherRankedType,
293                                                             &impl_m.fty.sig);
294         let impl_sig =
295             impl_sig.subst(tcx, impl_to_skol_substs);
296         let impl_sig =
297             assoc::normalize_associated_types_in(&infcx,
298                                                  &mut fulfillment_cx,
299                                                  impl_m_span,
300                                                  impl_m_body_id,
301                                                  &impl_sig);
302         let impl_args = impl_sig.inputs.clone();
303         let impl_fty = tcx.mk_fn_ptr(tcx.mk_bare_fn(ty::BareFnTy {
304             unsafety: impl_m.fty.unsafety,
305             abi: impl_m.fty.abi,
306             sig: ty::Binder(impl_sig)
307         }));
308         debug!("compare_impl_method: impl_fty={:?}", impl_fty);
309
310         let trait_sig = tcx.liberate_late_bound_regions(
311             infcx.parameter_environment.free_id_outlive,
312             &trait_m.fty.sig);
313         let trait_sig =
314             trait_sig.subst(tcx, trait_to_skol_substs);
315         let trait_sig =
316             assoc::normalize_associated_types_in(&infcx,
317                                                  &mut fulfillment_cx,
318                                                  impl_m_span,
319                                                  impl_m_body_id,
320                                                  &trait_sig);
321         let trait_args = trait_sig.inputs.clone();
322         let trait_fty = tcx.mk_fn_ptr(tcx.mk_bare_fn(ty::BareFnTy {
323             unsafety: trait_m.fty.unsafety,
324             abi: trait_m.fty.abi,
325             sig: ty::Binder(trait_sig)
326         }));
327
328         debug!("compare_impl_method: trait_fty={:?}", trait_fty);
329
330         if let Err(terr) = infcx.sub_types(false, origin, impl_fty, trait_fty) {
331             debug!("sub_types failed: impl ty {:?}, trait ty {:?}",
332                    impl_fty,
333                    trait_fty);
334
335             let impl_m_iter = match tcx.map.expect_impl_item(impl_m_node_id).node {
336                 ImplItemKind::Method(ref impl_m_sig, _) => impl_m_sig.decl.inputs.iter(),
337                 _ => bug!("{:?} is not a method", impl_m)
338             };
339
340             let (impl_err_span, trait_err_span) = match terr {
341                 TypeError::Mutability => {
342                     if let Some(trait_m_node_id) = tcx.map.as_local_node_id(trait_m.def_id) {
343                         let trait_m_iter = match tcx.map.expect_trait_item(trait_m_node_id).node {
344                             TraitItem_::MethodTraitItem(ref trait_m_sig, _) =>
345                                 trait_m_sig.decl.inputs.iter(),
346                             _ => bug!("{:?} is not a MethodTraitItem", trait_m)
347                         };
348
349                         impl_m_iter.zip(trait_m_iter).find(|&(ref impl_arg, ref trait_arg)| {
350                             match (&impl_arg.ty.node, &trait_arg.ty.node) {
351                                 (&Ty_::TyRptr(_, ref impl_mt), &Ty_::TyRptr(_, ref trait_mt)) |
352                                 (&Ty_::TyPtr(ref impl_mt), &Ty_::TyPtr(ref trait_mt)) =>
353                                     impl_mt.mutbl != trait_mt.mutbl,
354                                 _ => false
355                             }
356                         }).map(|(ref impl_arg, ref trait_arg)| {
357                             match (impl_arg.to_self(), trait_arg.to_self()) {
358                                 (Some(impl_self), Some(trait_self)) =>
359                                     (impl_self.span, Some(trait_self.span)),
360                                 (None, None) => (impl_arg.ty.span, Some(trait_arg.ty.span)),
361                                 _ => bug!("impl and trait fns have different first args, \
362                                            impl: {:?}, trait: {:?}", impl_arg, trait_arg)
363                             }
364                         }).unwrap_or((origin.span(), tcx.map.span_if_local(trait_m.def_id)))
365                     } else {
366                         (origin.span(), tcx.map.span_if_local(trait_m.def_id))
367                     }
368                 }
369                 TypeError::Sorts(ExpectedFound { expected, found }) => {
370                     if let Some(trait_m_node_id) = tcx.map.as_local_node_id(trait_m.def_id) {
371                         let trait_m_iter = match tcx.map.expect_trait_item(trait_m_node_id).node {
372                             TraitItem_::MethodTraitItem(ref trait_m_sig, _) =>
373                                 trait_m_sig.decl.inputs.iter(),
374                             _ => bug!("{:?} is not a MethodTraitItem", trait_m)
375                         };
376                         let impl_iter = impl_args.iter();
377                         let trait_iter = trait_args.iter();
378                         let arg_idx = impl_iter.zip(trait_iter)
379                                                .position(|(impl_arg_ty, trait_arg_ty)| {
380                                                 *impl_arg_ty == found && *trait_arg_ty == expected
381                                                }).unwrap();
382                         impl_m_iter.zip(trait_m_iter)
383                                    .nth(arg_idx)
384                                    .map(|(impl_arg, trait_arg)|
385                                         (impl_arg.ty.span, Some(trait_arg.ty.span)))
386                                    .unwrap_or(
387                                     (origin.span(), tcx.map.span_if_local(trait_m.def_id)))
388                     } else {
389                         (origin.span(), tcx.map.span_if_local(trait_m.def_id))
390                     }
391                 }
392                 _ => (origin.span(), tcx.map.span_if_local(trait_m.def_id))
393             };
394
395             let origin = TypeOrigin::MethodCompatCheck(impl_err_span);
396
397             let mut diag = struct_span_err!(
398                 tcx.sess, origin.span(), E0053,
399                 "method `{}` has an incompatible type for trait", trait_m.name
400             );
401
402             infcx.note_type_err(
403                 &mut diag,
404                 origin,
405                 trait_err_span.map(|sp| (sp, format!("original trait requirement"))),
406                 Some(infer::ValuePairs::Types(ExpectedFound {
407                      expected: trait_fty,
408                      found: impl_fty
409                 })),
410                 &terr
411             );
412             diag.emit();
413             return
414         }
415
416         // Check that all obligations are satisfied by the implementation's
417         // version.
418         if let Err(ref errors) = fulfillment_cx.select_all_or_error(&infcx) {
419             infcx.report_fulfillment_errors(errors);
420             return
421         }
422
423         // Finally, resolve all regions. This catches wily misuses of
424         // lifetime parameters. We have to build up a plausible lifetime
425         // environment based on what we find in the trait. We could also
426         // include the obligations derived from the method argument types,
427         // but I don't think it's necessary -- after all, those are still
428         // in effect when type-checking the body, and all the
429         // where-clauses in the header etc should be implied by the trait
430         // anyway, so it shouldn't be needed there either. Anyway, we can
431         // always add more relations later (it's backwards compat).
432         let mut free_regions = FreeRegionMap::new();
433         free_regions.relate_free_regions_from_predicates(
434             &infcx.parameter_environment.caller_bounds);
435
436         infcx.resolve_regions_and_report_errors(&free_regions, impl_m_body_id);
437     });
438
439     fn check_region_bounds_on_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
440                                                     span: Span,
441                                                     impl_m: &ty::Method<'tcx>,
442                                                     trait_generics: &ty::Generics<'tcx>,
443                                                     impl_generics: &ty::Generics<'tcx>,
444                                                     trait_to_skol_substs: &Substs<'tcx>,
445                                                     impl_to_skol_substs: &Substs<'tcx>)
446                                                     -> bool
447     {
448
449         let trait_params = &trait_generics.regions[..];
450         let impl_params = &impl_generics.regions[..];
451
452         debug!("check_region_bounds_on_impl_method: \
453                trait_generics={:?} \
454                impl_generics={:?} \
455                trait_to_skol_substs={:?} \
456                impl_to_skol_substs={:?}",
457                trait_generics,
458                impl_generics,
459                trait_to_skol_substs,
460                impl_to_skol_substs);
461
462         // Must have same number of early-bound lifetime parameters.
463         // Unfortunately, if the user screws up the bounds, then this
464         // will change classification between early and late.  E.g.,
465         // if in trait we have `<'a,'b:'a>`, and in impl we just have
466         // `<'a,'b>`, then we have 2 early-bound lifetime parameters
467         // in trait but 0 in the impl. But if we report "expected 2
468         // but found 0" it's confusing, because it looks like there
469         // are zero. Since I don't quite know how to phrase things at
470         // the moment, give a kind of vague error message.
471         if trait_params.len() != impl_params.len() {
472             span_err!(ccx.tcx.sess, span, E0195,
473                 "lifetime parameters or bounds on method `{}` do \
474                          not match the trait declaration",
475                          impl_m.name);
476             return false;
477         }
478
479         return true;
480     }
481 }
482
483 pub fn compare_const_impl<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
484                                     impl_c: &ty::AssociatedConst<'tcx>,
485                                     impl_c_span: Span,
486                                     trait_c: &ty::AssociatedConst<'tcx>,
487                                     impl_trait_ref: &ty::TraitRef<'tcx>) {
488     debug!("compare_const_impl(impl_trait_ref={:?})",
489            impl_trait_ref);
490
491     let tcx = ccx.tcx;
492     tcx.infer_ctxt(None, None, Reveal::NotSpecializable).enter(|infcx| {
493         let mut fulfillment_cx = traits::FulfillmentContext::new();
494
495         // The below is for the most part highly similar to the procedure
496         // for methods above. It is simpler in many respects, especially
497         // because we shouldn't really have to deal with lifetimes or
498         // predicates. In fact some of this should probably be put into
499         // shared functions because of DRY violations...
500         let trait_to_impl_substs = &impl_trait_ref.substs;
501
502         // Create a parameter environment that represents the implementation's
503         // method.
504         let impl_c_node_id = tcx.map.as_local_node_id(impl_c.def_id).unwrap();
505         let impl_param_env = ty::ParameterEnvironment::for_item(tcx, impl_c_node_id);
506
507         // Create mapping from impl to skolemized.
508         let impl_to_skol_substs = &impl_param_env.free_substs;
509
510         // Create mapping from trait to skolemized.
511         let trait_to_skol_substs =
512             impl_to_skol_substs.rebase_onto(tcx, impl_c.container.id(),
513                                             trait_to_impl_substs.subst(tcx, impl_to_skol_substs));
514         debug!("compare_const_impl: trait_to_skol_substs={:?}",
515             trait_to_skol_substs);
516
517         // Compute skolemized form of impl and trait const tys.
518         let impl_ty = impl_c.ty.subst(tcx, impl_to_skol_substs);
519         let trait_ty = trait_c.ty.subst(tcx, trait_to_skol_substs);
520         let mut origin = TypeOrigin::Misc(impl_c_span);
521
522         let err = infcx.commit_if_ok(|_| {
523             // There is no "body" here, so just pass dummy id.
524             let impl_ty =
525                 assoc::normalize_associated_types_in(&infcx,
526                                                      &mut fulfillment_cx,
527                                                      impl_c_span,
528                                                      0,
529                                                      &impl_ty);
530
531             debug!("compare_const_impl: impl_ty={:?}",
532                 impl_ty);
533
534             let trait_ty =
535                 assoc::normalize_associated_types_in(&infcx,
536                                                      &mut fulfillment_cx,
537                                                      impl_c_span,
538                                                      0,
539                                                      &trait_ty);
540
541             debug!("compare_const_impl: trait_ty={:?}",
542                 trait_ty);
543
544             infcx.sub_types(false, origin, impl_ty, trait_ty)
545                  .map(|InferOk { obligations, .. }| {
546                 // FIXME(#32730) propagate obligations
547                 assert!(obligations.is_empty())
548             })
549         });
550
551         if let Err(terr) = err {
552             debug!("checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
553                    impl_ty,
554                    trait_ty);
555
556             // Locate the Span containing just the type of the offending impl
557             match tcx.map.expect_impl_item(impl_c_node_id).node {
558                 ImplItemKind::Const(ref ty, _) => origin = TypeOrigin::Misc(ty.span),
559                 _ => bug!("{:?} is not a impl const", impl_c)
560             }
561
562             let mut diag = struct_span_err!(
563                 tcx.sess, origin.span(), E0326,
564                 "implemented const `{}` has an incompatible type for trait",
565                 trait_c.name
566             );
567
568             // Add a label to the Span containing just the type of the item
569             let trait_c_node_id = tcx.map.as_local_node_id(trait_c.def_id).unwrap();
570             let trait_c_span = match tcx.map.expect_trait_item(trait_c_node_id).node {
571                 TraitItem_::ConstTraitItem(ref ty, _) => ty.span,
572                 _ => bug!("{:?} is not a trait const", trait_c)
573             };
574
575             infcx.note_type_err(
576                 &mut diag,
577                 origin,
578                 Some((trait_c_span, format!("original trait requirement"))),
579                 Some(infer::ValuePairs::Types(ExpectedFound {
580                     expected: trait_ty,
581                     found: impl_ty
582                 })), &terr
583             );
584             diag.emit();
585         }
586     });
587 }