]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/compare_method.rs
Auto merge of #41433 - estebank:constructor, r=michaelwoerister
[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::ty::{self, TyCtxt};
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::ast;
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 /// - impl_m_body_id: id of the method body
34 /// - trait_m: the method in the trait
35 /// - impl_trait_ref: the TraitRef corresponding to the trait implementation
36
37 pub fn compare_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
38                                      impl_m: &ty::AssociatedItem,
39                                      impl_m_span: Span,
40                                      impl_m_body_id: ast::NodeId,
41                                      trait_m: &ty::AssociatedItem,
42                                      impl_trait_ref: ty::TraitRef<'tcx>,
43                                      trait_item_span: Option<Span>,
44                                      old_broken_mode: bool) {
45     debug!("compare_impl_method(impl_trait_ref={:?})",
46            impl_trait_ref);
47
48     if let Err(ErrorReported) = compare_self_type(tcx,
49                                                   impl_m,
50                                                   impl_m_span,
51                                                   trait_m,
52                                                   impl_trait_ref) {
53         return;
54     }
55
56     if let Err(ErrorReported) = compare_number_of_generics(tcx,
57                                                            impl_m,
58                                                            impl_m_span,
59                                                            trait_m,
60                                                            trait_item_span) {
61         return;
62     }
63
64     if let Err(ErrorReported) = compare_number_of_method_arguments(tcx,
65                                                                    impl_m,
66                                                                    impl_m_span,
67                                                                    trait_m,
68                                                                    trait_item_span) {
69         return;
70     }
71
72     if let Err(ErrorReported) = compare_predicate_entailment(tcx,
73                                                              impl_m,
74                                                              impl_m_span,
75                                                              impl_m_body_id,
76                                                              trait_m,
77                                                              impl_trait_ref,
78                                                              old_broken_mode) {
79         return;
80     }
81 }
82
83 fn compare_predicate_entailment<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
84                                           impl_m: &ty::AssociatedItem,
85                                           impl_m_span: Span,
86                                           impl_m_body_id: ast::NodeId,
87                                           trait_m: &ty::AssociatedItem,
88                                           impl_trait_ref: ty::TraitRef<'tcx>,
89                                           old_broken_mode: bool)
90                                           -> Result<(), ErrorReported> {
91     let trait_to_impl_substs = impl_trait_ref.substs;
92
93     let cause = ObligationCause {
94         span: impl_m_span,
95         body_id: impl_m_body_id,
96         code: ObligationCauseCode::CompareImplMethodObligation {
97             item_name: impl_m.name,
98             impl_item_def_id: impl_m.def_id,
99             trait_item_def_id: trait_m.def_id,
100             lint_id: if !old_broken_mode { Some(impl_m_body_id) } else { None },
101         },
102     };
103
104     // This code is best explained by example. Consider a trait:
105     //
106     //     trait Trait<'t,T> {
107     //          fn method<'a,M>(t: &'t T, m: &'a M) -> Self;
108     //     }
109     //
110     // And an impl:
111     //
112     //     impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
113     //          fn method<'b,N>(t: &'j &'i U, m: &'b N) -> Foo;
114     //     }
115     //
116     // We wish to decide if those two method types are compatible.
117     //
118     // We start out with trait_to_impl_substs, that maps the trait
119     // type parameters to impl type parameters. This is taken from the
120     // impl trait reference:
121     //
122     //     trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
123     //
124     // We create a mapping `dummy_substs` that maps from the impl type
125     // parameters to fresh types and regions. For type parameters,
126     // this is the identity transform, but we could as well use any
127     // skolemized types. For regions, we convert from bound to free
128     // regions (Note: but only early-bound regions, i.e., those
129     // declared on the impl or used in type parameter bounds).
130     //
131     //     impl_to_skol_substs = {'i => 'i0, U => U0, N => N0 }
132     //
133     // Now we can apply skol_substs to the type of the impl method
134     // to yield a new function type in terms of our fresh, skolemized
135     // types:
136     //
137     //     <'b> fn(t: &'i0 U0, m: &'b) -> Foo
138     //
139     // We now want to extract and substitute the type of the *trait*
140     // method and compare it. To do so, we must create a compound
141     // substitution by combining trait_to_impl_substs and
142     // impl_to_skol_substs, and also adding a mapping for the method
143     // type parameters. We extend the mapping to also include
144     // the method parameters.
145     //
146     //     trait_to_skol_substs = { T => &'i0 U0, Self => Foo, M => N0 }
147     //
148     // Applying this to the trait method type yields:
149     //
150     //     <'a> fn(t: &'i0 U0, m: &'a) -> Foo
151     //
152     // This type is also the same but the name of the bound region ('a
153     // vs 'b).  However, the normal subtyping rules on fn types handle
154     // this kind of equivalency just fine.
155     //
156     // We now use these substitutions to ensure that all declared bounds are
157     // satisfied by the implementation's method.
158     //
159     // We do this by creating a parameter environment which contains a
160     // substitution corresponding to impl_to_skol_substs. We then build
161     // trait_to_skol_substs and use it to convert the predicates contained
162     // in the trait_m.generics to the skolemized form.
163     //
164     // Finally we register each of these predicates as an obligation in
165     // a fresh FulfillmentCtxt, and invoke select_all_or_error.
166
167     // Create a parameter environment that represents the implementation's
168     // method.
169     let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
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_body_id);
221     let trait_param_env = impl_param_env.with_caller_bounds(hybrid_preds.predicates);
222     let trait_param_env = traits::normalize_param_env_or_error(tcx,
223                                                                trait_param_env,
224                                                                normalize_cause.clone());
225
226     tcx.infer_ctxt(trait_param_env, Reveal::UserFacing).enter(|infcx| {
227         let inh = Inherited::new(infcx);
228         let infcx = &inh.infcx;
229
230         debug!("compare_impl_method: caller_bounds={:?}",
231                infcx.parameter_environment.caller_bounds);
232
233         let mut selcx = traits::SelectionContext::new(&infcx);
234
235         let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_skol_substs);
236         let (impl_m_own_bounds, _) = infcx.replace_late_bound_regions_with_fresh_var(impl_m_span,
237                                                        infer::HigherRankedType,
238                                                        &ty::Binder(impl_m_own_bounds.predicates));
239         for predicate in impl_m_own_bounds {
240             let traits::Normalized { value: predicate, obligations } =
241                 traits::normalize(&mut selcx, normalize_cause.clone(), &predicate);
242
243             inh.register_predicates(obligations);
244             inh.register_predicate(traits::Obligation::new(cause.clone(), predicate));
245         }
246
247         // We now need to check that the signature of the impl method is
248         // compatible with that of the trait method. We do this by
249         // checking that `impl_fty <: trait_fty`.
250         //
251         // FIXME. Unfortunately, this doesn't quite work right now because
252         // associated type normalization is not integrated into subtype
253         // checks. For the comparison to be valid, we need to
254         // normalize the associated types in the impl/trait methods
255         // first. However, because function types bind regions, just
256         // calling `normalize_associated_types_in` would have no effect on
257         // any associated types appearing in the fn arguments or return
258         // type.
259
260         // Compute skolemized form of impl and trait method tys.
261         let tcx = infcx.tcx;
262
263         let m_sig = |method: &ty::AssociatedItem| {
264             match tcx.type_of(method.def_id).sty {
265                 ty::TyFnDef(_, _, f) => f,
266                 _ => bug!()
267             }
268         };
269
270         let (impl_sig, _) =
271             infcx.replace_late_bound_regions_with_fresh_var(impl_m_span,
272                                                             infer::HigherRankedType,
273                                                             &m_sig(impl_m));
274         let impl_sig =
275             impl_sig.subst(tcx, impl_to_skol_substs);
276         let impl_sig =
277             inh.normalize_associated_types_in(impl_m_span,
278                                               impl_m_body_id,
279                                               &impl_sig);
280         let impl_fty = tcx.mk_fn_ptr(ty::Binder(impl_sig));
281         debug!("compare_impl_method: impl_fty={:?}", impl_fty);
282
283         let trait_sig = tcx.liberate_late_bound_regions(
284             infcx.parameter_environment.free_id_outlive,
285             &m_sig(trait_m));
286         let trait_sig =
287             trait_sig.subst(tcx, trait_to_skol_substs);
288         let trait_sig =
289             inh.normalize_associated_types_in(impl_m_span,
290                                               impl_m_body_id,
291                                               &trait_sig);
292         let trait_fty = tcx.mk_fn_ptr(ty::Binder(trait_sig));
293
294         debug!("compare_impl_method: trait_fty={:?}", trait_fty);
295
296         let sub_result = infcx.sub_types(false, &cause, impl_fty, trait_fty)
297                               .map(|InferOk { obligations, .. }| {
298                                   inh.register_predicates(obligations);
299                               });
300
301         if let Err(terr) = sub_result {
302             debug!("sub_types failed: impl ty {:?}, trait ty {:?}",
303                    impl_fty,
304                    trait_fty);
305
306             let (impl_err_span, trait_err_span) = extract_spans_for_error_reporting(&infcx,
307                                                                                     &terr,
308                                                                                     &cause,
309                                                                                     impl_m,
310                                                                                     impl_sig,
311                                                                                     trait_m,
312                                                                                     trait_sig);
313
314             let cause = ObligationCause {
315                 span: impl_err_span,
316                 ..cause.clone()
317             };
318
319             let mut diag = struct_span_err!(tcx.sess,
320                                             cause.span,
321                                             E0053,
322                                             "method `{}` has an incompatible type for trait",
323                                             trait_m.name);
324
325             infcx.note_type_err(&mut diag,
326                                 &cause,
327                                 trait_err_span.map(|sp| (sp, format!("type in trait"))),
328                                 Some(infer::ValuePairs::Types(ExpectedFound {
329                                     expected: trait_fty,
330                                     found: impl_fty,
331                                 })),
332                                 &terr);
333             diag.emit();
334             return Err(ErrorReported);
335         }
336
337         // Check that all obligations are satisfied by the implementation's
338         // version.
339         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
340             infcx.report_fulfillment_errors(errors);
341             return Err(ErrorReported);
342         }
343
344         // Finally, resolve all regions. This catches wily misuses of
345         // lifetime parameters.
346         if old_broken_mode {
347             // FIXME(#18937) -- this is how the code used to
348             // work. This is buggy because the fulfillment cx creates
349             // region obligations that get overlooked.  The right
350             // thing to do is the code below. But we keep this old
351             // pass around temporarily.
352             let mut free_regions = FreeRegionMap::new();
353             free_regions.relate_free_regions_from_predicates(
354                 &infcx.parameter_environment.caller_bounds);
355             infcx.resolve_regions_and_report_errors(&free_regions, impl_m_body_id);
356         } else {
357             let fcx = FnCtxt::new(&inh, impl_m_body_id);
358             fcx.regionck_item(impl_m_body_id, impl_m_span, &[]);
359         }
360
361         Ok(())
362     })
363 }
364
365 fn check_region_bounds_on_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
366                                                 span: Span,
367                                                 impl_m: &ty::AssociatedItem,
368                                                 trait_generics: &ty::Generics,
369                                                 impl_generics: &ty::Generics,
370                                                 trait_to_skol_substs: &Substs<'tcx>,
371                                                 impl_to_skol_substs: &Substs<'tcx>)
372                                                 -> Result<(), ErrorReported> {
373     let trait_params = &trait_generics.regions[..];
374     let impl_params = &impl_generics.regions[..];
375
376     debug!("check_region_bounds_on_impl_method: \
377             trait_generics={:?} \
378             impl_generics={:?} \
379             trait_to_skol_substs={:?} \
380             impl_to_skol_substs={:?}",
381            trait_generics,
382            impl_generics,
383            trait_to_skol_substs,
384            impl_to_skol_substs);
385
386     // Must have same number of early-bound lifetime parameters.
387     // Unfortunately, if the user screws up the bounds, then this
388     // will change classification between early and late.  E.g.,
389     // if in trait we have `<'a,'b:'a>`, and in impl we just have
390     // `<'a,'b>`, then we have 2 early-bound lifetime parameters
391     // in trait but 0 in the impl. But if we report "expected 2
392     // but found 0" it's confusing, because it looks like there
393     // are zero. Since I don't quite know how to phrase things at
394     // the moment, give a kind of vague error message.
395     if trait_params.len() != impl_params.len() {
396         struct_span_err!(tcx.sess,
397                          span,
398                          E0195,
399                          "lifetime parameters or bounds on method `{}` do not match the \
400                           trait declaration",
401                          impl_m.name)
402             .span_label(span, &format!("lifetimes do not match trait"))
403             .emit();
404         return Err(ErrorReported);
405     }
406
407     return Ok(());
408 }
409
410 fn extract_spans_for_error_reporting<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
411                                                      terr: &TypeError,
412                                                      cause: &ObligationCause<'tcx>,
413                                                      impl_m: &ty::AssociatedItem,
414                                                      impl_sig: ty::FnSig<'tcx>,
415                                                      trait_m: &ty::AssociatedItem,
416                                                      trait_sig: ty::FnSig<'tcx>)
417                                                      -> (Span, Option<Span>) {
418     let tcx = infcx.tcx;
419     let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
420     let (impl_m_output, impl_m_iter) = match tcx.hir.expect_impl_item(impl_m_node_id).node {
421         ImplItemKind::Method(ref impl_m_sig, _) => {
422             (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter())
423         }
424         _ => bug!("{:?} is not a method", impl_m),
425     };
426
427     match *terr {
428         TypeError::Mutability => {
429             if let Some(trait_m_node_id) = tcx.hir.as_local_node_id(trait_m.def_id) {
430                 let trait_m_iter = match tcx.hir.expect_trait_item(trait_m_node_id).node {
431                     TraitItemKind::Method(ref trait_m_sig, _) => {
432                         trait_m_sig.decl.inputs.iter()
433                     }
434                     _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
435                 };
436
437                 impl_m_iter.zip(trait_m_iter).find(|&(ref impl_arg, ref trait_arg)| {
438                     match (&impl_arg.node, &trait_arg.node) {
439                         (&hir::TyRptr(_, ref impl_mt), &hir::TyRptr(_, ref trait_mt)) |
440                         (&hir::TyPtr(ref impl_mt), &hir::TyPtr(ref trait_mt)) => {
441                             impl_mt.mutbl != trait_mt.mutbl
442                         }
443                         _ => false,
444                     }
445                 }).map(|(ref impl_arg, ref trait_arg)| {
446                     (impl_arg.span, Some(trait_arg.span))
447                 })
448                 .unwrap_or_else(|| (cause.span, tcx.hir.span_if_local(trait_m.def_id)))
449             } else {
450                 (cause.span, tcx.hir.span_if_local(trait_m.def_id))
451             }
452         }
453         TypeError::Sorts(ExpectedFound { .. }) => {
454             if let Some(trait_m_node_id) = tcx.hir.as_local_node_id(trait_m.def_id) {
455                 let (trait_m_output, trait_m_iter) =
456                     match tcx.hir.expect_trait_item(trait_m_node_id).node {
457                         TraitItemKind::Method(ref trait_m_sig, _) => {
458                             (&trait_m_sig.decl.output, trait_m_sig.decl.inputs.iter())
459                         }
460                         _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
461                     };
462
463                 let impl_iter = impl_sig.inputs().iter();
464                 let trait_iter = trait_sig.inputs().iter();
465                 impl_iter.zip(trait_iter)
466                          .zip(impl_m_iter)
467                          .zip(trait_m_iter)
468                          .filter_map(|(((impl_arg_ty, trait_arg_ty), impl_arg), trait_arg)| {
469                              match infcx.sub_types(true, &cause, trait_arg_ty, impl_arg_ty) {
470                                  Ok(_) => None,
471                                  Err(_) => Some((impl_arg.span, Some(trait_arg.span))),
472                              }
473                          })
474                          .next()
475                          .unwrap_or_else(|| {
476                              if infcx.sub_types(false, &cause, impl_sig.output(),
477                                                 trait_sig.output())
478                                      .is_err() {
479                                          (impl_m_output.span(), Some(trait_m_output.span()))
480                                      } else {
481                                          (cause.span, tcx.hir.span_if_local(trait_m.def_id))
482                                      }
483                          })
484             } else {
485                 (cause.span, tcx.hir.span_if_local(trait_m.def_id))
486             }
487         }
488         _ => (cause.span, tcx.hir.span_if_local(trait_m.def_id)),
489     }
490 }
491
492 fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
493                                impl_m: &ty::AssociatedItem,
494                                impl_m_span: Span,
495                                trait_m: &ty::AssociatedItem,
496                                impl_trait_ref: ty::TraitRef<'tcx>)
497                                -> Result<(), ErrorReported>
498 {
499     // Try to give more informative error messages about self typing
500     // mismatches.  Note that any mismatch will also be detected
501     // below, where we construct a canonical function type that
502     // includes the self parameter as a normal parameter.  It's just
503     // that the error messages you get out of this code are a bit more
504     // inscrutable, particularly for cases where one method has no
505     // self.
506
507     let self_string = |method: &ty::AssociatedItem| {
508         let untransformed_self_ty = match method.container {
509             ty::ImplContainer(_) => impl_trait_ref.self_ty(),
510             ty::TraitContainer(_) => tcx.mk_self_type()
511         };
512         let method_ty = tcx.type_of(method.def_id);
513         let self_arg_ty = *method_ty.fn_sig().input(0).skip_binder();
514         match ExplicitSelf::determine(untransformed_self_ty, self_arg_ty) {
515             ExplicitSelf::ByValue => "self".to_string(),
516             ExplicitSelf::ByReference(_, hir::MutImmutable) => "&self".to_string(),
517             ExplicitSelf::ByReference(_, hir::MutMutable) => "&mut self".to_string(),
518             _ => format!("self: {}", self_arg_ty)
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 declared without `{}`", self_descr));
537             }
538             err.emit();
539             return Err(ErrorReported);
540         }
541
542         (true, false) => {
543             let self_descr = self_string(trait_m);
544             let mut err = struct_span_err!(tcx.sess,
545                                            impl_m_span,
546                                            E0186,
547                                            "method `{}` has a `{}` declaration in the trait, but \
548                                             not in the impl",
549                                            trait_m.name,
550                                            self_descr);
551             err.span_label(impl_m_span,
552                            &format!("expected `{}` in impl", self_descr));
553             if let Some(span) = tcx.hir.span_if_local(trait_m.def_id) {
554                 err.span_label(span, &format!("`{}` used in trait", self_descr));
555             }
556             err.emit();
557             return Err(ErrorReported);
558         }
559     }
560
561     Ok(())
562 }
563
564 fn compare_number_of_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
565                                         impl_m: &ty::AssociatedItem,
566                                         impl_m_span: Span,
567                                         trait_m: &ty::AssociatedItem,
568                                         trait_item_span: Option<Span>)
569                                         -> Result<(), ErrorReported> {
570     let impl_m_generics = tcx.generics_of(impl_m.def_id);
571     let trait_m_generics = tcx.generics_of(trait_m.def_id);
572     let num_impl_m_type_params = impl_m_generics.types.len();
573     let num_trait_m_type_params = trait_m_generics.types.len();
574     if num_impl_m_type_params != num_trait_m_type_params {
575         let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
576         let span = match tcx.hir.expect_impl_item(impl_m_node_id).node {
577             ImplItemKind::Method(ref impl_m_sig, _) => {
578                 if impl_m_sig.generics.is_parameterized() {
579                     impl_m_sig.generics.span
580                 } else {
581                     impl_m_span
582                 }
583             }
584             _ => bug!("{:?} is not a method", impl_m),
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 m_fty = |method: &ty::AssociatedItem| {
640         match tcx.type_of(method.def_id).sty {
641             ty::TyFnDef(_, _, f) => f,
642             _ => bug!()
643         }
644     };
645     let impl_m_fty = m_fty(impl_m);
646     let trait_m_fty = m_fty(trait_m);
647     let trait_number_args = trait_m_fty.inputs().skip_binder().len();
648     let impl_number_args = impl_m_fty.inputs().skip_binder().len();
649     if trait_number_args != impl_number_args {
650         let trait_m_node_id = tcx.hir.as_local_node_id(trait_m.def_id);
651         let trait_span = if let Some(trait_id) = trait_m_node_id {
652             match tcx.hir.expect_trait_item(trait_id).node {
653                 TraitItemKind::Method(ref trait_m_sig, _) => {
654                     if let Some(arg) = trait_m_sig.decl.inputs.get(if trait_number_args > 0 {
655                         trait_number_args - 1
656                     } else {
657                         0
658                     }) {
659                         Some(arg.span)
660                     } else {
661                         trait_item_span
662                     }
663                 }
664                 _ => bug!("{:?} is not a method", impl_m),
665             }
666         } else {
667             trait_item_span
668         };
669         let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
670         let impl_span = match tcx.hir.expect_impl_item(impl_m_node_id).node {
671             ImplItemKind::Method(ref impl_m_sig, _) => {
672                 if let Some(arg) = impl_m_sig.decl.inputs.get(if impl_number_args > 0 {
673                     impl_number_args - 1
674                 } else {
675                     0
676                 }) {
677                     arg.span
678                 } else {
679                     impl_m_span
680                 }
681             }
682             _ => bug!("{:?} is not a method", impl_m),
683         };
684         let mut err = struct_span_err!(tcx.sess,
685                                        impl_span,
686                                        E0050,
687                                        "method `{}` has {} parameter{} but the declaration in \
688                                         trait `{}` has {}",
689                                        trait_m.name,
690                                        impl_number_args,
691                                        if impl_number_args == 1 { "" } else { "s" },
692                                        tcx.item_path_str(trait_m.def_id),
693                                        trait_number_args);
694         if let Some(trait_span) = trait_span {
695             err.span_label(trait_span,
696                            &format!("trait requires {}",
697                                     &if trait_number_args != 1 {
698                                         format!("{} parameters", trait_number_args)
699                                     } else {
700                                         format!("{} parameter", trait_number_args)
701                                     }));
702         }
703         err.span_label(impl_span,
704                        &format!("expected {}, found {}",
705                                 &if trait_number_args != 1 {
706                                     format!("{} parameters", trait_number_args)
707                                 } else {
708                                     format!("{} parameter", trait_number_args)
709                                 },
710                                 impl_number_args));
711         err.emit();
712         return Err(ErrorReported);
713     }
714
715     Ok(())
716 }
717
718 pub fn compare_const_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
719                                     impl_c: &ty::AssociatedItem,
720                                     impl_c_span: Span,
721                                     trait_c: &ty::AssociatedItem,
722                                     impl_trait_ref: ty::TraitRef<'tcx>) {
723     debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
724
725     tcx.infer_ctxt((), Reveal::UserFacing).enter(|infcx| {
726         let inh = Inherited::new(infcx);
727         let infcx = &inh.infcx;
728
729         // The below is for the most part highly similar to the procedure
730         // for methods above. It is simpler in many respects, especially
731         // because we shouldn't really have to deal with lifetimes or
732         // predicates. In fact some of this should probably be put into
733         // shared functions because of DRY violations...
734         let trait_to_impl_substs = impl_trait_ref.substs;
735
736         // Create a parameter environment that represents the implementation's
737         // method.
738         let impl_c_node_id = tcx.hir.as_local_node_id(impl_c.def_id).unwrap();
739         let impl_param_env = ty::ParameterEnvironment::for_item(tcx, impl_c_node_id);
740
741         // Create mapping from impl to skolemized.
742         let impl_to_skol_substs = &impl_param_env.free_substs;
743
744         // Create mapping from trait to skolemized.
745         let trait_to_skol_substs = impl_to_skol_substs.rebase_onto(tcx,
746                                                                    impl_c.container.id(),
747                                                                    trait_to_impl_substs.subst(tcx,
748                                                                               impl_to_skol_substs));
749         debug!("compare_const_impl: trait_to_skol_substs={:?}",
750                trait_to_skol_substs);
751
752         // Compute skolemized form of impl and trait const tys.
753         let impl_ty = tcx.type_of(impl_c.def_id).subst(tcx, impl_to_skol_substs);
754         let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_skol_substs);
755         let mut cause = ObligationCause::misc(impl_c_span, impl_c_node_id);
756
757         // There is no "body" here, so just pass dummy id.
758         let impl_ty = inh.normalize_associated_types_in(impl_c_span,
759                                                         impl_c_node_id,
760                                                         &impl_ty);
761
762         debug!("compare_const_impl: impl_ty={:?}", impl_ty);
763
764         let trait_ty = inh.normalize_associated_types_in(impl_c_span,
765                                                          impl_c_node_id,
766                                                          &trait_ty);
767
768         debug!("compare_const_impl: trait_ty={:?}", trait_ty);
769
770         let err = infcx.sub_types(false, &cause, impl_ty, trait_ty)
771             .map(|ok| inh.register_infer_ok_obligations(ok));
772
773         if let Err(terr) = err {
774             debug!("checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
775                    impl_ty,
776                    trait_ty);
777
778             // Locate the Span containing just the type of the offending impl
779             match tcx.hir.expect_impl_item(impl_c_node_id).node {
780                 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
781                 _ => bug!("{:?} is not a impl const", impl_c),
782             }
783
784             let mut diag = struct_span_err!(tcx.sess,
785                                             cause.span,
786                                             E0326,
787                                             "implemented const `{}` has an incompatible type for \
788                                              trait",
789                                             trait_c.name);
790
791             // Add a label to the Span containing just the type of the item
792             let trait_c_node_id = tcx.hir.as_local_node_id(trait_c.def_id).unwrap();
793             let trait_c_span = match tcx.hir.expect_trait_item(trait_c_node_id).node {
794                 TraitItemKind::Const(ref ty, _) => ty.span,
795                 _ => bug!("{:?} is not a trait const", trait_c),
796             };
797
798             infcx.note_type_err(&mut diag,
799                                 &cause,
800                                 Some((trait_c_span, format!("type in trait"))),
801                                 Some(infer::ValuePairs::Types(ExpectedFound {
802                                     expected: trait_ty,
803                                     found: impl_ty,
804                                 })),
805                                 &terr);
806             diag.emit();
807         }
808
809         // FIXME(#41323) Check the obligations in the fulfillment context.
810     });
811 }