]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/compare_method.rs
Rollup merge of #48824 - davidalber:update-conduct, 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 rustc::hir::{self, ImplItemKind, TraitItemKind};
12 use rustc::infer::{self, InferOk};
13 use rustc::ty::{self, TyCtxt};
14 use rustc::ty::util::ExplicitSelf;
15 use rustc::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
16 use rustc::ty::error::{ExpectedFound, TypeError};
17 use rustc::ty::subst::{Subst, Substs};
18 use rustc::util::common::ErrorReported;
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                                       ty::UniverseIndex::ROOT);
223     let param_env = traits::normalize_param_env_or_error(tcx,
224                                                          impl_m.def_id,
225                                                          param_env,
226                                                          normalize_cause.clone());
227
228     tcx.infer_ctxt().enter(|infcx| {
229         let inh = Inherited::new(infcx, impl_m.def_id);
230         let infcx = &inh.infcx;
231
232         debug!("compare_impl_method: caller_bounds={:?}",
233                param_env.caller_bounds);
234
235         let mut selcx = traits::SelectionContext::new(&infcx);
236
237         let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_skol_substs);
238         let (impl_m_own_bounds, _) = infcx.replace_late_bound_regions_with_fresh_var(impl_m_span,
239                                                        infer::HigherRankedType,
240                                                        &ty::Binder(impl_m_own_bounds.predicates));
241         for predicate in impl_m_own_bounds {
242             let traits::Normalized { value: predicate, obligations } =
243                 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), &predicate);
244
245             inh.register_predicates(obligations);
246             inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
247         }
248
249         // We now need to check that the signature of the impl method is
250         // compatible with that of the trait method. We do this by
251         // checking that `impl_fty <: trait_fty`.
252         //
253         // FIXME. Unfortunately, this doesn't quite work right now because
254         // associated type normalization is not integrated into subtype
255         // checks. For the comparison to be valid, we need to
256         // normalize the associated types in the impl/trait methods
257         // first. However, because function types bind regions, just
258         // calling `normalize_associated_types_in` would have no effect on
259         // any associated types appearing in the fn arguments or return
260         // type.
261
262         // Compute skolemized form of impl and trait method tys.
263         let tcx = infcx.tcx;
264
265         let (impl_sig, _) =
266             infcx.replace_late_bound_regions_with_fresh_var(impl_m_span,
267                                                             infer::HigherRankedType,
268                                                             &tcx.fn_sig(impl_m.def_id));
269         let impl_sig =
270             inh.normalize_associated_types_in(impl_m_span,
271                                               impl_m_node_id,
272                                               param_env,
273                                               &impl_sig);
274         let impl_fty = tcx.mk_fn_ptr(ty::Binder(impl_sig));
275         debug!("compare_impl_method: impl_fty={:?}", impl_fty);
276
277         let trait_sig = tcx.liberate_late_bound_regions(
278             impl_m.def_id,
279             &tcx.fn_sig(trait_m.def_id));
280         let trait_sig =
281             trait_sig.subst(tcx, trait_to_skol_substs);
282         let trait_sig =
283             inh.normalize_associated_types_in(impl_m_span,
284                                               impl_m_node_id,
285                                               param_env,
286                                               &trait_sig);
287         let trait_fty = tcx.mk_fn_ptr(ty::Binder(trait_sig));
288
289         debug!("compare_impl_method: trait_fty={:?}", trait_fty);
290
291         let sub_result = infcx.at(&cause, param_env)
292                               .sup(trait_fty, impl_fty)
293                               .map(|InferOk { obligations, .. }| {
294                                   inh.register_predicates(obligations);
295                               });
296
297         if let Err(terr) = sub_result {
298             debug!("sub_types failed: impl ty {:?}, trait ty {:?}",
299                    impl_fty,
300                    trait_fty);
301
302             let (impl_err_span, trait_err_span) = extract_spans_for_error_reporting(&infcx,
303                                                                                     param_env,
304                                                                                     &terr,
305                                                                                     &cause,
306                                                                                     impl_m,
307                                                                                     impl_sig,
308                                                                                     trait_m,
309                                                                                     trait_sig);
310
311             let cause = ObligationCause {
312                 span: impl_err_span,
313                 ..cause.clone()
314             };
315
316             let mut diag = struct_span_err!(tcx.sess,
317                                             cause.span(&tcx),
318                                             E0053,
319                                             "method `{}` has an incompatible type for trait",
320                                             trait_m.name);
321
322             infcx.note_type_err(&mut diag,
323                                 &cause,
324                                 trait_err_span.map(|sp| (sp, format!("type in trait"))),
325                                 Some(infer::ValuePairs::Types(ExpectedFound {
326                                     expected: trait_fty,
327                                     found: impl_fty,
328                                 })),
329                                 &terr);
330             diag.emit();
331             return Err(ErrorReported);
332         }
333
334         // Check that all obligations are satisfied by the implementation's
335         // version.
336         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
337             infcx.report_fulfillment_errors(errors, None);
338             return Err(ErrorReported);
339         }
340
341         // Finally, resolve all regions. This catches wily misuses of
342         // lifetime parameters.
343         let fcx = FnCtxt::new(&inh, param_env, impl_m_node_id);
344         fcx.regionck_item(impl_m_node_id, impl_m_span, &[]);
345
346         Ok(())
347     })
348 }
349
350 fn check_region_bounds_on_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
351                                                 span: Span,
352                                                 impl_m: &ty::AssociatedItem,
353                                                 trait_m: &ty::AssociatedItem,
354                                                 trait_generics: &ty::Generics,
355                                                 impl_generics: &ty::Generics,
356                                                 trait_to_skol_substs: &Substs<'tcx>)
357                                                 -> Result<(), ErrorReported> {
358     let span = tcx.sess.codemap().def_span(span);
359     let trait_params = &trait_generics.regions[..];
360     let impl_params = &impl_generics.regions[..];
361
362     debug!("check_region_bounds_on_impl_method: \
363             trait_generics={:?} \
364             impl_generics={:?} \
365             trait_to_skol_substs={:?}",
366            trait_generics,
367            impl_generics,
368            trait_to_skol_substs);
369
370     // Must have same number of early-bound lifetime parameters.
371     // Unfortunately, if the user screws up the bounds, then this
372     // will change classification between early and late.  E.g.,
373     // if in trait we have `<'a,'b:'a>`, and in impl we just have
374     // `<'a,'b>`, then we have 2 early-bound lifetime parameters
375     // in trait but 0 in the impl. But if we report "expected 2
376     // but found 0" it's confusing, because it looks like there
377     // are zero. Since I don't quite know how to phrase things at
378     // the moment, give a kind of vague error message.
379     if trait_params.len() != impl_params.len() {
380         let mut err = struct_span_err!(tcx.sess,
381                                        span,
382                                        E0195,
383                                        "lifetime parameters or bounds on method `{}` do not match \
384                                         the trait declaration",
385                                        impl_m.name);
386         err.span_label(span, "lifetimes do not match method in trait");
387         if let Some(sp) = tcx.hir.span_if_local(trait_m.def_id) {
388             err.span_label(tcx.sess.codemap().def_span(sp),
389                            "lifetimes in impl do not match this method in trait");
390         }
391         err.emit();
392         return Err(ErrorReported);
393     }
394
395     return Ok(());
396 }
397
398 fn extract_spans_for_error_reporting<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
399                                                      param_env: ty::ParamEnv<'tcx>,
400                                                      terr: &TypeError,
401                                                      cause: &ObligationCause<'tcx>,
402                                                      impl_m: &ty::AssociatedItem,
403                                                      impl_sig: ty::FnSig<'tcx>,
404                                                      trait_m: &ty::AssociatedItem,
405                                                      trait_sig: ty::FnSig<'tcx>)
406                                                      -> (Span, Option<Span>) {
407     let tcx = infcx.tcx;
408     let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
409     let (impl_m_output, impl_m_iter) = match tcx.hir.expect_impl_item(impl_m_node_id).node {
410         ImplItemKind::Method(ref impl_m_sig, _) => {
411             (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter())
412         }
413         _ => bug!("{:?} is not a method", impl_m),
414     };
415
416     match *terr {
417         TypeError::Mutability => {
418             if let Some(trait_m_node_id) = tcx.hir.as_local_node_id(trait_m.def_id) {
419                 let trait_m_iter = match tcx.hir.expect_trait_item(trait_m_node_id).node {
420                     TraitItemKind::Method(ref trait_m_sig, _) => {
421                         trait_m_sig.decl.inputs.iter()
422                     }
423                     _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
424                 };
425
426                 impl_m_iter.zip(trait_m_iter).find(|&(ref impl_arg, ref trait_arg)| {
427                     match (&impl_arg.node, &trait_arg.node) {
428                         (&hir::TyRptr(_, ref impl_mt), &hir::TyRptr(_, ref trait_mt)) |
429                         (&hir::TyPtr(ref impl_mt), &hir::TyPtr(ref trait_mt)) => {
430                             impl_mt.mutbl != trait_mt.mutbl
431                         }
432                         _ => false,
433                     }
434                 }).map(|(ref impl_arg, ref trait_arg)| {
435                     (impl_arg.span, Some(trait_arg.span))
436                 })
437                 .unwrap_or_else(|| (cause.span(&tcx), tcx.hir.span_if_local(trait_m.def_id)))
438             } else {
439                 (cause.span(&tcx), tcx.hir.span_if_local(trait_m.def_id))
440             }
441         }
442         TypeError::Sorts(ExpectedFound { .. }) => {
443             if let Some(trait_m_node_id) = tcx.hir.as_local_node_id(trait_m.def_id) {
444                 let (trait_m_output, trait_m_iter) =
445                     match tcx.hir.expect_trait_item(trait_m_node_id).node {
446                         TraitItemKind::Method(ref trait_m_sig, _) => {
447                             (&trait_m_sig.decl.output, trait_m_sig.decl.inputs.iter())
448                         }
449                         _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
450                     };
451
452                 let impl_iter = impl_sig.inputs().iter();
453                 let trait_iter = trait_sig.inputs().iter();
454                 impl_iter.zip(trait_iter)
455                          .zip(impl_m_iter)
456                          .zip(trait_m_iter)
457                          .filter_map(|(((&impl_arg_ty, &trait_arg_ty), impl_arg), trait_arg)| {
458                              match infcx.at(&cause, param_env).sub(trait_arg_ty, impl_arg_ty) {
459                                  Ok(_) => None,
460                                  Err(_) => Some((impl_arg.span, Some(trait_arg.span))),
461                              }
462                          })
463                          .next()
464                          .unwrap_or_else(|| {
465                              if
466                                  infcx.at(&cause, param_env)
467                                       .sup(trait_sig.output(), impl_sig.output())
468                                       .is_err()
469                              {
470                                  (impl_m_output.span(), Some(trait_m_output.span()))
471                              } else {
472                                  (cause.span(&tcx), tcx.hir.span_if_local(trait_m.def_id))
473                              }
474                          })
475             } else {
476                 (cause.span(&tcx), tcx.hir.span_if_local(trait_m.def_id))
477             }
478         }
479         _ => (cause.span(&tcx), tcx.hir.span_if_local(trait_m.def_id)),
480     }
481 }
482
483 fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
484                                impl_m: &ty::AssociatedItem,
485                                impl_m_span: Span,
486                                trait_m: &ty::AssociatedItem,
487                                impl_trait_ref: ty::TraitRef<'tcx>)
488                                -> Result<(), ErrorReported>
489 {
490     // Try to give more informative error messages about self typing
491     // mismatches.  Note that any mismatch will also be detected
492     // below, where we construct a canonical function type that
493     // includes the self parameter as a normal parameter.  It's just
494     // that the error messages you get out of this code are a bit more
495     // inscrutable, particularly for cases where one method has no
496     // self.
497
498     let self_string = |method: &ty::AssociatedItem| {
499         let untransformed_self_ty = match method.container {
500             ty::ImplContainer(_) => impl_trait_ref.self_ty(),
501             ty::TraitContainer(_) => tcx.mk_self_type()
502         };
503         let self_arg_ty = *tcx.fn_sig(method.def_id).input(0).skip_binder();
504         let param_env = ty::ParamEnv::empty(Reveal::All);
505
506         tcx.infer_ctxt().enter(|infcx| {
507             let self_arg_ty = tcx.liberate_late_bound_regions(
508                 method.def_id,
509                 &ty::Binder(self_arg_ty)
510             );
511             let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
512             match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
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
521     match (trait_m.method_has_self_argument, impl_m.method_has_self_argument) {
522         (false, false) | (true, true) => {}
523
524         (false, true) => {
525             let self_descr = self_string(impl_m);
526             let mut err = struct_span_err!(tcx.sess,
527                                            impl_m_span,
528                                            E0185,
529                                            "method `{}` has a `{}` declaration in the impl, but \
530                                             not in the trait",
531                                            trait_m.name,
532                                            self_descr);
533             err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
534             if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
535                 err.span_label(span, format!("trait method declared without `{}`", self_descr));
536             } else {
537                 err.note_trait_signature(trait_m.name.to_string(),
538                                          trait_m.signature(&tcx));
539             }
540             err.emit();
541             return Err(ErrorReported);
542         }
543
544         (true, false) => {
545             let self_descr = self_string(trait_m);
546             let mut err = struct_span_err!(tcx.sess,
547                                            impl_m_span,
548                                            E0186,
549                                            "method `{}` has a `{}` declaration in the trait, but \
550                                             not in the impl",
551                                            trait_m.name,
552                                            self_descr);
553             err.span_label(impl_m_span, format!("expected `{}` in impl", self_descr));
554             if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
555                 err.span_label(span, format!("`{}` used in trait", self_descr));
556             } else {
557                 err.note_trait_signature(trait_m.name.to_string(),
558                                          trait_m.signature(&tcx));
559             }
560             err.emit();
561             return Err(ErrorReported);
562         }
563     }
564
565     Ok(())
566 }
567
568 fn compare_number_of_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
569                                         impl_m: &ty::AssociatedItem,
570                                         impl_m_span: Span,
571                                         trait_m: &ty::AssociatedItem,
572                                         trait_item_span: Option<Span>)
573                                         -> Result<(), ErrorReported> {
574     let impl_m_generics = tcx.generics_of(impl_m.def_id);
575     let trait_m_generics = tcx.generics_of(trait_m.def_id);
576     let num_impl_m_type_params = impl_m_generics.types.len();
577     let num_trait_m_type_params = trait_m_generics.types.len();
578     if num_impl_m_type_params != num_trait_m_type_params {
579         let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
580         let impl_m_item = tcx.hir.expect_impl_item(impl_m_node_id);
581         let span = if impl_m_item.generics.params.is_empty() {
582             impl_m_span
583         } else {
584             impl_m_item.generics.span
585         };
586
587         let mut err = struct_span_err!(tcx.sess,
588                                        span,
589                                        E0049,
590                                        "method `{}` has {} type parameter{} but its trait \
591                                         declaration has {} type parameter{}",
592                                        trait_m.name,
593                                        num_impl_m_type_params,
594                                        if num_impl_m_type_params == 1 { "" } else { "s" },
595                                        num_trait_m_type_params,
596                                        if num_trait_m_type_params == 1 {
597                                            ""
598                                        } else {
599                                            "s"
600                                        });
601
602         let mut suffix = None;
603
604         if let Some(span) = trait_item_span {
605             err.span_label(span,
606                            format!("expected {}",
607                                     &if num_trait_m_type_params != 1 {
608                                         format!("{} type parameters", num_trait_m_type_params)
609                                     } else {
610                                         format!("{} type parameter", num_trait_m_type_params)
611                                     }));
612         } else {
613             suffix = Some(format!(", expected {}", num_trait_m_type_params));
614         }
615
616         err.span_label(span,
617                        format!("found {}{}",
618                                 &if num_impl_m_type_params != 1 {
619                                     format!("{} type parameters", num_impl_m_type_params)
620                                 } else {
621                                     format!("1 type parameter")
622                                 },
623                                 suffix.as_ref().map(|s| &s[..]).unwrap_or("")));
624
625         err.emit();
626
627         return Err(ErrorReported);
628     }
629
630     Ok(())
631 }
632
633 fn compare_number_of_method_arguments<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
634                                                 impl_m: &ty::AssociatedItem,
635                                                 impl_m_span: Span,
636                                                 trait_m: &ty::AssociatedItem,
637                                                 trait_item_span: Option<Span>)
638                                                 -> Result<(), ErrorReported> {
639     let impl_m_fty = tcx.fn_sig(impl_m.def_id);
640     let trait_m_fty = tcx.fn_sig(trait_m.def_id);
641     let trait_number_args = trait_m_fty.inputs().skip_binder().len();
642     let impl_number_args = impl_m_fty.inputs().skip_binder().len();
643     if trait_number_args != impl_number_args {
644         let trait_m_node_id = tcx.hir.as_local_node_id(trait_m.def_id);
645         let trait_span = if let Some(trait_id) = trait_m_node_id {
646             match tcx.hir.expect_trait_item(trait_id).node {
647                 TraitItemKind::Method(ref trait_m_sig, _) => {
648                     if let Some(arg) = trait_m_sig.decl.inputs.get(if trait_number_args > 0 {
649                         trait_number_args - 1
650                     } else {
651                         0
652                     }) {
653                         Some(arg.span)
654                     } else {
655                         trait_item_span
656                     }
657                 }
658                 _ => bug!("{:?} is not a method", impl_m),
659             }
660         } else {
661             trait_item_span
662         };
663         let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
664         let impl_span = match tcx.hir.expect_impl_item(impl_m_node_id).node {
665             ImplItemKind::Method(ref impl_m_sig, _) => {
666                 if let Some(arg) = impl_m_sig.decl.inputs.get(if impl_number_args > 0 {
667                     impl_number_args - 1
668                 } else {
669                     0
670                 }) {
671                     arg.span
672                 } else {
673                     impl_m_span
674                 }
675             }
676             _ => bug!("{:?} is not a method", impl_m),
677         };
678         let mut err = struct_span_err!(tcx.sess,
679                                        impl_span,
680                                        E0050,
681                                        "method `{}` has {} parameter{} but the declaration in \
682                                         trait `{}` has {}",
683                                        trait_m.name,
684                                        impl_number_args,
685                                        if impl_number_args == 1 { "" } else { "s" },
686                                        tcx.item_path_str(trait_m.def_id),
687                                        trait_number_args);
688         if let Some(trait_span) = trait_span {
689             err.span_label(trait_span,
690                            format!("trait requires {}",
691                                     &if trait_number_args != 1 {
692                                         format!("{} parameters", trait_number_args)
693                                     } else {
694                                         format!("{} parameter", trait_number_args)
695                                     }));
696         } else {
697             err.note_trait_signature(trait_m.name.to_string(),
698                                      trait_m.signature(&tcx));
699         }
700         err.span_label(impl_span,
701                        format!("expected {}, found {}",
702                                 &if trait_number_args != 1 {
703                                     format!("{} parameters", trait_number_args)
704                                 } else {
705                                     format!("{} parameter", trait_number_args)
706                                 },
707                                 impl_number_args));
708         err.emit();
709         return Err(ErrorReported);
710     }
711
712     Ok(())
713 }
714
715 fn compare_synthetic_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
716                                         impl_m: &ty::AssociatedItem,
717                                         _impl_m_span: Span, // FIXME necessary?
718                                         trait_m: &ty::AssociatedItem,
719                                         _trait_item_span: Option<Span>) // FIXME necessary?
720                                         -> Result<(), ErrorReported> {
721     // FIXME(chrisvittal) Clean up this function, list of FIXME items:
722     //     1. Better messages for the span lables
723     //     2. Explanation as to what is going on
724     //     3. Correct the function signature for what we actually use
725     // If we get here, we already have the same number of generics, so the zip will
726     // be okay.
727     let mut error_found = false;
728     let impl_m_generics = tcx.generics_of(impl_m.def_id);
729     let trait_m_generics = tcx.generics_of(trait_m.def_id);
730     for (impl_ty, trait_ty) in impl_m_generics.types.iter().zip(trait_m_generics.types.iter()) {
731         if impl_ty.synthetic != trait_ty.synthetic {
732             let impl_node_id = tcx.hir.as_local_node_id(impl_ty.def_id).unwrap();
733             let impl_span = tcx.hir.span(impl_node_id);
734             let trait_node_id = tcx.hir.as_local_node_id(trait_ty.def_id).unwrap();
735             let trait_span = tcx.hir.span(trait_node_id);
736             let mut err = struct_span_err!(tcx.sess,
737                                            impl_span,
738                                            E0643,
739                                            "method `{}` has incompatible signature for trait",
740                                            trait_m.name);
741             err.span_label(trait_span, "annotation in trait");
742             err.span_label(impl_span, "annotation in impl");
743             err.emit();
744             error_found = true;
745         }
746     }
747     if error_found {
748         Err(ErrorReported)
749     } else {
750         Ok(())
751     }
752 }
753
754 pub fn compare_const_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
755                                     impl_c: &ty::AssociatedItem,
756                                     impl_c_span: Span,
757                                     trait_c: &ty::AssociatedItem,
758                                     impl_trait_ref: ty::TraitRef<'tcx>) {
759     debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
760
761     tcx.infer_ctxt().enter(|infcx| {
762         let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
763         let inh = Inherited::new(infcx, impl_c.def_id);
764         let infcx = &inh.infcx;
765
766         // The below is for the most part highly similar to the procedure
767         // for methods above. It is simpler in many respects, especially
768         // because we shouldn't really have to deal with lifetimes or
769         // predicates. In fact some of this should probably be put into
770         // shared functions because of DRY violations...
771         let trait_to_impl_substs = impl_trait_ref.substs;
772
773         // Create a parameter environment that represents the implementation's
774         // method.
775         let impl_c_node_id = tcx.hir.as_local_node_id(impl_c.def_id).unwrap();
776
777         // Compute skolemized form of impl and trait const tys.
778         let impl_ty = tcx.type_of(impl_c.def_id);
779         let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
780         let mut cause = ObligationCause::misc(impl_c_span, impl_c_node_id);
781
782         // There is no "body" here, so just pass dummy id.
783         let impl_ty = inh.normalize_associated_types_in(impl_c_span,
784                                                         impl_c_node_id,
785                                                         param_env,
786                                                         &impl_ty);
787
788         debug!("compare_const_impl: impl_ty={:?}", impl_ty);
789
790         let trait_ty = inh.normalize_associated_types_in(impl_c_span,
791                                                          impl_c_node_id,
792                                                          param_env,
793                                                          &trait_ty);
794
795         debug!("compare_const_impl: trait_ty={:?}", trait_ty);
796
797         let err = infcx.at(&cause, param_env)
798                        .sup(trait_ty, impl_ty)
799                        .map(|ok| inh.register_infer_ok_obligations(ok));
800
801         if let Err(terr) = err {
802             debug!("checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
803                    impl_ty,
804                    trait_ty);
805
806             // Locate the Span containing just the type of the offending impl
807             match tcx.hir.expect_impl_item(impl_c_node_id).node {
808                 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
809                 _ => bug!("{:?} is not a impl const", impl_c),
810             }
811
812             let mut diag = struct_span_err!(tcx.sess,
813                                             cause.span,
814                                             E0326,
815                                             "implemented const `{}` has an incompatible type for \
816                                              trait",
817                                             trait_c.name);
818
819             let trait_c_node_id = tcx.hir.as_local_node_id(trait_c.def_id);
820             let trait_c_span = trait_c_node_id.map(|trait_c_node_id| {
821                 // Add a label to the Span containing just the type of the const
822                 match tcx.hir.expect_trait_item(trait_c_node_id).node {
823                     TraitItemKind::Const(ref ty, _) => ty.span,
824                     _ => bug!("{:?} is not a trait const", trait_c),
825                 }
826             });
827
828             infcx.note_type_err(&mut diag,
829                                 &cause,
830                                 trait_c_span.map(|span| (span, format!("type in trait"))),
831                                 Some(infer::ValuePairs::Types(ExpectedFound {
832                                     expected: trait_ty,
833                                     found: impl_ty,
834                                 })),
835                                 &terr);
836             diag.emit();
837         }
838
839         // Check that all obligations are satisfied by the implementation's
840         // version.
841         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
842             infcx.report_fulfillment_errors(errors, None);
843             return;
844         }
845
846         let fcx = FnCtxt::new(&inh, param_env, impl_c_node_id);
847         fcx.regionck_item(impl_c_node_id, impl_c_span, &[]);
848     });
849 }