]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/compare_method.rs
9ed5528e86783905c6e2c46e477c4c1aa6235778
[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 a parameter environment that represents the implementation's
169     // method.
170     let impl_param_env = ty::ParameterEnvironment::for_item(tcx, impl_m_node_id);
171
172     // Create mapping from impl to skolemized.
173     let impl_to_skol_substs = &impl_param_env.free_substs;
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.subst(tcx,
179                                                                           impl_to_skol_substs));
180     debug!("compare_impl_method: trait_to_skol_substs={:?}",
181            trait_to_skol_substs);
182
183     let impl_m_generics = tcx.generics_of(impl_m.def_id);
184     let trait_m_generics = tcx.generics_of(trait_m.def_id);
185     let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
186     let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
187
188     // Check region bounds.
189     check_region_bounds_on_impl_method(tcx,
190                                        impl_m_span,
191                                        impl_m,
192                                        &trait_m_generics,
193                                        &impl_m_generics,
194                                        trait_to_skol_substs,
195                                        impl_to_skol_substs)?;
196
197     // Create obligations for each predicate declared by the impl
198     // definition in the context of the trait's parameter
199     // environment. We can't just use `impl_env.caller_bounds`,
200     // however, because we want to replace all late-bound regions with
201     // region variables.
202     let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
203     let mut hybrid_preds = impl_predicates.instantiate(tcx, impl_to_skol_substs);
204
205     debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
206
207     // This is the only tricky bit of the new way we check implementation methods
208     // We need to build a set of predicates where only the method-level bounds
209     // are from the trait and we assume all other bounds from the implementation
210     // to be previously satisfied.
211     //
212     // We then register the obligations from the impl_m and check to see
213     // if all constraints hold.
214     hybrid_preds.predicates
215                 .extend(trait_m_predicates.instantiate_own(tcx, trait_to_skol_substs).predicates);
216
217     // Construct trait parameter environment and then shift it into the skolemized viewpoint.
218     // The key step here is to update the caller_bounds's predicates to be
219     // the new hybrid bounds we computed.
220     let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_node_id);
221     let trait_param_env = impl_param_env.with_caller_bounds(
222         tcx.intern_predicates(&hybrid_preds.predicates));
223     let trait_param_env = traits::normalize_param_env_or_error(tcx,
224                                                                impl_m.def_id,
225                                                                trait_param_env,
226                                                                normalize_cause.clone());
227
228     tcx.infer_ctxt(trait_param_env, Reveal::UserFacing).enter(|infcx| {
229         let inh = Inherited::new(infcx);
230         let infcx = &inh.infcx;
231
232         debug!("compare_impl_method: caller_bounds={:?}",
233                infcx.parameter_environment.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, normalize_cause.clone(), &predicate);
244
245             inh.register_predicates(obligations);
246             inh.register_predicate(traits::Obligation::new(cause.clone(), 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 m_sig = |method: &ty::AssociatedItem| {
266             match tcx.type_of(method.def_id).sty {
267                 ty::TyFnDef(_, _, f) => f,
268                 _ => bug!()
269             }
270         };
271
272         let (impl_sig, _) =
273             infcx.replace_late_bound_regions_with_fresh_var(impl_m_span,
274                                                             infer::HigherRankedType,
275                                                             &m_sig(impl_m));
276         let impl_sig =
277             impl_sig.subst(tcx, impl_to_skol_substs);
278         let impl_sig =
279             inh.normalize_associated_types_in(impl_m_span,
280                                               impl_m_node_id,
281                                               &impl_sig);
282         let impl_fty = tcx.mk_fn_ptr(ty::Binder(impl_sig));
283         debug!("compare_impl_method: impl_fty={:?}", impl_fty);
284
285         let trait_sig = tcx.liberate_late_bound_regions(
286             infcx.parameter_environment.free_id_outlive,
287             &m_sig(trait_m));
288         let trait_sig =
289             trait_sig.subst(tcx, trait_to_skol_substs);
290         let trait_sig =
291             inh.normalize_associated_types_in(impl_m_span,
292                                               impl_m_node_id,
293                                               &trait_sig);
294         let trait_fty = tcx.mk_fn_ptr(ty::Binder(trait_sig));
295
296         debug!("compare_impl_method: trait_fty={:?}", trait_fty);
297
298         let sub_result = infcx.sub_types(false, &cause, impl_fty, trait_fty)
299                               .map(|InferOk { obligations, .. }| {
300                                   inh.register_predicates(obligations);
301                               });
302
303         if let Err(terr) = sub_result {
304             debug!("sub_types failed: impl ty {:?}, trait ty {:?}",
305                    impl_fty,
306                    trait_fty);
307
308             let (impl_err_span, trait_err_span) = extract_spans_for_error_reporting(&infcx,
309                                                                                     &terr,
310                                                                                     &cause,
311                                                                                     impl_m,
312                                                                                     impl_sig,
313                                                                                     trait_m,
314                                                                                     trait_sig);
315
316             let cause = ObligationCause {
317                 span: impl_err_span,
318                 ..cause.clone()
319             };
320
321             let mut diag = struct_span_err!(tcx.sess,
322                                             cause.span,
323                                             E0053,
324                                             "method `{}` has an incompatible type for trait",
325                                             trait_m.name);
326
327             infcx.note_type_err(&mut diag,
328                                 &cause,
329                                 trait_err_span.map(|sp| (sp, format!("type in trait"))),
330                                 Some(infer::ValuePairs::Types(ExpectedFound {
331                                     expected: trait_fty,
332                                     found: impl_fty,
333                                 })),
334                                 &terr);
335             diag.emit();
336             return Err(ErrorReported);
337         }
338
339         // Check that all obligations are satisfied by the implementation's
340         // version.
341         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
342             infcx.report_fulfillment_errors(errors);
343             return Err(ErrorReported);
344         }
345
346         // Finally, resolve all regions. This catches wily misuses of
347         // lifetime parameters.
348         if old_broken_mode {
349             // FIXME(#18937) -- this is how the code used to
350             // work. This is buggy because the fulfillment cx creates
351             // region obligations that get overlooked.  The right
352             // thing to do is the code below. But we keep this old
353             // pass around temporarily.
354             let region_maps = RegionMaps::new();
355             let mut free_regions = FreeRegionMap::new();
356             free_regions.relate_free_regions_from_predicates(
357                 &infcx.parameter_environment.caller_bounds);
358             infcx.resolve_regions_and_report_errors(impl_m.def_id, &region_maps, &free_regions);
359         } else {
360             let fcx = FnCtxt::new(&inh, impl_m_node_id);
361             fcx.regionck_item(impl_m_node_id, impl_m_span, &[]);
362         }
363
364         Ok(())
365     })
366 }
367
368 fn check_region_bounds_on_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
369                                                 span: Span,
370                                                 impl_m: &ty::AssociatedItem,
371                                                 trait_generics: &ty::Generics,
372                                                 impl_generics: &ty::Generics,
373                                                 trait_to_skol_substs: &Substs<'tcx>,
374                                                 impl_to_skol_substs: &Substs<'tcx>)
375                                                 -> Result<(), ErrorReported> {
376     let trait_params = &trait_generics.regions[..];
377     let impl_params = &impl_generics.regions[..];
378
379     debug!("check_region_bounds_on_impl_method: \
380             trait_generics={:?} \
381             impl_generics={:?} \
382             trait_to_skol_substs={:?} \
383             impl_to_skol_substs={:?}",
384            trait_generics,
385            impl_generics,
386            trait_to_skol_substs,
387            impl_to_skol_substs);
388
389     // Must have same number of early-bound lifetime parameters.
390     // Unfortunately, if the user screws up the bounds, then this
391     // will change classification between early and late.  E.g.,
392     // if in trait we have `<'a,'b:'a>`, and in impl we just have
393     // `<'a,'b>`, then we have 2 early-bound lifetime parameters
394     // in trait but 0 in the impl. But if we report "expected 2
395     // but found 0" it's confusing, because it looks like there
396     // are zero. Since I don't quite know how to phrase things at
397     // the moment, give a kind of vague error message.
398     if trait_params.len() != impl_params.len() {
399         struct_span_err!(tcx.sess,
400                          span,
401                          E0195,
402                          "lifetime parameters or bounds on method `{}` do not match the \
403                           trait declaration",
404                          impl_m.name)
405             .span_label(span, &format!("lifetimes do not match trait"))
406             .emit();
407         return Err(ErrorReported);
408     }
409
410     return Ok(());
411 }
412
413 fn extract_spans_for_error_reporting<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
414                                                      terr: &TypeError,
415                                                      cause: &ObligationCause<'tcx>,
416                                                      impl_m: &ty::AssociatedItem,
417                                                      impl_sig: ty::FnSig<'tcx>,
418                                                      trait_m: &ty::AssociatedItem,
419                                                      trait_sig: ty::FnSig<'tcx>)
420                                                      -> (Span, Option<Span>) {
421     let tcx = infcx.tcx;
422     let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
423     let (impl_m_output, impl_m_iter) = match tcx.hir.expect_impl_item(impl_m_node_id).node {
424         ImplItemKind::Method(ref impl_m_sig, _) => {
425             (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter())
426         }
427         _ => bug!("{:?} is not a method", impl_m),
428     };
429
430     match *terr {
431         TypeError::Mutability => {
432             if let Some(trait_m_node_id) = tcx.hir.as_local_node_id(trait_m.def_id) {
433                 let trait_m_iter = match tcx.hir.expect_trait_item(trait_m_node_id).node {
434                     TraitItemKind::Method(ref trait_m_sig, _) => {
435                         trait_m_sig.decl.inputs.iter()
436                     }
437                     _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
438                 };
439
440                 impl_m_iter.zip(trait_m_iter).find(|&(ref impl_arg, ref trait_arg)| {
441                     match (&impl_arg.node, &trait_arg.node) {
442                         (&hir::TyRptr(_, ref impl_mt), &hir::TyRptr(_, ref trait_mt)) |
443                         (&hir::TyPtr(ref impl_mt), &hir::TyPtr(ref trait_mt)) => {
444                             impl_mt.mutbl != trait_mt.mutbl
445                         }
446                         _ => false,
447                     }
448                 }).map(|(ref impl_arg, ref trait_arg)| {
449                     (impl_arg.span, Some(trait_arg.span))
450                 })
451                 .unwrap_or_else(|| (cause.span, tcx.hir.span_if_local(trait_m.def_id)))
452             } else {
453                 (cause.span, tcx.hir.span_if_local(trait_m.def_id))
454             }
455         }
456         TypeError::Sorts(ExpectedFound { .. }) => {
457             if let Some(trait_m_node_id) = tcx.hir.as_local_node_id(trait_m.def_id) {
458                 let (trait_m_output, trait_m_iter) =
459                     match tcx.hir.expect_trait_item(trait_m_node_id).node {
460                         TraitItemKind::Method(ref trait_m_sig, _) => {
461                             (&trait_m_sig.decl.output, trait_m_sig.decl.inputs.iter())
462                         }
463                         _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
464                     };
465
466                 let impl_iter = impl_sig.inputs().iter();
467                 let trait_iter = trait_sig.inputs().iter();
468                 impl_iter.zip(trait_iter)
469                          .zip(impl_m_iter)
470                          .zip(trait_m_iter)
471                          .filter_map(|(((impl_arg_ty, trait_arg_ty), impl_arg), trait_arg)| {
472                              match infcx.sub_types(true, &cause, trait_arg_ty, impl_arg_ty) {
473                                  Ok(_) => None,
474                                  Err(_) => Some((impl_arg.span, Some(trait_arg.span))),
475                              }
476                          })
477                          .next()
478                          .unwrap_or_else(|| {
479                              if infcx.sub_types(false, &cause, impl_sig.output(),
480                                                 trait_sig.output())
481                                      .is_err() {
482                                          (impl_m_output.span(), Some(trait_m_output.span()))
483                                      } else {
484                                          (cause.span, tcx.hir.span_if_local(trait_m.def_id))
485                                      }
486                          })
487             } else {
488                 (cause.span, tcx.hir.span_if_local(trait_m.def_id))
489             }
490         }
491         _ => (cause.span, tcx.hir.span_if_local(trait_m.def_id)),
492     }
493 }
494
495 fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
496                                impl_m: &ty::AssociatedItem,
497                                impl_m_span: Span,
498                                trait_m: &ty::AssociatedItem,
499                                impl_trait_ref: ty::TraitRef<'tcx>)
500                                -> Result<(), ErrorReported>
501 {
502     // Try to give more informative error messages about self typing
503     // mismatches.  Note that any mismatch will also be detected
504     // below, where we construct a canonical function type that
505     // includes the self parameter as a normal parameter.  It's just
506     // that the error messages you get out of this code are a bit more
507     // inscrutable, particularly for cases where one method has no
508     // self.
509
510     let self_string = |method: &ty::AssociatedItem| {
511         let untransformed_self_ty = match method.container {
512             ty::ImplContainer(_) => impl_trait_ref.self_ty(),
513             ty::TraitContainer(_) => tcx.mk_self_type()
514         };
515         let method_ty = tcx.type_of(method.def_id);
516         let self_arg_ty = *method_ty.fn_sig().input(0).skip_binder();
517         match ExplicitSelf::determine(untransformed_self_ty, self_arg_ty) {
518             ExplicitSelf::ByValue => "self".to_string(),
519             ExplicitSelf::ByReference(_, hir::MutImmutable) => "&self".to_string(),
520             ExplicitSelf::ByReference(_, hir::MutMutable) => "&mut self".to_string(),
521             _ => format!("self: {}", self_arg_ty)
522         }
523     };
524
525     match (trait_m.method_has_self_argument, impl_m.method_has_self_argument) {
526         (false, false) | (true, true) => {}
527
528         (false, true) => {
529             let self_descr = self_string(impl_m);
530             let mut err = struct_span_err!(tcx.sess,
531                                            impl_m_span,
532                                            E0185,
533                                            "method `{}` has a `{}` declaration in the impl, but \
534                                             not in the trait",
535                                            trait_m.name,
536                                            self_descr);
537             err.span_label(impl_m_span, &format!("`{}` used in impl", self_descr));
538             if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
539                 err.span_label(span, &format!("trait declared without `{}`", self_descr));
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,
555                            &format!("expected `{}` in impl", self_descr));
556             if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
557                 err.span_label(span, &format!("`{}` used in trait", self_descr));
558             }
559             err.emit();
560             return Err(ErrorReported);
561         }
562     }
563
564     Ok(())
565 }
566
567 fn compare_number_of_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
568                                         impl_m: &ty::AssociatedItem,
569                                         impl_m_span: Span,
570                                         trait_m: &ty::AssociatedItem,
571                                         trait_item_span: Option<Span>)
572                                         -> Result<(), ErrorReported> {
573     let impl_m_generics = tcx.generics_of(impl_m.def_id);
574     let trait_m_generics = tcx.generics_of(trait_m.def_id);
575     let num_impl_m_type_params = impl_m_generics.types.len();
576     let num_trait_m_type_params = trait_m_generics.types.len();
577     if num_impl_m_type_params != num_trait_m_type_params {
578         let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
579         let span = match tcx.hir.expect_impl_item(impl_m_node_id).node {
580             ImplItemKind::Method(ref impl_m_sig, _) => {
581                 if impl_m_sig.generics.is_parameterized() {
582                     impl_m_sig.generics.span
583                 } else {
584                     impl_m_span
585                 }
586             }
587             _ => bug!("{:?} is not a method", impl_m),
588         };
589
590         let mut err = struct_span_err!(tcx.sess,
591                                        span,
592                                        E0049,
593                                        "method `{}` has {} type parameter{} but its trait \
594                                         declaration has {} type parameter{}",
595                                        trait_m.name,
596                                        num_impl_m_type_params,
597                                        if num_impl_m_type_params == 1 { "" } else { "s" },
598                                        num_trait_m_type_params,
599                                        if num_trait_m_type_params == 1 {
600                                            ""
601                                        } else {
602                                            "s"
603                                        });
604
605         let mut suffix = None;
606
607         if let Some(span) = trait_item_span {
608             err.span_label(span,
609                            &format!("expected {}",
610                                     &if num_trait_m_type_params != 1 {
611                                         format!("{} type parameters", num_trait_m_type_params)
612                                     } else {
613                                         format!("{} type parameter", num_trait_m_type_params)
614                                     }));
615         } else {
616             suffix = Some(format!(", expected {}", num_trait_m_type_params));
617         }
618
619         err.span_label(span,
620                        &format!("found {}{}",
621                                 &if num_impl_m_type_params != 1 {
622                                     format!("{} type parameters", num_impl_m_type_params)
623                                 } else {
624                                     format!("1 type parameter")
625                                 },
626                                 suffix.as_ref().map(|s| &s[..]).unwrap_or("")));
627
628         err.emit();
629
630         return Err(ErrorReported);
631     }
632
633     Ok(())
634 }
635
636 fn compare_number_of_method_arguments<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
637                                                 impl_m: &ty::AssociatedItem,
638                                                 impl_m_span: Span,
639                                                 trait_m: &ty::AssociatedItem,
640                                                 trait_item_span: Option<Span>)
641                                                 -> Result<(), ErrorReported> {
642     let m_fty = |method: &ty::AssociatedItem| {
643         match tcx.type_of(method.def_id).sty {
644             ty::TyFnDef(_, _, f) => f,
645             _ => bug!()
646         }
647     };
648     let impl_m_fty = m_fty(impl_m);
649     let trait_m_fty = m_fty(trait_m);
650     let trait_number_args = trait_m_fty.inputs().skip_binder().len();
651     let impl_number_args = impl_m_fty.inputs().skip_binder().len();
652     if trait_number_args != impl_number_args {
653         let trait_m_node_id = tcx.hir.as_local_node_id(trait_m.def_id);
654         let trait_span = if let Some(trait_id) = trait_m_node_id {
655             match tcx.hir.expect_trait_item(trait_id).node {
656                 TraitItemKind::Method(ref trait_m_sig, _) => {
657                     if let Some(arg) = trait_m_sig.decl.inputs.get(if trait_number_args > 0 {
658                         trait_number_args - 1
659                     } else {
660                         0
661                     }) {
662                         Some(arg.span)
663                     } else {
664                         trait_item_span
665                     }
666                 }
667                 _ => bug!("{:?} is not a method", impl_m),
668             }
669         } else {
670             trait_item_span
671         };
672         let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
673         let impl_span = match tcx.hir.expect_impl_item(impl_m_node_id).node {
674             ImplItemKind::Method(ref impl_m_sig, _) => {
675                 if let Some(arg) = impl_m_sig.decl.inputs.get(if impl_number_args > 0 {
676                     impl_number_args - 1
677                 } else {
678                     0
679                 }) {
680                     arg.span
681                 } else {
682                     impl_m_span
683                 }
684             }
685             _ => bug!("{:?} is not a method", impl_m),
686         };
687         let mut err = struct_span_err!(tcx.sess,
688                                        impl_span,
689                                        E0050,
690                                        "method `{}` has {} parameter{} but the declaration in \
691                                         trait `{}` has {}",
692                                        trait_m.name,
693                                        impl_number_args,
694                                        if impl_number_args == 1 { "" } else { "s" },
695                                        tcx.item_path_str(trait_m.def_id),
696                                        trait_number_args);
697         if let Some(trait_span) = trait_span {
698             err.span_label(trait_span,
699                            &format!("trait requires {}",
700                                     &if trait_number_args != 1 {
701                                         format!("{} parameters", trait_number_args)
702                                     } else {
703                                         format!("{} parameter", trait_number_args)
704                                     }));
705         }
706         err.span_label(impl_span,
707                        &format!("expected {}, found {}",
708                                 &if trait_number_args != 1 {
709                                     format!("{} parameters", trait_number_args)
710                                 } else {
711                                     format!("{} parameter", trait_number_args)
712                                 },
713                                 impl_number_args));
714         err.emit();
715         return Err(ErrorReported);
716     }
717
718     Ok(())
719 }
720
721 pub fn compare_const_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
722                                     impl_c: &ty::AssociatedItem,
723                                     impl_c_span: Span,
724                                     trait_c: &ty::AssociatedItem,
725                                     impl_trait_ref: ty::TraitRef<'tcx>) {
726     debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
727
728     tcx.infer_ctxt((), Reveal::UserFacing).enter(|infcx| {
729         let inh = Inherited::new(infcx);
730         let infcx = &inh.infcx;
731
732         // The below is for the most part highly similar to the procedure
733         // for methods above. It is simpler in many respects, especially
734         // because we shouldn't really have to deal with lifetimes or
735         // predicates. In fact some of this should probably be put into
736         // shared functions because of DRY violations...
737         let trait_to_impl_substs = impl_trait_ref.substs;
738
739         // Create a parameter environment that represents the implementation's
740         // method.
741         let impl_c_node_id = tcx.hir.as_local_node_id(impl_c.def_id).unwrap();
742         let impl_param_env = ty::ParameterEnvironment::for_item(tcx, impl_c_node_id);
743
744         // Create mapping from impl to skolemized.
745         let impl_to_skol_substs = &impl_param_env.free_substs;
746
747         // Create mapping from trait to skolemized.
748         let trait_to_skol_substs = impl_to_skol_substs.rebase_onto(tcx,
749                                                                    impl_c.container.id(),
750                                                                    trait_to_impl_substs.subst(tcx,
751                                                                               impl_to_skol_substs));
752         debug!("compare_const_impl: trait_to_skol_substs={:?}",
753                trait_to_skol_substs);
754
755         // Compute skolemized form of impl and trait const tys.
756         let impl_ty = tcx.type_of(impl_c.def_id).subst(tcx, impl_to_skol_substs);
757         let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_skol_substs);
758         let mut cause = ObligationCause::misc(impl_c_span, impl_c_node_id);
759
760         // There is no "body" here, so just pass dummy id.
761         let impl_ty = inh.normalize_associated_types_in(impl_c_span,
762                                                         impl_c_node_id,
763                                                         &impl_ty);
764
765         debug!("compare_const_impl: impl_ty={:?}", impl_ty);
766
767         let trait_ty = inh.normalize_associated_types_in(impl_c_span,
768                                                          impl_c_node_id,
769                                                          &trait_ty);
770
771         debug!("compare_const_impl: trait_ty={:?}", trait_ty);
772
773         let err = infcx.sub_types(false, &cause, impl_ty, trait_ty)
774             .map(|ok| inh.register_infer_ok_obligations(ok));
775
776         if let Err(terr) = err {
777             debug!("checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
778                    impl_ty,
779                    trait_ty);
780
781             // Locate the Span containing just the type of the offending impl
782             match tcx.hir.expect_impl_item(impl_c_node_id).node {
783                 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
784                 _ => bug!("{:?} is not a impl const", impl_c),
785             }
786
787             let mut diag = struct_span_err!(tcx.sess,
788                                             cause.span,
789                                             E0326,
790                                             "implemented const `{}` has an incompatible type for \
791                                              trait",
792                                             trait_c.name);
793
794             let trait_c_node_id = tcx.hir.as_local_node_id(trait_c.def_id);
795             let trait_c_span = trait_c_node_id.map(|trait_c_node_id| {
796                 // Add a label to the Span containing just the type of the const
797                 match tcx.hir.expect_trait_item(trait_c_node_id).node {
798                     TraitItemKind::Const(ref ty, _) => ty.span,
799                     _ => bug!("{:?} is not a trait const", trait_c),
800                 }
801             });
802
803             infcx.note_type_err(&mut diag,
804                                 &cause,
805                                 trait_c_span.map(|span| (span, format!("type in trait"))),
806                                 Some(infer::ValuePairs::Types(ExpectedFound {
807                                     expected: trait_ty,
808                                     found: impl_ty,
809                                 })),
810                                 &terr);
811             diag.emit();
812         }
813
814         // FIXME(#41323) Check the obligations in the fulfillment context.
815     });
816 }