]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/compare_method.rs
Auto merge of #42387 - GuillaumeGomez:error-codes-next, r=Susurrus
[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 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;
20
21 use syntax_pos::Span;
22
23 use super::{Inherited, FnCtxt};
24 use astconv::ExplicitSelf;
25
26 /// Checks that a method from an impl conforms to the signature of
27 /// the same method as declared in the trait.
28 ///
29 /// # Parameters
30 ///
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
35
36 pub fn compare_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
37                                      impl_m: &ty::AssociatedItem,
38                                      impl_m_span: Span,
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={:?})",
44            impl_trait_ref);
45
46     if let Err(ErrorReported) = compare_self_type(tcx,
47                                                   impl_m,
48                                                   impl_m_span,
49                                                   trait_m,
50                                                   impl_trait_ref) {
51         return;
52     }
53
54     if let Err(ErrorReported) = compare_number_of_generics(tcx,
55                                                            impl_m,
56                                                            impl_m_span,
57                                                            trait_m,
58                                                            trait_item_span) {
59         return;
60     }
61
62     if let Err(ErrorReported) = compare_number_of_method_arguments(tcx,
63                                                                    impl_m,
64                                                                    impl_m_span,
65                                                                    trait_m,
66                                                                    trait_item_span) {
67         return;
68     }
69
70     if let Err(ErrorReported) = compare_predicate_entailment(tcx,
71                                                              impl_m,
72                                                              impl_m_span,
73                                                              trait_m,
74                                                              impl_trait_ref,
75                                                              old_broken_mode) {
76         return;
77     }
78 }
79
80 fn compare_predicate_entailment<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
81                                           impl_m: &ty::AssociatedItem,
82                                           impl_m_span: Span,
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;
88
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();
93
94     let cause = ObligationCause {
95         span: impl_m_span,
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 },
102         },
103     };
104
105     // This code is best explained by example. Consider a trait:
106     //
107     //     trait Trait<'t,T> {
108     //          fn method<'a,M>(t: &'t T, m: &'a M) -> Self;
109     //     }
110     //
111     // And an impl:
112     //
113     //     impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
114     //          fn method<'b,N>(t: &'j &'i U, m: &'b N) -> Foo;
115     //     }
116     //
117     // We wish to decide if those two method types are compatible.
118     //
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:
122     //
123     //     trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
124     //
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).
131     //
132     //     impl_to_skol_substs = {'i => 'i0, U => U0, N => N0 }
133     //
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
136     // types:
137     //
138     //     <'b> fn(t: &'i0 U0, m: &'b) -> Foo
139     //
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.
146     //
147     //     trait_to_skol_substs = { T => &'i0 U0, Self => Foo, M => N0 }
148     //
149     // Applying this to the trait method type yields:
150     //
151     //     <'a> fn(t: &'i0 U0, m: &'a) -> Foo
152     //
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.
156     //
157     // We now use these substitutions to ensure that all declared bounds are
158     // satisfied by the implementation's method.
159     //
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.
164     //
165     // Finally we register each of these predicates as an obligation in
166     // a fresh FulfillmentCtxt, and invoke select_all_or_error.
167
168     // Create mapping from impl to skolemized.
169     let impl_to_skol_substs = Substs::identity_for_item(tcx, impl_m.def_id);
170
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);
177
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);
182
183     // Check region bounds.
184     check_region_bounds_on_impl_method(tcx,
185                                        impl_m_span,
186                                        impl_m,
187                                        &trait_m_generics,
188                                        &impl_m_generics,
189                                        trait_to_skol_substs)?;
190
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
195     // region variables.
196     let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
197     let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
198
199     debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
200
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.
205     //
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);
210
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),
216                                       Reveal::UserFacing);
217     let param_env = traits::normalize_param_env_or_error(tcx,
218                                                          impl_m.def_id,
219                                                          param_env,
220                                                          normalize_cause.clone());
221
222     tcx.infer_ctxt(()).enter(|infcx| {
223         let inh = Inherited::new(infcx, impl_m.def_id);
224         let infcx = &inh.infcx;
225
226         debug!("compare_impl_method: caller_bounds={:?}",
227                param_env.caller_bounds);
228
229         let mut selcx = traits::SelectionContext::new(&infcx);
230
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);
238
239             inh.register_predicates(obligations);
240             inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
241         }
242
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`.
246         //
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
254         // type.
255
256         // Compute skolemized form of impl and trait method tys.
257         let tcx = infcx.tcx;
258
259         let m_sig = |method: &ty::AssociatedItem| {
260             match tcx.type_of(method.def_id).sty {
261                 ty::TyFnDef(_, _, f) => f,
262                 _ => bug!()
263             }
264         };
265
266         let (impl_sig, _) =
267             infcx.replace_late_bound_regions_with_fresh_var(impl_m_span,
268                                                             infer::HigherRankedType,
269                                                             &m_sig(impl_m));
270         let impl_sig =
271             inh.normalize_associated_types_in(impl_m_span,
272                                               impl_m_node_id,
273                                               param_env,
274                                               &impl_sig);
275         let impl_fty = tcx.mk_fn_ptr(ty::Binder(impl_sig));
276         debug!("compare_impl_method: impl_fty={:?}", impl_fty);
277
278         let trait_sig = inh.liberate_late_bound_regions(
279             impl_m.def_id,
280             &m_sig(trait_m));
281         let trait_sig =
282             trait_sig.subst(tcx, trait_to_skol_substs);
283         let trait_sig =
284             inh.normalize_associated_types_in(impl_m_span,
285                                               impl_m_node_id,
286                                               param_env,
287                                               &trait_sig);
288         let trait_fty = tcx.mk_fn_ptr(ty::Binder(trait_sig));
289
290         debug!("compare_impl_method: trait_fty={:?}", trait_fty);
291
292         let sub_result = infcx.at(&cause, param_env)
293                               .sup(trait_fty, impl_fty)
294                               .map(|InferOk { obligations, .. }| {
295                                   inh.register_predicates(obligations);
296                               });
297
298         if let Err(terr) = sub_result {
299             debug!("sub_types failed: impl ty {:?}, trait ty {:?}",
300                    impl_fty,
301                    trait_fty);
302
303             let (impl_err_span, trait_err_span) = extract_spans_for_error_reporting(&infcx,
304                                                                                     param_env,
305                                                                                     &terr,
306                                                                                     &cause,
307                                                                                     impl_m,
308                                                                                     impl_sig,
309                                                                                     trait_m,
310                                                                                     trait_sig);
311
312             let cause = ObligationCause {
313                 span: impl_err_span,
314                 ..cause.clone()
315             };
316
317             let mut diag = struct_span_err!(tcx.sess,
318                                             cause.span,
319                                             E0053,
320                                             "method `{}` has an incompatible type for trait",
321                                             trait_m.name);
322
323             infcx.note_type_err(&mut diag,
324                                 &cause,
325                                 trait_err_span.map(|sp| (sp, format!("type in trait"))),
326                                 Some(infer::ValuePairs::Types(ExpectedFound {
327                                     expected: trait_fty,
328                                     found: impl_fty,
329                                 })),
330                                 &terr);
331             diag.emit();
332             return Err(ErrorReported);
333         }
334
335         // Check that all obligations are satisfied by the implementation's
336         // version.
337         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
338             infcx.report_fulfillment_errors(errors);
339             return Err(ErrorReported);
340         }
341
342         // Finally, resolve all regions. This catches wily misuses of
343         // lifetime parameters.
344         if old_broken_mode {
345             // FIXME(#18937) -- this is how the code used to
346             // work. This is buggy because the fulfillment cx creates
347             // region obligations that get overlooked.  The right
348             // thing to do is the code below. But we keep this old
349             // pass around temporarily.
350             let region_maps = RegionMaps::new();
351             let mut free_regions = FreeRegionMap::new();
352             free_regions.relate_free_regions_from_predicates(&param_env.caller_bounds);
353             infcx.resolve_regions_and_report_errors(impl_m.def_id, &region_maps, &free_regions);
354         } else {
355             let fcx = FnCtxt::new(&inh, param_env, impl_m_node_id);
356             fcx.regionck_item(impl_m_node_id, impl_m_span, &[]);
357         }
358
359         Ok(())
360     })
361 }
362
363 fn check_region_bounds_on_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
364                                                 span: Span,
365                                                 impl_m: &ty::AssociatedItem,
366                                                 trait_generics: &ty::Generics,
367                                                 impl_generics: &ty::Generics,
368                                                 trait_to_skol_substs: &Substs<'tcx>)
369                                                 -> Result<(), ErrorReported> {
370     let trait_params = &trait_generics.regions[..];
371     let impl_params = &impl_generics.regions[..];
372
373     debug!("check_region_bounds_on_impl_method: \
374             trait_generics={:?} \
375             impl_generics={:?} \
376             trait_to_skol_substs={:?}",
377            trait_generics,
378            impl_generics,
379            trait_to_skol_substs);
380
381     // Must have same number of early-bound lifetime parameters.
382     // Unfortunately, if the user screws up the bounds, then this
383     // will change classification between early and late.  E.g.,
384     // if in trait we have `<'a,'b:'a>`, and in impl we just have
385     // `<'a,'b>`, then we have 2 early-bound lifetime parameters
386     // in trait but 0 in the impl. But if we report "expected 2
387     // but found 0" it's confusing, because it looks like there
388     // are zero. Since I don't quite know how to phrase things at
389     // the moment, give a kind of vague error message.
390     if trait_params.len() != impl_params.len() {
391         struct_span_err!(tcx.sess,
392                          span,
393                          E0195,
394                          "lifetime parameters or bounds on method `{}` do not match the \
395                           trait declaration",
396                          impl_m.name)
397             .span_label(span, "lifetimes do not match trait")
398             .emit();
399         return Err(ErrorReported);
400     }
401
402     return Ok(());
403 }
404
405 fn extract_spans_for_error_reporting<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
406                                                      param_env: ty::ParamEnv<'tcx>,
407                                                      terr: &TypeError,
408                                                      cause: &ObligationCause<'tcx>,
409                                                      impl_m: &ty::AssociatedItem,
410                                                      impl_sig: ty::FnSig<'tcx>,
411                                                      trait_m: &ty::AssociatedItem,
412                                                      trait_sig: ty::FnSig<'tcx>)
413                                                      -> (Span, Option<Span>) {
414     let tcx = infcx.tcx;
415     let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
416     let (impl_m_output, impl_m_iter) = match tcx.hir.expect_impl_item(impl_m_node_id).node {
417         ImplItemKind::Method(ref impl_m_sig, _) => {
418             (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter())
419         }
420         _ => bug!("{:?} is not a method", impl_m),
421     };
422
423     match *terr {
424         TypeError::Mutability => {
425             if let Some(trait_m_node_id) = tcx.hir.as_local_node_id(trait_m.def_id) {
426                 let trait_m_iter = match tcx.hir.expect_trait_item(trait_m_node_id).node {
427                     TraitItemKind::Method(ref trait_m_sig, _) => {
428                         trait_m_sig.decl.inputs.iter()
429                     }
430                     _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
431                 };
432
433                 impl_m_iter.zip(trait_m_iter).find(|&(ref impl_arg, ref trait_arg)| {
434                     match (&impl_arg.node, &trait_arg.node) {
435                         (&hir::TyRptr(_, ref impl_mt), &hir::TyRptr(_, ref trait_mt)) |
436                         (&hir::TyPtr(ref impl_mt), &hir::TyPtr(ref trait_mt)) => {
437                             impl_mt.mutbl != trait_mt.mutbl
438                         }
439                         _ => false,
440                     }
441                 }).map(|(ref impl_arg, ref trait_arg)| {
442                     (impl_arg.span, Some(trait_arg.span))
443                 })
444                 .unwrap_or_else(|| (cause.span, tcx.hir.span_if_local(trait_m.def_id)))
445             } else {
446                 (cause.span, tcx.hir.span_if_local(trait_m.def_id))
447             }
448         }
449         TypeError::Sorts(ExpectedFound { .. }) => {
450             if let Some(trait_m_node_id) = tcx.hir.as_local_node_id(trait_m.def_id) {
451                 let (trait_m_output, trait_m_iter) =
452                     match tcx.hir.expect_trait_item(trait_m_node_id).node {
453                         TraitItemKind::Method(ref trait_m_sig, _) => {
454                             (&trait_m_sig.decl.output, trait_m_sig.decl.inputs.iter())
455                         }
456                         _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
457                     };
458
459                 let impl_iter = impl_sig.inputs().iter();
460                 let trait_iter = trait_sig.inputs().iter();
461                 impl_iter.zip(trait_iter)
462                          .zip(impl_m_iter)
463                          .zip(trait_m_iter)
464                          .filter_map(|(((&impl_arg_ty, &trait_arg_ty), impl_arg), trait_arg)| {
465                              match infcx.at(&cause, param_env).sub(trait_arg_ty, impl_arg_ty) {
466                                  Ok(_) => None,
467                                  Err(_) => Some((impl_arg.span, Some(trait_arg.span))),
468                              }
469                          })
470                          .next()
471                          .unwrap_or_else(|| {
472                              if
473                                  infcx.at(&cause, param_env)
474                                       .sup(trait_sig.output(), impl_sig.output())
475                                       .is_err()
476                              {
477                                  (impl_m_output.span(), Some(trait_m_output.span()))
478                              } else {
479                                  (cause.span, tcx.hir.span_if_local(trait_m.def_id))
480                              }
481                          })
482             } else {
483                 (cause.span, tcx.hir.span_if_local(trait_m.def_id))
484             }
485         }
486         _ => (cause.span, tcx.hir.span_if_local(trait_m.def_id)),
487     }
488 }
489
490 fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
491                                impl_m: &ty::AssociatedItem,
492                                impl_m_span: Span,
493                                trait_m: &ty::AssociatedItem,
494                                impl_trait_ref: ty::TraitRef<'tcx>)
495                                -> Result<(), ErrorReported>
496 {
497     // Try to give more informative error messages about self typing
498     // mismatches.  Note that any mismatch will also be detected
499     // below, where we construct a canonical function type that
500     // includes the self parameter as a normal parameter.  It's just
501     // that the error messages you get out of this code are a bit more
502     // inscrutable, particularly for cases where one method has no
503     // self.
504
505     let self_string = |method: &ty::AssociatedItem| {
506         let untransformed_self_ty = match method.container {
507             ty::ImplContainer(_) => impl_trait_ref.self_ty(),
508             ty::TraitContainer(_) => tcx.mk_self_type()
509         };
510         let method_ty = tcx.type_of(method.def_id);
511         let self_arg_ty = *method_ty.fn_sig().input(0).skip_binder();
512         match ExplicitSelf::determine(untransformed_self_ty, self_arg_ty) {
513             ExplicitSelf::ByValue => "self".to_string(),
514             ExplicitSelf::ByReference(_, hir::MutImmutable) => "&self".to_string(),
515             ExplicitSelf::ByReference(_, hir::MutMutable) => "&mut self".to_string(),
516             _ => format!("self: {}", self_arg_ty)
517         }
518     };
519
520     match (trait_m.method_has_self_argument, impl_m.method_has_self_argument) {
521         (false, false) | (true, true) => {}
522
523         (false, true) => {
524             let self_descr = self_string(impl_m);
525             let mut err = struct_span_err!(tcx.sess,
526                                            impl_m_span,
527                                            E0185,
528                                            "method `{}` has a `{}` declaration in the impl, but \
529                                             not in the trait",
530                                            trait_m.name,
531                                            self_descr);
532             err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
533             if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
534                 err.span_label(span, format!("trait declared without `{}`", self_descr));
535             }
536             err.emit();
537             return Err(ErrorReported);
538         }
539
540         (true, false) => {
541             let self_descr = self_string(trait_m);
542             let mut err = struct_span_err!(tcx.sess,
543                                            impl_m_span,
544                                            E0186,
545                                            "method `{}` has a `{}` declaration in the trait, but \
546                                             not in the impl",
547                                            trait_m.name,
548                                            self_descr);
549             err.span_label(impl_m_span,
550                            format!("expected `{}` in impl", self_descr));
551             if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
552                 err.span_label(span, format!("`{}` used in trait", self_descr));
553             }
554             err.emit();
555             return Err(ErrorReported);
556         }
557     }
558
559     Ok(())
560 }
561
562 fn compare_number_of_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
563                                         impl_m: &ty::AssociatedItem,
564                                         impl_m_span: Span,
565                                         trait_m: &ty::AssociatedItem,
566                                         trait_item_span: Option<Span>)
567                                         -> Result<(), ErrorReported> {
568     let impl_m_generics = tcx.generics_of(impl_m.def_id);
569     let trait_m_generics = tcx.generics_of(trait_m.def_id);
570     let num_impl_m_type_params = impl_m_generics.types.len();
571     let num_trait_m_type_params = trait_m_generics.types.len();
572     if num_impl_m_type_params != num_trait_m_type_params {
573         let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
574         let span = match tcx.hir.expect_impl_item(impl_m_node_id).node {
575             ImplItemKind::Method(ref impl_m_sig, _) => {
576                 if impl_m_sig.generics.is_parameterized() {
577                     impl_m_sig.generics.span
578                 } else {
579                     impl_m_span
580                 }
581             }
582             _ => bug!("{:?} is not a method", impl_m),
583         };
584
585         let mut err = struct_span_err!(tcx.sess,
586                                        span,
587                                        E0049,
588                                        "method `{}` has {} type parameter{} but its trait \
589                                         declaration has {} type parameter{}",
590                                        trait_m.name,
591                                        num_impl_m_type_params,
592                                        if num_impl_m_type_params == 1 { "" } else { "s" },
593                                        num_trait_m_type_params,
594                                        if num_trait_m_type_params == 1 {
595                                            ""
596                                        } else {
597                                            "s"
598                                        });
599
600         let mut suffix = None;
601
602         if let Some(span) = trait_item_span {
603             err.span_label(span,
604                            format!("expected {}",
605                                     &if num_trait_m_type_params != 1 {
606                                         format!("{} type parameters", num_trait_m_type_params)
607                                     } else {
608                                         format!("{} type parameter", num_trait_m_type_params)
609                                     }));
610         } else {
611             suffix = Some(format!(", expected {}", num_trait_m_type_params));
612         }
613
614         err.span_label(span,
615                        format!("found {}{}",
616                                 &if num_impl_m_type_params != 1 {
617                                     format!("{} type parameters", num_impl_m_type_params)
618                                 } else {
619                                     format!("1 type parameter")
620                                 },
621                                 suffix.as_ref().map(|s| &s[..]).unwrap_or("")));
622
623         err.emit();
624
625         return Err(ErrorReported);
626     }
627
628     Ok(())
629 }
630
631 fn compare_number_of_method_arguments<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
632                                                 impl_m: &ty::AssociatedItem,
633                                                 impl_m_span: Span,
634                                                 trait_m: &ty::AssociatedItem,
635                                                 trait_item_span: Option<Span>)
636                                                 -> Result<(), ErrorReported> {
637     let m_fty = |method: &ty::AssociatedItem| {
638         match tcx.type_of(method.def_id).sty {
639             ty::TyFnDef(_, _, f) => f,
640             _ => bug!()
641         }
642     };
643     let impl_m_fty = m_fty(impl_m);
644     let trait_m_fty = m_fty(trait_m);
645     let trait_number_args = trait_m_fty.inputs().skip_binder().len();
646     let impl_number_args = impl_m_fty.inputs().skip_binder().len();
647     if trait_number_args != impl_number_args {
648         let trait_m_node_id = tcx.hir.as_local_node_id(trait_m.def_id);
649         let trait_span = if let Some(trait_id) = trait_m_node_id {
650             match tcx.hir.expect_trait_item(trait_id).node {
651                 TraitItemKind::Method(ref trait_m_sig, _) => {
652                     if let Some(arg) = trait_m_sig.decl.inputs.get(if trait_number_args > 0 {
653                         trait_number_args - 1
654                     } else {
655                         0
656                     }) {
657                         Some(arg.span)
658                     } else {
659                         trait_item_span
660                     }
661                 }
662                 _ => bug!("{:?} is not a method", impl_m),
663             }
664         } else {
665             trait_item_span
666         };
667         let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
668         let impl_span = match tcx.hir.expect_impl_item(impl_m_node_id).node {
669             ImplItemKind::Method(ref impl_m_sig, _) => {
670                 if let Some(arg) = impl_m_sig.decl.inputs.get(if impl_number_args > 0 {
671                     impl_number_args - 1
672                 } else {
673                     0
674                 }) {
675                     arg.span
676                 } else {
677                     impl_m_span
678                 }
679             }
680             _ => bug!("{:?} is not a method", impl_m),
681         };
682         let mut err = struct_span_err!(tcx.sess,
683                                        impl_span,
684                                        E0050,
685                                        "method `{}` has {} parameter{} but the declaration in \
686                                         trait `{}` has {}",
687                                        trait_m.name,
688                                        impl_number_args,
689                                        if impl_number_args == 1 { "" } else { "s" },
690                                        tcx.item_path_str(trait_m.def_id),
691                                        trait_number_args);
692         if let Some(trait_span) = trait_span {
693             err.span_label(trait_span,
694                            format!("trait requires {}",
695                                     &if trait_number_args != 1 {
696                                         format!("{} parameters", trait_number_args)
697                                     } else {
698                                         format!("{} parameter", trait_number_args)
699                                     }));
700         }
701         err.span_label(impl_span,
702                        format!("expected {}, found {}",
703                                 &if trait_number_args != 1 {
704                                     format!("{} parameters", trait_number_args)
705                                 } else {
706                                     format!("{} parameter", trait_number_args)
707                                 },
708                                 impl_number_args));
709         err.emit();
710         return Err(ErrorReported);
711     }
712
713     Ok(())
714 }
715
716 pub fn compare_const_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
717                                     impl_c: &ty::AssociatedItem,
718                                     impl_c_span: Span,
719                                     trait_c: &ty::AssociatedItem,
720                                     impl_trait_ref: ty::TraitRef<'tcx>) {
721     debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
722
723     tcx.infer_ctxt(()).enter(|infcx| {
724         let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
725         let inh = Inherited::new(infcx, impl_c.def_id);
726         let infcx = &inh.infcx;
727
728         // The below is for the most part highly similar to the procedure
729         // for methods above. It is simpler in many respects, especially
730         // because we shouldn't really have to deal with lifetimes or
731         // predicates. In fact some of this should probably be put into
732         // shared functions because of DRY violations...
733         let trait_to_impl_substs = impl_trait_ref.substs;
734
735         // Create a parameter environment that represents the implementation's
736         // method.
737         let impl_c_node_id = tcx.hir.as_local_node_id(impl_c.def_id).unwrap();
738
739         // Compute skolemized form of impl and trait const tys.
740         let impl_ty = tcx.type_of(impl_c.def_id);
741         let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
742         let mut cause = ObligationCause::misc(impl_c_span, impl_c_node_id);
743
744         // There is no "body" here, so just pass dummy id.
745         let impl_ty = inh.normalize_associated_types_in(impl_c_span,
746                                                         impl_c_node_id,
747                                                         param_env,
748                                                         &impl_ty);
749
750         debug!("compare_const_impl: impl_ty={:?}", impl_ty);
751
752         let trait_ty = inh.normalize_associated_types_in(impl_c_span,
753                                                          impl_c_node_id,
754                                                          param_env,
755                                                          &trait_ty);
756
757         debug!("compare_const_impl: trait_ty={:?}", trait_ty);
758
759         let err = infcx.at(&cause, param_env)
760                        .sup(trait_ty, impl_ty)
761                        .map(|ok| inh.register_infer_ok_obligations(ok));
762
763         if let Err(terr) = err {
764             debug!("checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
765                    impl_ty,
766                    trait_ty);
767
768             // Locate the Span containing just the type of the offending impl
769             match tcx.hir.expect_impl_item(impl_c_node_id).node {
770                 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
771                 _ => bug!("{:?} is not a impl const", impl_c),
772             }
773
774             let mut diag = struct_span_err!(tcx.sess,
775                                             cause.span,
776                                             E0326,
777                                             "implemented const `{}` has an incompatible type for \
778                                              trait",
779                                             trait_c.name);
780
781             let trait_c_node_id = tcx.hir.as_local_node_id(trait_c.def_id);
782             let trait_c_span = trait_c_node_id.map(|trait_c_node_id| {
783                 // Add a label to the Span containing just the type of the const
784                 match tcx.hir.expect_trait_item(trait_c_node_id).node {
785                     TraitItemKind::Const(ref ty, _) => ty.span,
786                     _ => bug!("{:?} is not a trait const", trait_c),
787                 }
788             });
789
790             infcx.note_type_err(&mut diag,
791                                 &cause,
792                                 trait_c_span.map(|span| (span, format!("type in trait"))),
793                                 Some(infer::ValuePairs::Types(ExpectedFound {
794                                     expected: trait_ty,
795                                     found: impl_ty,
796                                 })),
797                                 &terr);
798             diag.emit();
799         }
800
801         // Check that all obligations are satisfied by the implementation's
802         // version.
803         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
804             infcx.report_fulfillment_errors(errors);
805             return;
806         }
807
808         let fcx = FnCtxt::new(&inh, param_env, impl_c_node_id);
809         fcx.regionck_item(impl_c_node_id, impl_c_span, &[]);
810     });
811 }