]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/compare_method.rs
Auto merge of #50710 - Zoxc:value_to_constvalue, r=oli-obk
[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::ty::{self, TyCtxt, GenericParamDefKind};
14 use rustc::ty::util::ExplicitSelf;
15 use rustc::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
16 use rustc::ty::error::{ExpectedFound, TypeError};
17 use rustc::ty::subst::{Subst, Substs};
18 use rustc::util::common::ErrorReported;
19
20 use syntax_pos::Span;
21
22 use super::{Inherited, FnCtxt};
23
24 /// Checks that a method from an impl conforms to the signature of
25 /// the same method as declared in the trait.
26 ///
27 /// # Parameters
28 ///
29 /// - impl_m: type of the method we are checking
30 /// - impl_m_span: span to use for reporting errors
31 /// - trait_m: the method in the trait
32 /// - impl_trait_ref: the TraitRef corresponding to the trait implementation
33
34 pub fn compare_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
35                                      impl_m: &ty::AssociatedItem,
36                                      impl_m_span: Span,
37                                      trait_m: &ty::AssociatedItem,
38                                      impl_trait_ref: ty::TraitRef<'tcx>,
39                                      trait_item_span: Option<Span>) {
40     debug!("compare_impl_method(impl_trait_ref={:?})",
41            impl_trait_ref);
42
43     let impl_m_span = tcx.sess.codemap().def_span(impl_m_span);
44
45     if let Err(ErrorReported) = compare_self_type(tcx,
46                                                   impl_m,
47                                                   impl_m_span,
48                                                   trait_m,
49                                                   impl_trait_ref) {
50         return;
51     }
52
53     if let Err(ErrorReported) = compare_number_of_generics(tcx,
54                                                            impl_m,
55                                                            impl_m_span,
56                                                            trait_m,
57                                                            trait_item_span) {
58         return;
59     }
60
61     if let Err(ErrorReported) = compare_number_of_method_arguments(tcx,
62                                                                    impl_m,
63                                                                    impl_m_span,
64                                                                    trait_m,
65                                                                    trait_item_span) {
66         return;
67     }
68
69     if let Err(ErrorReported) = compare_synthetic_generics(tcx,
70                                                            impl_m,
71                                                            impl_m_span,
72                                                            trait_m,
73                                                            trait_item_span) {
74         return;
75     }
76
77     if let Err(ErrorReported) = compare_predicate_entailment(tcx,
78                                                              impl_m,
79                                                              impl_m_span,
80                                                              trait_m,
81                                                              impl_trait_ref) {
82         return;
83     }
84 }
85
86 fn compare_predicate_entailment<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
87                                           impl_m: &ty::AssociatedItem,
88                                           impl_m_span: Span,
89                                           trait_m: &ty::AssociatedItem,
90                                           impl_trait_ref: ty::TraitRef<'tcx>)
91                                           -> Result<(), ErrorReported> {
92     let trait_to_impl_substs = impl_trait_ref.substs;
93
94     // This node-id should be used for the `body_id` field on each
95     // `ObligationCause` (and the `FnCtxt`). This is what
96     // `regionck_item` expects.
97     let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
98
99     let cause = ObligationCause {
100         span: impl_m_span,
101         body_id: impl_m_node_id,
102         code: ObligationCauseCode::CompareImplMethodObligation {
103             item_name: impl_m.name,
104             impl_item_def_id: impl_m.def_id,
105             trait_item_def_id: trait_m.def_id,
106         },
107     };
108
109     // This code is best explained by example. Consider a trait:
110     //
111     //     trait Trait<'t,T> {
112     //          fn method<'a,M>(t: &'t T, m: &'a M) -> Self;
113     //     }
114     //
115     // And an impl:
116     //
117     //     impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
118     //          fn method<'b,N>(t: &'j &'i U, m: &'b N) -> Foo;
119     //     }
120     //
121     // We wish to decide if those two method types are compatible.
122     //
123     // We start out with trait_to_impl_substs, that maps the trait
124     // type parameters to impl type parameters. This is taken from the
125     // impl trait reference:
126     //
127     //     trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
128     //
129     // We create a mapping `dummy_substs` that maps from the impl type
130     // parameters to fresh types and regions. For type parameters,
131     // this is the identity transform, but we could as well use any
132     // skolemized types. For regions, we convert from bound to free
133     // regions (Note: but only early-bound regions, i.e., those
134     // declared on the impl or used in type parameter bounds).
135     //
136     //     impl_to_skol_substs = {'i => 'i0, U => U0, N => N0 }
137     //
138     // Now we can apply skol_substs to the type of the impl method
139     // to yield a new function type in terms of our fresh, skolemized
140     // types:
141     //
142     //     <'b> fn(t: &'i0 U0, m: &'b) -> Foo
143     //
144     // We now want to extract and substitute the type of the *trait*
145     // method and compare it. To do so, we must create a compound
146     // substitution by combining trait_to_impl_substs and
147     // impl_to_skol_substs, and also adding a mapping for the method
148     // type parameters. We extend the mapping to also include
149     // the method parameters.
150     //
151     //     trait_to_skol_substs = { T => &'i0 U0, Self => Foo, M => N0 }
152     //
153     // Applying this to the trait method type yields:
154     //
155     //     <'a> fn(t: &'i0 U0, m: &'a) -> Foo
156     //
157     // This type is also the same but the name of the bound region ('a
158     // vs 'b).  However, the normal subtyping rules on fn types handle
159     // this kind of equivalency just fine.
160     //
161     // We now use these substitutions to ensure that all declared bounds are
162     // satisfied by the implementation's method.
163     //
164     // We do this by creating a parameter environment which contains a
165     // substitution corresponding to impl_to_skol_substs. We then build
166     // trait_to_skol_substs and use it to convert the predicates contained
167     // in the trait_m.generics to the skolemized form.
168     //
169     // Finally we register each of these predicates as an obligation in
170     // a fresh FulfillmentCtxt, and invoke select_all_or_error.
171
172     // Create mapping from impl to skolemized.
173     let impl_to_skol_substs = Substs::identity_for_item(tcx, impl_m.def_id);
174
175     // Create mapping from trait to skolemized.
176     let trait_to_skol_substs = impl_to_skol_substs.rebase_onto(tcx,
177                                                                impl_m.container.id(),
178                                                                trait_to_impl_substs);
179     debug!("compare_impl_method: trait_to_skol_substs={:?}",
180            trait_to_skol_substs);
181
182     let impl_m_generics = tcx.generics_of(impl_m.def_id);
183     let trait_m_generics = tcx.generics_of(trait_m.def_id);
184     let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
185     let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
186
187     // Check region bounds.
188     check_region_bounds_on_impl_method(tcx,
189                                        impl_m_span,
190                                        impl_m,
191                                        trait_m,
192                                        &trait_m_generics,
193                                        &impl_m_generics,
194                                        trait_to_skol_substs)?;
195
196     // Create obligations for each predicate declared by the impl
197     // definition in the context of the trait's parameter
198     // environment. We can't just use `impl_env.caller_bounds`,
199     // however, because we want to replace all late-bound regions with
200     // region variables.
201     let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
202     let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
203
204     debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
205
206     // This is the only tricky bit of the new way we check implementation methods
207     // We need to build a set of predicates where only the method-level bounds
208     // are from the trait and we assume all other bounds from the implementation
209     // to be previously satisfied.
210     //
211     // We then register the obligations from the impl_m and check to see
212     // if all constraints hold.
213     hybrid_preds.predicates
214                 .extend(trait_m_predicates.instantiate_own(tcx, trait_to_skol_substs).predicates);
215
216     // Construct trait parameter environment and then shift it into the skolemized viewpoint.
217     // The key step here is to update the caller_bounds's predicates to be
218     // the new hybrid bounds we computed.
219     let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_node_id);
220     let param_env = ty::ParamEnv::new(tcx.intern_predicates(&hybrid_preds.predicates),
221                                       Reveal::UserFacing);
222     let param_env = traits::normalize_param_env_or_error(tcx,
223                                                          impl_m.def_id,
224                                                          param_env,
225                                                          normalize_cause.clone());
226
227     tcx.infer_ctxt().enter(|infcx| {
228         let inh = Inherited::new(infcx, impl_m.def_id);
229         let infcx = &inh.infcx;
230
231         debug!("compare_impl_method: caller_bounds={:?}",
232                param_env.caller_bounds);
233
234         let mut selcx = traits::SelectionContext::new(&infcx);
235
236         let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_skol_substs);
237         let (impl_m_own_bounds, _) = infcx.replace_late_bound_regions_with_fresh_var(
238             impl_m_span,
239             infer::HigherRankedType,
240             &ty::Binder::bind(impl_m_own_bounds.predicates)
241         );
242         for predicate in impl_m_own_bounds {
243             let traits::Normalized { value: predicate, obligations } =
244                 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), &predicate);
245
246             inh.register_predicates(obligations);
247             inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
248         }
249
250         // We now need to check that the signature of the impl method is
251         // compatible with that of the trait method. We do this by
252         // checking that `impl_fty <: trait_fty`.
253         //
254         // FIXME. Unfortunately, this doesn't quite work right now because
255         // associated type normalization is not integrated into subtype
256         // checks. For the comparison to be valid, we need to
257         // normalize the associated types in the impl/trait methods
258         // first. However, because function types bind regions, just
259         // calling `normalize_associated_types_in` would have no effect on
260         // any associated types appearing in the fn arguments or return
261         // type.
262
263         // Compute skolemized form of impl and trait method tys.
264         let tcx = infcx.tcx;
265
266         let (impl_sig, _) =
267             infcx.replace_late_bound_regions_with_fresh_var(impl_m_span,
268                                                             infer::HigherRankedType,
269                                                             &tcx.fn_sig(impl_m.def_id));
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::bind(impl_sig));
276         debug!("compare_impl_method: impl_fty={:?}", impl_fty);
277
278         let trait_sig = tcx.liberate_late_bound_regions(
279             impl_m.def_id,
280             &tcx.fn_sig(trait_m.def_id));
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::bind(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(&tcx),
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, None, false);
339             return Err(ErrorReported);
340         }
341
342         // Finally, resolve all regions. This catches wily misuses of
343         // lifetime parameters.
344         let fcx = FnCtxt::new(&inh, param_env, impl_m_node_id);
345         fcx.regionck_item(impl_m_node_id, impl_m_span, &[]);
346
347         Ok(())
348     })
349 }
350
351 fn check_region_bounds_on_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
352                                                 span: Span,
353                                                 impl_m: &ty::AssociatedItem,
354                                                 trait_m: &ty::AssociatedItem,
355                                                 trait_generics: &ty::Generics,
356                                                 impl_generics: &ty::Generics,
357                                                 trait_to_skol_substs: &Substs<'tcx>)
358                                                 -> Result<(), ErrorReported> {
359     let span = tcx.sess.codemap().def_span(span);
360     let trait_params = trait_generics.own_counts().lifetimes;
361     let impl_params = impl_generics.own_counts().lifetimes;
362
363     debug!("check_region_bounds_on_impl_method: \
364             trait_generics={:?} \
365             impl_generics={:?} \
366             trait_to_skol_substs={:?}",
367            trait_generics,
368            impl_generics,
369            trait_to_skol_substs);
370
371     // Must have same number of early-bound lifetime parameters.
372     // Unfortunately, if the user screws up the bounds, then this
373     // will change classification between early and late.  E.g.,
374     // if in trait we have `<'a,'b:'a>`, and in impl we just have
375     // `<'a,'b>`, then we have 2 early-bound lifetime parameters
376     // in trait but 0 in the impl. But if we report "expected 2
377     // but found 0" it's confusing, because it looks like there
378     // are zero. Since I don't quite know how to phrase things at
379     // the moment, give a kind of vague error message.
380     if trait_params != impl_params {
381         let mut err = struct_span_err!(tcx.sess,
382                                        span,
383                                        E0195,
384                                        "lifetime parameters or bounds on method `{}` do not match \
385                                         the trait declaration",
386                                        impl_m.name);
387         err.span_label(span, "lifetimes do not match method in trait");
388         if let Some(sp) = tcx.hir.span_if_local(trait_m.def_id) {
389             err.span_label(tcx.sess.codemap().def_span(sp),
390                            "lifetimes in impl do not match this method in trait");
391         }
392         err.emit();
393         return Err(ErrorReported);
394     }
395
396     return Ok(());
397 }
398
399 fn extract_spans_for_error_reporting<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
400                                                      param_env: ty::ParamEnv<'tcx>,
401                                                      terr: &TypeError,
402                                                      cause: &ObligationCause<'tcx>,
403                                                      impl_m: &ty::AssociatedItem,
404                                                      impl_sig: ty::FnSig<'tcx>,
405                                                      trait_m: &ty::AssociatedItem,
406                                                      trait_sig: ty::FnSig<'tcx>)
407                                                      -> (Span, Option<Span>) {
408     let tcx = infcx.tcx;
409     let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
410     let (impl_m_output, impl_m_iter) = match tcx.hir.expect_impl_item(impl_m_node_id).node {
411         ImplItemKind::Method(ref impl_m_sig, _) => {
412             (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter())
413         }
414         _ => bug!("{:?} is not a method", impl_m),
415     };
416
417     match *terr {
418         TypeError::Mutability => {
419             if let Some(trait_m_node_id) = tcx.hir.as_local_node_id(trait_m.def_id) {
420                 let trait_m_iter = match tcx.hir.expect_trait_item(trait_m_node_id).node {
421                     TraitItemKind::Method(ref trait_m_sig, _) => {
422                         trait_m_sig.decl.inputs.iter()
423                     }
424                     _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
425                 };
426
427                 impl_m_iter.zip(trait_m_iter).find(|&(ref impl_arg, ref trait_arg)| {
428                     match (&impl_arg.node, &trait_arg.node) {
429                         (&hir::TyRptr(_, ref impl_mt), &hir::TyRptr(_, ref trait_mt)) |
430                         (&hir::TyPtr(ref impl_mt), &hir::TyPtr(ref trait_mt)) => {
431                             impl_mt.mutbl != trait_mt.mutbl
432                         }
433                         _ => false,
434                     }
435                 }).map(|(ref impl_arg, ref trait_arg)| {
436                     (impl_arg.span, Some(trait_arg.span))
437                 })
438                 .unwrap_or_else(|| (cause.span(&tcx), tcx.hir.span_if_local(trait_m.def_id)))
439             } else {
440                 (cause.span(&tcx), tcx.hir.span_if_local(trait_m.def_id))
441             }
442         }
443         TypeError::Sorts(ExpectedFound { .. }) => {
444             if let Some(trait_m_node_id) = tcx.hir.as_local_node_id(trait_m.def_id) {
445                 let (trait_m_output, trait_m_iter) =
446                     match tcx.hir.expect_trait_item(trait_m_node_id).node {
447                         TraitItemKind::Method(ref trait_m_sig, _) => {
448                             (&trait_m_sig.decl.output, trait_m_sig.decl.inputs.iter())
449                         }
450                         _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
451                     };
452
453                 let impl_iter = impl_sig.inputs().iter();
454                 let trait_iter = trait_sig.inputs().iter();
455                 impl_iter.zip(trait_iter)
456                          .zip(impl_m_iter)
457                          .zip(trait_m_iter)
458                          .filter_map(|(((&impl_arg_ty, &trait_arg_ty), impl_arg), trait_arg)| {
459                              match infcx.at(&cause, param_env).sub(trait_arg_ty, impl_arg_ty) {
460                                  Ok(_) => None,
461                                  Err(_) => Some((impl_arg.span, Some(trait_arg.span))),
462                              }
463                          })
464                          .next()
465                          .unwrap_or_else(|| {
466                              if
467                                  infcx.at(&cause, param_env)
468                                       .sup(trait_sig.output(), impl_sig.output())
469                                       .is_err()
470                              {
471                                  (impl_m_output.span(), Some(trait_m_output.span()))
472                              } else {
473                                  (cause.span(&tcx), tcx.hir.span_if_local(trait_m.def_id))
474                              }
475                          })
476             } else {
477                 (cause.span(&tcx), tcx.hir.span_if_local(trait_m.def_id))
478             }
479         }
480         _ => (cause.span(&tcx), tcx.hir.span_if_local(trait_m.def_id)),
481     }
482 }
483
484 fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
485                                impl_m: &ty::AssociatedItem,
486                                impl_m_span: Span,
487                                trait_m: &ty::AssociatedItem,
488                                impl_trait_ref: ty::TraitRef<'tcx>)
489                                -> Result<(), ErrorReported>
490 {
491     // Try to give more informative error messages about self typing
492     // mismatches.  Note that any mismatch will also be detected
493     // below, where we construct a canonical function type that
494     // includes the self parameter as a normal parameter.  It's just
495     // that the error messages you get out of this code are a bit more
496     // inscrutable, particularly for cases where one method has no
497     // self.
498
499     let self_string = |method: &ty::AssociatedItem| {
500         let untransformed_self_ty = match method.container {
501             ty::ImplContainer(_) => impl_trait_ref.self_ty(),
502             ty::TraitContainer(_) => tcx.mk_self_type()
503         };
504         let self_arg_ty = *tcx.fn_sig(method.def_id).input(0).skip_binder();
505         let param_env = ty::ParamEnv::reveal_all();
506
507         tcx.infer_ctxt().enter(|infcx| {
508             let self_arg_ty = tcx.liberate_late_bound_regions(
509                 method.def_id,
510                 &ty::Binder::bind(self_arg_ty)
511             );
512             let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
513             match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
514                 ExplicitSelf::ByValue => "self".to_string(),
515                 ExplicitSelf::ByReference(_, hir::MutImmutable) => "&self".to_string(),
516                 ExplicitSelf::ByReference(_, hir::MutMutable) => "&mut self".to_string(),
517                 _ => format!("self: {}", self_arg_ty)
518             }
519         })
520     };
521
522     match (trait_m.method_has_self_argument, impl_m.method_has_self_argument) {
523         (false, false) | (true, true) => {}
524
525         (false, true) => {
526             let self_descr = self_string(impl_m);
527             let mut err = struct_span_err!(tcx.sess,
528                                            impl_m_span,
529                                            E0185,
530                                            "method `{}` has a `{}` declaration in the impl, but \
531                                             not in the trait",
532                                            trait_m.name,
533                                            self_descr);
534             err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
535             if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
536                 err.span_label(span, format!("trait method declared without `{}`", self_descr));
537             } else {
538                 err.note_trait_signature(trait_m.name.to_string(),
539                                          trait_m.signature(&tcx));
540             }
541             err.emit();
542             return Err(ErrorReported);
543         }
544
545         (true, false) => {
546             let self_descr = self_string(trait_m);
547             let mut err = struct_span_err!(tcx.sess,
548                                            impl_m_span,
549                                            E0186,
550                                            "method `{}` has a `{}` declaration in the trait, but \
551                                             not in the impl",
552                                            trait_m.name,
553                                            self_descr);
554             err.span_label(impl_m_span, format!("expected `{}` in impl", self_descr));
555             if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
556                 err.span_label(span, format!("`{}` used in trait", self_descr));
557             } else {
558                 err.note_trait_signature(trait_m.name.to_string(),
559                                          trait_m.signature(&tcx));
560             }
561             err.emit();
562             return Err(ErrorReported);
563         }
564     }
565
566     Ok(())
567 }
568
569 fn compare_number_of_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
570                                         impl_m: &ty::AssociatedItem,
571                                         impl_m_span: Span,
572                                         trait_m: &ty::AssociatedItem,
573                                         trait_item_span: Option<Span>)
574                                         -> Result<(), ErrorReported> {
575     let impl_m_generics = tcx.generics_of(impl_m.def_id);
576     let trait_m_generics = tcx.generics_of(trait_m.def_id);
577     let num_impl_m_type_params = impl_m_generics.own_counts().types;
578     let num_trait_m_type_params = trait_m_generics.own_counts().types;
579     if num_impl_m_type_params != num_trait_m_type_params {
580         let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
581         let impl_m_item = tcx.hir.expect_impl_item(impl_m_node_id);
582         let span = if impl_m_item.generics.params.is_empty() {
583             impl_m_span
584         } else {
585             impl_m_item.generics.span
586         };
587
588         let mut err = struct_span_err!(tcx.sess,
589                                        span,
590                                        E0049,
591                                        "method `{}` has {} type parameter{} but its trait \
592                                         declaration has {} type parameter{}",
593                                        trait_m.name,
594                                        num_impl_m_type_params,
595                                        if num_impl_m_type_params == 1 { "" } else { "s" },
596                                        num_trait_m_type_params,
597                                        if num_trait_m_type_params == 1 {
598                                            ""
599                                        } else {
600                                            "s"
601                                        });
602
603         let mut suffix = None;
604
605         if let Some(span) = trait_item_span {
606             err.span_label(span,
607                            format!("expected {}",
608                                     &if num_trait_m_type_params != 1 {
609                                         format!("{} type parameters", num_trait_m_type_params)
610                                     } else {
611                                         format!("{} type parameter", num_trait_m_type_params)
612                                     }));
613         } else {
614             suffix = Some(format!(", expected {}", num_trait_m_type_params));
615         }
616
617         err.span_label(span,
618                        format!("found {}{}",
619                                 &if num_impl_m_type_params != 1 {
620                                     format!("{} type parameters", num_impl_m_type_params)
621                                 } else {
622                                     format!("1 type parameter")
623                                 },
624                                 suffix.as_ref().map(|s| &s[..]).unwrap_or("")));
625
626         err.emit();
627
628         return Err(ErrorReported);
629     }
630
631     Ok(())
632 }
633
634 fn compare_number_of_method_arguments<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
635                                                 impl_m: &ty::AssociatedItem,
636                                                 impl_m_span: Span,
637                                                 trait_m: &ty::AssociatedItem,
638                                                 trait_item_span: Option<Span>)
639                                                 -> Result<(), ErrorReported> {
640     let impl_m_fty = tcx.fn_sig(impl_m.def_id);
641     let trait_m_fty = tcx.fn_sig(trait_m.def_id);
642     let trait_number_args = trait_m_fty.inputs().skip_binder().len();
643     let impl_number_args = impl_m_fty.inputs().skip_binder().len();
644     if trait_number_args != impl_number_args {
645         let trait_m_node_id = tcx.hir.as_local_node_id(trait_m.def_id);
646         let trait_span = if let Some(trait_id) = trait_m_node_id {
647             match tcx.hir.expect_trait_item(trait_id).node {
648                 TraitItemKind::Method(ref trait_m_sig, _) => {
649                     if let Some(arg) = trait_m_sig.decl.inputs.get(if trait_number_args > 0 {
650                         trait_number_args - 1
651                     } else {
652                         0
653                     }) {
654                         Some(arg.span)
655                     } else {
656                         trait_item_span
657                     }
658                 }
659                 _ => bug!("{:?} is not a method", impl_m),
660             }
661         } else {
662             trait_item_span
663         };
664         let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
665         let impl_span = match tcx.hir.expect_impl_item(impl_m_node_id).node {
666             ImplItemKind::Method(ref impl_m_sig, _) => {
667                 if let Some(arg) = impl_m_sig.decl.inputs.get(if impl_number_args > 0 {
668                     impl_number_args - 1
669                 } else {
670                     0
671                 }) {
672                     arg.span
673                 } else {
674                     impl_m_span
675                 }
676             }
677             _ => bug!("{:?} is not a method", impl_m),
678         };
679         let mut err = struct_span_err!(tcx.sess,
680                                        impl_span,
681                                        E0050,
682                                        "method `{}` has {} parameter{} but the declaration in \
683                                         trait `{}` has {}",
684                                        trait_m.name,
685                                        impl_number_args,
686                                        if impl_number_args == 1 { "" } else { "s" },
687                                        tcx.item_path_str(trait_m.def_id),
688                                        trait_number_args);
689         if let Some(trait_span) = trait_span {
690             err.span_label(trait_span,
691                            format!("trait requires {}",
692                                     &if trait_number_args != 1 {
693                                         format!("{} parameters", trait_number_args)
694                                     } else {
695                                         format!("{} parameter", trait_number_args)
696                                     }));
697         } else {
698             err.note_trait_signature(trait_m.name.to_string(),
699                                      trait_m.signature(&tcx));
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 fn compare_synthetic_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
717                                         impl_m: &ty::AssociatedItem,
718                                         _impl_m_span: Span, // FIXME necessary?
719                                         trait_m: &ty::AssociatedItem,
720                                         _trait_item_span: Option<Span>) // FIXME necessary?
721                                         -> Result<(), ErrorReported> {
722     // FIXME(chrisvittal) Clean up this function, list of FIXME items:
723     //     1. Better messages for the span lables
724     //     2. Explanation as to what is going on
725     //     3. Correct the function signature for what we actually use
726     // If we get here, we already have the same number of generics, so the zip will
727     // be okay.
728     let mut error_found = false;
729     let impl_m_generics = tcx.generics_of(impl_m.def_id);
730     let trait_m_generics = tcx.generics_of(trait_m.def_id);
731     let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| {
732         match param.kind {
733             GenericParamDefKind::Type(ty) => Some((param.def_id, ty.synthetic)),
734             GenericParamDefKind::Lifetime => None,
735         }
736     });
737     let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| {
738         match param.kind {
739             GenericParamDefKind::Type(ty) => Some((param.def_id, ty.synthetic)),
740             GenericParamDefKind::Lifetime => None,
741         }
742     });
743     for ((impl_def_id, impl_synthetic),
744          (trait_def_id, trait_synthetic)) in impl_m_type_params.zip(trait_m_type_params) {
745         if impl_synthetic != trait_synthetic {
746             let impl_node_id = tcx.hir.as_local_node_id(impl_def_id).unwrap();
747             let impl_span = tcx.hir.span(impl_node_id);
748             let trait_span = tcx.def_span(trait_def_id);
749             let mut err = struct_span_err!(tcx.sess,
750                                            impl_span,
751                                            E0643,
752                                            "method `{}` has incompatible signature for trait",
753                                            trait_m.name);
754             err.span_label(trait_span, "annotation in trait");
755             err.span_label(impl_span, "annotation in impl");
756             err.emit();
757             error_found = true;
758         }
759     }
760     if error_found {
761         Err(ErrorReported)
762     } else {
763         Ok(())
764     }
765 }
766
767 pub fn compare_const_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
768                                     impl_c: &ty::AssociatedItem,
769                                     impl_c_span: Span,
770                                     trait_c: &ty::AssociatedItem,
771                                     impl_trait_ref: ty::TraitRef<'tcx>) {
772     debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
773
774     tcx.infer_ctxt().enter(|infcx| {
775         let param_env = ty::ParamEnv::empty();
776         let inh = Inherited::new(infcx, impl_c.def_id);
777         let infcx = &inh.infcx;
778
779         // The below is for the most part highly similar to the procedure
780         // for methods above. It is simpler in many respects, especially
781         // because we shouldn't really have to deal with lifetimes or
782         // predicates. In fact some of this should probably be put into
783         // shared functions because of DRY violations...
784         let trait_to_impl_substs = impl_trait_ref.substs;
785
786         // Create a parameter environment that represents the implementation's
787         // method.
788         let impl_c_node_id = tcx.hir.as_local_node_id(impl_c.def_id).unwrap();
789
790         // Compute skolemized form of impl and trait const tys.
791         let impl_ty = tcx.type_of(impl_c.def_id);
792         let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
793         let mut cause = ObligationCause::misc(impl_c_span, impl_c_node_id);
794
795         // There is no "body" here, so just pass dummy id.
796         let impl_ty = inh.normalize_associated_types_in(impl_c_span,
797                                                         impl_c_node_id,
798                                                         param_env,
799                                                         &impl_ty);
800
801         debug!("compare_const_impl: impl_ty={:?}", impl_ty);
802
803         let trait_ty = inh.normalize_associated_types_in(impl_c_span,
804                                                          impl_c_node_id,
805                                                          param_env,
806                                                          &trait_ty);
807
808         debug!("compare_const_impl: trait_ty={:?}", trait_ty);
809
810         let err = infcx.at(&cause, param_env)
811                        .sup(trait_ty, impl_ty)
812                        .map(|ok| inh.register_infer_ok_obligations(ok));
813
814         if let Err(terr) = err {
815             debug!("checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
816                    impl_ty,
817                    trait_ty);
818
819             // Locate the Span containing just the type of the offending impl
820             match tcx.hir.expect_impl_item(impl_c_node_id).node {
821                 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
822                 _ => bug!("{:?} is not a impl const", impl_c),
823             }
824
825             let mut diag = struct_span_err!(tcx.sess,
826                                             cause.span,
827                                             E0326,
828                                             "implemented const `{}` has an incompatible type for \
829                                              trait",
830                                             trait_c.name);
831
832             let trait_c_node_id = tcx.hir.as_local_node_id(trait_c.def_id);
833             let trait_c_span = trait_c_node_id.map(|trait_c_node_id| {
834                 // Add a label to the Span containing just the type of the const
835                 match tcx.hir.expect_trait_item(trait_c_node_id).node {
836                     TraitItemKind::Const(ref ty, _) => ty.span,
837                     _ => bug!("{:?} is not a trait const", trait_c),
838                 }
839             });
840
841             infcx.note_type_err(&mut diag,
842                                 &cause,
843                                 trait_c_span.map(|span| (span, format!("type in trait"))),
844                                 Some(infer::ValuePairs::Types(ExpectedFound {
845                                     expected: trait_ty,
846                                     found: impl_ty,
847                                 })),
848                                 &terr);
849             diag.emit();
850         }
851
852         // Check that all obligations are satisfied by the implementation's
853         // version.
854         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
855             infcx.report_fulfillment_errors(errors, None, false);
856             return;
857         }
858
859         let fcx = FnCtxt::new(&inh, param_env, impl_c_node_id);
860         fcx.regionck_item(impl_c_node_id, impl_c_span, &[]);
861     });
862 }