]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/compare_method.rs
review comments: use param kind type to identify impl Trait
[rust.git] / src / librustc_typeck / check / compare_method.rs
1 use rustc::hir::{self, GenericParamKind, ImplItemKind, TraitItemKind};
2 use rustc::hir::def::{Res, DefKind};
3 use rustc::infer::{self, InferOk};
4 use rustc::ty::{self, TyCtxt, GenericParamDefKind};
5 use rustc::ty::util::ExplicitSelf;
6 use rustc::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
7 use rustc::ty::error::{ExpectedFound, TypeError};
8 use rustc::ty::subst::{Subst, InternalSubsts, SubstsRef};
9 use rustc::util::common::ErrorReported;
10 use errors::{Applicability, DiagnosticId};
11
12 use syntax_pos::Span;
13
14 use super::{Inherited, FnCtxt, potentially_plural_count};
15
16 /// Checks that a method from an impl conforms to the signature of
17 /// the same method as declared in the trait.
18 ///
19 /// # Parameters
20 ///
21 /// - `impl_m`: type of the method we are checking
22 /// - `impl_m_span`: span to use for reporting errors
23 /// - `trait_m`: the method in the trait
24 /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
25
26 pub fn compare_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
27                                      impl_m: &ty::AssocItem,
28                                      impl_m_span: Span,
29                                      trait_m: &ty::AssocItem,
30                                      impl_trait_ref: ty::TraitRef<'tcx>,
31                                      trait_item_span: Option<Span>) {
32     debug!("compare_impl_method(impl_trait_ref={:?})",
33            impl_trait_ref);
34
35     let impl_m_span = tcx.sess.source_map().def_span(impl_m_span);
36
37     if let Err(ErrorReported) = compare_self_type(tcx,
38                                                   impl_m,
39                                                   impl_m_span,
40                                                   trait_m,
41                                                   impl_trait_ref) {
42         return;
43     }
44
45     if let Err(ErrorReported) = compare_number_of_generics(tcx,
46                                                            impl_m,
47                                                            impl_m_span,
48                                                            trait_m,
49                                                            trait_item_span) {
50         return;
51     }
52
53     if let Err(ErrorReported) = compare_number_of_method_arguments(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_synthetic_generics(tcx,
62                                                            impl_m,
63                                                            trait_m) {
64         return;
65     }
66
67     if let Err(ErrorReported) = compare_predicate_entailment(tcx,
68                                                              impl_m,
69                                                              impl_m_span,
70                                                              trait_m,
71                                                              impl_trait_ref) {
72         return;
73     }
74 }
75
76 fn compare_predicate_entailment<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
77                                           impl_m: &ty::AssocItem,
78                                           impl_m_span: Span,
79                                           trait_m: &ty::AssocItem,
80                                           impl_trait_ref: ty::TraitRef<'tcx>)
81                                           -> Result<(), ErrorReported> {
82     let trait_to_impl_substs = impl_trait_ref.substs;
83
84     // This node-id should be used for the `body_id` field on each
85     // `ObligationCause` (and the `FnCtxt`). This is what
86     // `regionck_item` expects.
87     let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id).unwrap();
88
89     let cause = ObligationCause {
90         span: impl_m_span,
91         body_id: impl_m_hir_id,
92         code: ObligationCauseCode::CompareImplMethodObligation {
93             item_name: impl_m.ident.name,
94             impl_item_def_id: impl_m.def_id,
95             trait_item_def_id: trait_m.def_id,
96         },
97     };
98
99     // This code is best explained by example. Consider a trait:
100     //
101     //     trait Trait<'t,T> {
102     //          fn method<'a,M>(t: &'t T, m: &'a M) -> Self;
103     //     }
104     //
105     // And an impl:
106     //
107     //     impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
108     //          fn method<'b,N>(t: &'j &'i U, m: &'b N) -> Foo;
109     //     }
110     //
111     // We wish to decide if those two method types are compatible.
112     //
113     // We start out with trait_to_impl_substs, that maps the trait
114     // type parameters to impl type parameters. This is taken from the
115     // impl trait reference:
116     //
117     //     trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
118     //
119     // We create a mapping `dummy_substs` that maps from the impl type
120     // parameters to fresh types and regions. For type parameters,
121     // this is the identity transform, but we could as well use any
122     // placeholder types. For regions, we convert from bound to free
123     // regions (Note: but only early-bound regions, i.e., those
124     // declared on the impl or used in type parameter bounds).
125     //
126     //     impl_to_skol_substs = {'i => 'i0, U => U0, N => N0 }
127     //
128     // Now we can apply skol_substs to the type of the impl method
129     // to yield a new function type in terms of our fresh, placeholder
130     // types:
131     //
132     //     <'b> fn(t: &'i0 U0, m: &'b) -> Foo
133     //
134     // We now want to extract and substitute the type of the *trait*
135     // method and compare it. To do so, we must create a compound
136     // substitution by combining trait_to_impl_substs and
137     // impl_to_skol_substs, and also adding a mapping for the method
138     // type parameters. We extend the mapping to also include
139     // the method parameters.
140     //
141     //     trait_to_skol_substs = { T => &'i0 U0, Self => Foo, M => N0 }
142     //
143     // Applying this to the trait method type yields:
144     //
145     //     <'a> fn(t: &'i0 U0, m: &'a) -> Foo
146     //
147     // This type is also the same but the name of the bound region ('a
148     // vs 'b).  However, the normal subtyping rules on fn types handle
149     // this kind of equivalency just fine.
150     //
151     // We now use these substitutions to ensure that all declared bounds are
152     // satisfied by the implementation's method.
153     //
154     // We do this by creating a parameter environment which contains a
155     // substitution corresponding to impl_to_skol_substs. We then build
156     // trait_to_skol_substs and use it to convert the predicates contained
157     // in the trait_m.generics to the placeholder form.
158     //
159     // Finally we register each of these predicates as an obligation in
160     // a fresh FulfillmentCtxt, and invoke select_all_or_error.
161
162     // Create mapping from impl to placeholder.
163     let impl_to_skol_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
164
165     // Create mapping from trait to placeholder.
166     let trait_to_skol_substs = impl_to_skol_substs.rebase_onto(tcx,
167                                                                impl_m.container.id(),
168                                                                trait_to_impl_substs);
169     debug!("compare_impl_method: trait_to_skol_substs={:?}",
170            trait_to_skol_substs);
171
172     let impl_m_generics = tcx.generics_of(impl_m.def_id);
173     let trait_m_generics = tcx.generics_of(trait_m.def_id);
174     let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
175     let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
176
177     // Check region bounds.
178     check_region_bounds_on_impl_method(tcx,
179                                        impl_m_span,
180                                        impl_m,
181                                        trait_m,
182                                        &trait_m_generics,
183                                        &impl_m_generics,
184                                        trait_to_skol_substs)?;
185
186     // Create obligations for each predicate declared by the impl
187     // definition in the context of the trait's parameter
188     // environment. We can't just use `impl_env.caller_bounds`,
189     // however, because we want to replace all late-bound regions with
190     // region variables.
191     let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
192     let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
193
194     debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
195
196     // This is the only tricky bit of the new way we check implementation methods
197     // We need to build a set of predicates where only the method-level bounds
198     // are from the trait and we assume all other bounds from the implementation
199     // to be previously satisfied.
200     //
201     // We then register the obligations from the impl_m and check to see
202     // if all constraints hold.
203     hybrid_preds.predicates.extend(
204         trait_m_predicates.instantiate_own(tcx, trait_to_skol_substs).predicates);
205
206     // Construct trait parameter environment and then shift it into the placeholder viewpoint.
207     // The key step here is to update the caller_bounds's predicates to be
208     // the new hybrid bounds we computed.
209     let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
210     let param_env = ty::ParamEnv::new(
211         tcx.intern_predicates(&hybrid_preds.predicates),
212         Reveal::UserFacing,
213         None
214     );
215     let param_env = traits::normalize_param_env_or_error(tcx,
216                                                          impl_m.def_id,
217                                                          param_env,
218                                                          normalize_cause.clone());
219
220     tcx.infer_ctxt().enter(|infcx| {
221         let inh = Inherited::new(infcx, impl_m.def_id);
222         let infcx = &inh.infcx;
223
224         debug!("compare_impl_method: caller_bounds={:?}",
225                param_env.caller_bounds);
226
227         let mut selcx = traits::SelectionContext::new(&infcx);
228
229         let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_skol_substs);
230         let (impl_m_own_bounds, _) = infcx.replace_bound_vars_with_fresh_vars(
231             impl_m_span,
232             infer::HigherRankedType,
233             &ty::Binder::bind(impl_m_own_bounds.predicates)
234         );
235         for predicate in impl_m_own_bounds {
236             let traits::Normalized { value: predicate, obligations } =
237                 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), &predicate);
238
239             inh.register_predicates(obligations);
240             inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
241         }
242
243         // We now need to check that the signature of the impl method is
244         // compatible with that of the trait method. We do this by
245         // checking that `impl_fty <: trait_fty`.
246         //
247         // FIXME. Unfortunately, this doesn't quite work right now because
248         // associated type normalization is not integrated into subtype
249         // checks. For the comparison to be valid, we need to
250         // normalize the associated types in the impl/trait methods
251         // first. However, because function types bind regions, just
252         // calling `normalize_associated_types_in` would have no effect on
253         // any associated types appearing in the fn arguments or return
254         // type.
255
256         // Compute placeholder form of impl and trait method tys.
257         let tcx = infcx.tcx;
258
259         let (impl_sig, _) = infcx.replace_bound_vars_with_fresh_vars(
260             impl_m_span,
261             infer::HigherRankedType,
262             &tcx.fn_sig(impl_m.def_id)
263         );
264         let impl_sig =
265             inh.normalize_associated_types_in(impl_m_span,
266                                               impl_m_hir_id,
267                                               param_env,
268                                               &impl_sig);
269         let impl_fty = tcx.mk_fn_ptr(ty::Binder::bind(impl_sig));
270         debug!("compare_impl_method: impl_fty={:?}", impl_fty);
271
272         let trait_sig = tcx.liberate_late_bound_regions(
273             impl_m.def_id,
274             &tcx.fn_sig(trait_m.def_id));
275         let trait_sig =
276             trait_sig.subst(tcx, trait_to_skol_substs);
277         let trait_sig =
278             inh.normalize_associated_types_in(impl_m_span,
279                                               impl_m_hir_id,
280                                               param_env,
281                                               &trait_sig);
282         let trait_fty = tcx.mk_fn_ptr(ty::Binder::bind(trait_sig));
283
284         debug!("compare_impl_method: trait_fty={:?}", trait_fty);
285
286         let sub_result = infcx.at(&cause, param_env)
287                               .sup(trait_fty, impl_fty)
288                               .map(|InferOk { obligations, .. }| {
289                                   inh.register_predicates(obligations);
290                               });
291
292         if let Err(terr) = sub_result {
293             debug!("sub_types failed: impl ty {:?}, trait ty {:?}",
294                    impl_fty,
295                    trait_fty);
296
297             let (impl_err_span, trait_err_span) = extract_spans_for_error_reporting(&infcx,
298                                                                                     param_env,
299                                                                                     &terr,
300                                                                                     &cause,
301                                                                                     impl_m,
302                                                                                     impl_sig,
303                                                                                     trait_m,
304                                                                                     trait_sig);
305
306             let cause = ObligationCause {
307                 span: impl_err_span,
308                 ..cause.clone()
309             };
310
311             let mut diag = struct_span_err!(tcx.sess,
312                                             cause.span(tcx),
313                                             E0053,
314                                             "method `{}` has an incompatible type for trait",
315                                             trait_m.ident);
316             if let TypeError::Mutability = terr {
317                 if let Some(trait_err_span) = trait_err_span {
318                     if let Ok(trait_err_str) = tcx.sess.source_map()
319                                                        .span_to_snippet(trait_err_span) {
320                         diag.span_suggestion(
321                             impl_err_span,
322                             "consider change the type to match the mutability in trait",
323                             trait_err_str,
324                             Applicability::MachineApplicable,
325                         );
326                     }
327                 }
328             }
329
330             infcx.note_type_err(&mut diag,
331                                 &cause,
332                                 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
333                                 Some(infer::ValuePairs::Types(ExpectedFound {
334                                     expected: trait_fty,
335                                     found: impl_fty,
336                                 })),
337                                 &terr);
338             diag.emit();
339             return Err(ErrorReported);
340         }
341
342         // Check that all obligations are satisfied by the implementation's
343         // version.
344         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
345             infcx.report_fulfillment_errors(errors, None, false);
346             return Err(ErrorReported);
347         }
348
349         // Finally, resolve all regions. This catches wily misuses of
350         // lifetime parameters.
351         let fcx = FnCtxt::new(&inh, param_env, impl_m_hir_id);
352         fcx.regionck_item(impl_m_hir_id, impl_m_span, &[]);
353
354         Ok(())
355     })
356 }
357
358 fn check_region_bounds_on_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
359                                                 span: Span,
360                                                 impl_m: &ty::AssocItem,
361                                                 trait_m: &ty::AssocItem,
362                                                 trait_generics: &ty::Generics,
363                                                 impl_generics: &ty::Generics,
364                                                 trait_to_skol_substs: SubstsRef<'tcx>)
365                                                 -> Result<(), ErrorReported> {
366     let trait_params = trait_generics.own_counts().lifetimes;
367     let impl_params = impl_generics.own_counts().lifetimes;
368
369     debug!("check_region_bounds_on_impl_method: \
370             trait_generics={:?} \
371             impl_generics={:?} \
372             trait_to_skol_substs={:?}",
373            trait_generics,
374            impl_generics,
375            trait_to_skol_substs);
376
377     // Must have same number of early-bound lifetime parameters.
378     // Unfortunately, if the user screws up the bounds, then this
379     // will change classification between early and late.  E.g.,
380     // if in trait we have `<'a,'b:'a>`, and in impl we just have
381     // `<'a,'b>`, then we have 2 early-bound lifetime parameters
382     // in trait but 0 in the impl. But if we report "expected 2
383     // but found 0" it's confusing, because it looks like there
384     // are zero. Since I don't quite know how to phrase things at
385     // the moment, give a kind of vague error message.
386     if trait_params != impl_params {
387         let def_span = tcx.sess.source_map().def_span(span);
388         let span = tcx.hir().get_generics(impl_m.def_id).map(|g| g.span).unwrap_or(def_span);
389         let mut err = struct_span_err!(
390             tcx.sess,
391             span,
392             E0195,
393             "lifetime parameters or bounds on method `{}` do not match the trait declaration",
394             impl_m.ident,
395         );
396         err.span_label(span, "lifetimes do not match method in trait");
397         if let Some(sp) = tcx.hir().span_if_local(trait_m.def_id) {
398             let def_sp = tcx.sess.source_map().def_span(sp);
399             let sp = tcx.hir().get_generics(trait_m.def_id).map(|g| g.span).unwrap_or(def_sp);
400             err.span_label(sp, "lifetimes in impl do not match this method in trait");
401         }
402         err.emit();
403         return Err(ErrorReported);
404     }
405
406     Ok(())
407 }
408
409 fn extract_spans_for_error_reporting<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
410                                                      param_env: ty::ParamEnv<'tcx>,
411                                                      terr: &TypeError<'_>,
412                                                      cause: &ObligationCause<'tcx>,
413                                                      impl_m: &ty::AssocItem,
414                                                      impl_sig: ty::FnSig<'tcx>,
415                                                      trait_m: &ty::AssocItem,
416                                                      trait_sig: ty::FnSig<'tcx>)
417                                                      -> (Span, Option<Span>) {
418     let tcx = infcx.tcx;
419     let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id).unwrap();
420     let (impl_m_output, impl_m_iter) = match tcx.hir()
421                                                 .expect_impl_item(impl_m_hir_id)
422                                                 .node {
423         ImplItemKind::Method(ref impl_m_sig, _) => {
424             (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter())
425         }
426         _ => bug!("{:?} is not a method", impl_m),
427     };
428
429     match *terr {
430         TypeError::Mutability => {
431             if let Some(trait_m_hir_id) = tcx.hir().as_local_hir_id(trait_m.def_id) {
432                 let trait_m_iter = match tcx.hir()
433                                             .expect_trait_item(trait_m_hir_id)
434                                             .node {
435                     TraitItemKind::Method(ref trait_m_sig, _) => {
436                         trait_m_sig.decl.inputs.iter()
437                     }
438                     _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
439                 };
440
441                 impl_m_iter.zip(trait_m_iter).find(|&(ref impl_arg, ref trait_arg)| {
442                     match (&impl_arg.node, &trait_arg.node) {
443                         (&hir::TyKind::Rptr(_, ref impl_mt), &hir::TyKind::Rptr(_, ref trait_mt)) |
444                         (&hir::TyKind::Ptr(ref impl_mt), &hir::TyKind::Ptr(ref trait_mt)) => {
445                             impl_mt.mutbl != trait_mt.mutbl
446                         }
447                         _ => false,
448                     }
449                 }).map(|(ref impl_arg, ref trait_arg)| {
450                     (impl_arg.span, Some(trait_arg.span))
451                 })
452                 .unwrap_or_else(|| (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)))
453             } else {
454                 (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
455             }
456         }
457         TypeError::Sorts(ExpectedFound { .. }) => {
458             if let Some(trait_m_hir_id) = tcx.hir().as_local_hir_id(trait_m.def_id) {
459                 let (trait_m_output, trait_m_iter) =
460                     match tcx.hir().expect_trait_item(trait_m_hir_id).node {
461                         TraitItemKind::Method(ref trait_m_sig, _) => {
462                             (&trait_m_sig.decl.output, trait_m_sig.decl.inputs.iter())
463                         }
464                         _ => bug!("{:?} is not a TraitItemKind::Method", trait_m),
465                     };
466
467                 let impl_iter = impl_sig.inputs().iter();
468                 let trait_iter = trait_sig.inputs().iter();
469                 impl_iter.zip(trait_iter)
470                          .zip(impl_m_iter)
471                          .zip(trait_m_iter)
472                          .filter_map(|(((&impl_arg_ty, &trait_arg_ty), impl_arg), trait_arg)|
473                              match infcx.at(&cause, param_env).sub(trait_arg_ty, impl_arg_ty) {
474                                  Ok(_) => None,
475                                  Err(_) => Some((impl_arg.span, Some(trait_arg.span))),
476                              }
477                          )
478                          .next()
479                          .unwrap_or_else(||
480                              if
481                                  infcx.at(&cause, param_env)
482                                       .sup(trait_sig.output(), impl_sig.output())
483                                       .is_err()
484                              {
485                                  (impl_m_output.span(), Some(trait_m_output.span()))
486                              } else {
487                                  (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
488                              }
489                          )
490             } else {
491                 (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
492             }
493         }
494         _ => (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)),
495     }
496 }
497
498 fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
499                                impl_m: &ty::AssocItem,
500                                impl_m_span: Span,
501                                trait_m: &ty::AssocItem,
502                                impl_trait_ref: ty::TraitRef<'tcx>)
503                                -> Result<(), ErrorReported>
504 {
505     // Try to give more informative error messages about self typing
506     // mismatches.  Note that any mismatch will also be detected
507     // below, where we construct a canonical function type that
508     // includes the self parameter as a normal parameter.  It's just
509     // that the error messages you get out of this code are a bit more
510     // inscrutable, particularly for cases where one method has no
511     // self.
512
513     let self_string = |method: &ty::AssocItem| {
514         let untransformed_self_ty = match method.container {
515             ty::ImplContainer(_) => impl_trait_ref.self_ty(),
516             ty::TraitContainer(_) => tcx.mk_self_type()
517         };
518         let self_arg_ty = *tcx.fn_sig(method.def_id).input(0).skip_binder();
519         let param_env = ty::ParamEnv::reveal_all();
520
521         tcx.infer_ctxt().enter(|infcx| {
522             let self_arg_ty = tcx.liberate_late_bound_regions(
523                 method.def_id,
524                 &ty::Binder::bind(self_arg_ty)
525             );
526             let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
527             match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
528                 ExplicitSelf::ByValue => "self".to_owned(),
529                 ExplicitSelf::ByReference(_, hir::MutImmutable) => "&self".to_owned(),
530                 ExplicitSelf::ByReference(_, hir::MutMutable) => "&mut self".to_owned(),
531                 _ => format!("self: {}", self_arg_ty)
532             }
533         })
534     };
535
536     match (trait_m.method_has_self_argument, impl_m.method_has_self_argument) {
537         (false, false) | (true, true) => {}
538
539         (false, true) => {
540             let self_descr = self_string(impl_m);
541             let mut err = struct_span_err!(tcx.sess,
542                                            impl_m_span,
543                                            E0185,
544                                            "method `{}` has a `{}` declaration in the impl, but \
545                                             not in the trait",
546                                            trait_m.ident,
547                                            self_descr);
548             err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
549             if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
550                 err.span_label(span, format!("trait method declared without `{}`", self_descr));
551             } else {
552                 err.note_trait_signature(trait_m.ident.to_string(),
553                                          trait_m.signature(tcx));
554             }
555             err.emit();
556             return Err(ErrorReported);
557         }
558
559         (true, false) => {
560             let self_descr = self_string(trait_m);
561             let mut err = struct_span_err!(tcx.sess,
562                                            impl_m_span,
563                                            E0186,
564                                            "method `{}` has a `{}` declaration in the trait, but \
565                                             not in the impl",
566                                            trait_m.ident,
567                                            self_descr);
568             err.span_label(impl_m_span, format!("expected `{}` in impl", self_descr));
569             if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
570                 err.span_label(span, format!("`{}` used in trait", self_descr));
571             } else {
572                 err.note_trait_signature(trait_m.ident.to_string(),
573                                          trait_m.signature(tcx));
574             }
575             err.emit();
576             return Err(ErrorReported);
577         }
578     }
579
580     Ok(())
581 }
582
583 fn compare_number_of_generics<'a, 'tcx>(
584     tcx: TyCtxt<'a, 'tcx, 'tcx>,
585     impl_: &ty::AssocItem,
586     _impl_span: Span,
587     trait_: &ty::AssocItem,
588     trait_span: Option<Span>,
589 ) -> Result<(), ErrorReported> {
590     let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
591     let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
592
593     let matchings = [
594         ("type", trait_own_counts.types, impl_own_counts.types),
595         ("const", trait_own_counts.consts, impl_own_counts.consts),
596     ];
597
598     let mut err_occurred = false;
599     for &(kind, trait_count, impl_count) in &matchings {
600         if impl_count != trait_count {
601             err_occurred = true;
602
603             let (
604                 trait_spans,
605                 impl_trait_spans,
606             ) = if let Some(trait_hir_id) = tcx.hir().as_local_hir_id(trait_.def_id) {
607                 let trait_item = tcx.hir().expect_trait_item(trait_hir_id);
608                 if trait_item.generics.params.is_empty() {
609                     (Some(vec![trait_item.generics.span]), vec![])
610                 } else {
611                     let arg_spans: Vec<Span> = trait_item.generics.params.iter()
612                         .map(|p| p.span)
613                         .collect();
614                     let impl_trait_spans: Vec<Span> = trait_item.generics.params.iter()
615                         .filter_map(|p| match p.kind {
616                             GenericParamKind::Type {
617                                 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
618                             } => Some(p.span),
619                             _ => None,
620                         }).collect();
621                     (Some(arg_spans), impl_trait_spans)
622                 }
623             } else {
624                 (trait_span.map(|s| vec![s]), vec![])
625             };
626
627             let impl_hir_id = tcx.hir().as_local_hir_id(impl_.def_id).unwrap();
628             let impl_item = tcx.hir().expect_impl_item(impl_hir_id);
629             let impl_item_impl_trait_spans: Vec<Span> = impl_item.generics.params.iter()
630                 .filter_map(|p| match p.kind {
631                     GenericParamKind::Type {
632                         synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
633                     } => Some(p.span),
634                     _ => None,
635                 }).collect();
636             let spans = impl_item.generics.spans();
637             let span = spans.primary_span();
638
639             let mut err = tcx.sess.struct_span_err_with_code(
640                 spans,
641                 &format!(
642                     "method `{}` has {} {kind} parameter{} but its trait \
643                      declaration has {} {kind} parameter{}",
644                     trait_.ident,
645                     impl_count,
646                     if impl_count != 1 { "s" } else { "" },
647                     trait_count,
648                     if trait_count != 1 { "s" } else { "" },
649                     kind = kind,
650                 ),
651                 DiagnosticId::Error("E0049".into()),
652             );
653
654             let mut suffix = None;
655
656             if let Some(spans) = trait_spans {
657                 let mut spans = spans.iter();
658                 if let Some(span) = spans.next() {
659                     err.span_label(*span, format!(
660                         "expected {} {} parameter{}",
661                         trait_count,
662                         kind,
663                         if trait_count != 1 { "s" } else { "" },
664                     ));
665                 }
666                 for span in spans {
667                     err.span_label(*span, "");
668                 }
669             } else {
670                 suffix = Some(format!(", expected {}", trait_count));
671             }
672
673             if let Some(span) = span {
674                 err.span_label(span, format!(
675                     "found {} {} parameter{}{}",
676                     impl_count,
677                     kind,
678                     if impl_count != 1 { "s" } else { "" },
679                     suffix.unwrap_or_else(|| String::new()),
680                 ));
681             }
682
683             for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
684                 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
685             }
686
687             err.emit();
688         }
689     }
690
691     if err_occurred {
692         Err(ErrorReported)
693     } else {
694         Ok(())
695     }
696 }
697
698 fn compare_number_of_method_arguments<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
699                                                 impl_m: &ty::AssocItem,
700                                                 impl_m_span: Span,
701                                                 trait_m: &ty::AssocItem,
702                                                 trait_item_span: Option<Span>)
703                                                 -> Result<(), ErrorReported> {
704     let impl_m_fty = tcx.fn_sig(impl_m.def_id);
705     let trait_m_fty = tcx.fn_sig(trait_m.def_id);
706     let trait_number_args = trait_m_fty.inputs().skip_binder().len();
707     let impl_number_args = impl_m_fty.inputs().skip_binder().len();
708     if trait_number_args != impl_number_args {
709         let trait_m_hir_id = tcx.hir().as_local_hir_id(trait_m.def_id);
710         let trait_span = if let Some(trait_id) = trait_m_hir_id {
711             match tcx.hir().expect_trait_item(trait_id).node {
712                 TraitItemKind::Method(ref trait_m_sig, _) => {
713                     let pos = if trait_number_args > 0 {
714                         trait_number_args - 1
715                     } else {
716                         0
717                     };
718                     if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
719                         Some(if pos == 0 {
720                             arg.span
721                         } else {
722                             Span::new(trait_m_sig.decl.inputs[0].span.lo(),
723                                       arg.span.hi(),
724                                       arg.span.ctxt())
725                         })
726                     } else {
727                         trait_item_span
728                     }
729                 }
730                 _ => bug!("{:?} is not a method", impl_m),
731             }
732         } else {
733             trait_item_span
734         };
735         let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id).unwrap();
736         let impl_span = match tcx.hir().expect_impl_item(impl_m_hir_id).node {
737             ImplItemKind::Method(ref impl_m_sig, _) => {
738                 let pos = if impl_number_args > 0 {
739                     impl_number_args - 1
740                 } else {
741                     0
742                 };
743                 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
744                     if pos == 0 {
745                         arg.span
746                     } else {
747                         Span::new(impl_m_sig.decl.inputs[0].span.lo(),
748                                   arg.span.hi(),
749                                   arg.span.ctxt())
750                     }
751                 } else {
752                     impl_m_span
753                 }
754             }
755             _ => bug!("{:?} is not a method", impl_m),
756         };
757         let mut err = struct_span_err!(tcx.sess,
758                                        impl_span,
759                                        E0050,
760                                        "method `{}` has {} but the declaration in \
761                                         trait `{}` has {}",
762                                        trait_m.ident,
763                                        potentially_plural_count(impl_number_args, "parameter"),
764                                        tcx.def_path_str(trait_m.def_id),
765                                        trait_number_args);
766         if let Some(trait_span) = trait_span {
767             err.span_label(trait_span, format!("trait requires {}",
768                 potentially_plural_count(trait_number_args, "parameter")));
769         } else {
770             err.note_trait_signature(trait_m.ident.to_string(),
771                                      trait_m.signature(tcx));
772         }
773         err.span_label(impl_span, format!("expected {}, found {}",
774             potentially_plural_count(trait_number_args, "parameter"), impl_number_args));
775         err.emit();
776         return Err(ErrorReported);
777     }
778
779     Ok(())
780 }
781
782 fn compare_synthetic_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
783                                         impl_m: &ty::AssocItem,
784                                         trait_m: &ty::AssocItem)
785                                         -> Result<(), ErrorReported> {
786     // FIXME(chrisvittal) Clean up this function, list of FIXME items:
787     //     1. Better messages for the span labels
788     //     2. Explanation as to what is going on
789     // If we get here, we already have the same number of generics, so the zip will
790     // be okay.
791     let mut error_found = false;
792     let impl_m_generics = tcx.generics_of(impl_m.def_id);
793     let trait_m_generics = tcx.generics_of(trait_m.def_id);
794     let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
795         GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
796         GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
797     });
798     let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| {
799         match param.kind {
800             GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
801             GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
802         }
803     });
804     for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic))
805         in impl_m_type_params.zip(trait_m_type_params)
806     {
807         if impl_synthetic != trait_synthetic {
808             let impl_hir_id = tcx.hir().as_local_hir_id(impl_def_id).unwrap();
809             let impl_span = tcx.hir().span_by_hir_id(impl_hir_id);
810             let trait_span = tcx.def_span(trait_def_id);
811             let mut err = struct_span_err!(tcx.sess,
812                                            impl_span,
813                                            E0643,
814                                            "method `{}` has incompatible signature for trait",
815                                            trait_m.ident);
816             err.span_label(trait_span, "declaration in trait here");
817             match (impl_synthetic, trait_synthetic) {
818                 // The case where the impl method uses `impl Trait` but the trait method uses
819                 // explicit generics
820                 (Some(hir::SyntheticTyParamKind::ImplTrait), None) => {
821                     err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
822                     (|| {
823                         // try taking the name from the trait impl
824                         // FIXME: this is obviously suboptimal since the name can already be used
825                         // as another generic argument
826                         let new_name = tcx
827                             .sess
828                             .source_map()
829                             .span_to_snippet(trait_span)
830                             .ok()?;
831                         let trait_m = tcx.hir().as_local_hir_id(trait_m.def_id)?;
832                         let trait_m = tcx.hir().trait_item(hir::TraitItemId { hir_id: trait_m });
833
834                         let impl_m = tcx.hir().as_local_hir_id(impl_m.def_id)?;
835                         let impl_m = tcx.hir().impl_item(hir::ImplItemId { hir_id: impl_m });
836
837                         // in case there are no generics, take the spot between the function name
838                         // and the opening paren of the argument list
839                         let new_generics_span = tcx
840                             .sess
841                             .source_map()
842                             .generate_fn_name_span(impl_span)?
843                             .shrink_to_hi();
844                         // in case there are generics, just replace them
845                         let generics_span = impl_m
846                             .generics
847                             .span
848                             .substitute_dummy(new_generics_span);
849                         // replace with the generics from the trait
850                         let new_generics = tcx
851                             .sess
852                             .source_map()
853                             .span_to_snippet(trait_m.generics.span)
854                             .ok()?;
855
856                         err.multipart_suggestion(
857                             "try changing the `impl Trait` argument to a generic parameter",
858                             vec![
859                                 // replace `impl Trait` with `T`
860                                 (impl_span, new_name),
861                                 // replace impl method generics with trait method generics
862                                 // This isn't quite right, as users might have changed the names
863                                 // of the generics, but it works for the common case
864                                 (generics_span, new_generics),
865                             ],
866                             Applicability::MaybeIncorrect,
867                         );
868                         Some(())
869                     })();
870                 },
871                 // The case where the trait method uses `impl Trait`, but the impl method uses
872                 // explicit generics.
873                 (None, Some(hir::SyntheticTyParamKind::ImplTrait)) => {
874                     err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
875                     (|| {
876                         let impl_m = tcx.hir().as_local_hir_id(impl_m.def_id)?;
877                         let impl_m = tcx.hir().impl_item(hir::ImplItemId { hir_id: impl_m });
878                         let input_tys = match impl_m.node {
879                             hir::ImplItemKind::Method(ref sig, _) => &sig.decl.inputs,
880                             _ => unreachable!(),
881                         };
882                         struct Visitor(Option<Span>, hir::def_id::DefId);
883                         impl<'v> hir::intravisit::Visitor<'v> for Visitor {
884                             fn visit_ty(&mut self, ty: &'v hir::Ty) {
885                                 hir::intravisit::walk_ty(self, ty);
886                                 if let hir::TyKind::Path(
887                                     hir::QPath::Resolved(None, ref path)) = ty.node
888                                 {
889                                     if let Res::Def(DefKind::TyParam, def_id) = path.res {
890                                         if def_id == self.1 {
891                                             self.0 = Some(ty.span);
892                                         }
893                                     }
894                                 }
895                             }
896                             fn nested_visit_map<'this>(
897                                 &'this mut self
898                             ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
899                                 hir::intravisit::NestedVisitorMap::None
900                             }
901                         }
902                         let mut visitor = Visitor(None, impl_def_id);
903                         for ty in input_tys {
904                             hir::intravisit::Visitor::visit_ty(&mut visitor, ty);
905                         }
906                         let span = visitor.0?;
907
908                         let bounds = impl_m.generics.params.iter().find_map(|param| {
909                             match param.kind {
910                                 GenericParamKind::Lifetime { .. } => None,
911                                 GenericParamKind::Type { .. } |
912                                 GenericParamKind::Const { .. } => {
913                                     if param.hir_id == impl_hir_id {
914                                         Some(&param.bounds)
915                                     } else {
916                                         None
917                                     }
918                                 }
919                             }
920                         })?;
921                         let bounds = bounds.first()?.span().to(bounds.last()?.span());
922                         let bounds = tcx
923                             .sess
924                             .source_map()
925                             .span_to_snippet(bounds)
926                             .ok()?;
927
928                         err.multipart_suggestion(
929                             "try removing the generic parameter and using `impl Trait` instead",
930                             vec![
931                                 // delete generic parameters
932                                 (impl_m.generics.span, String::new()),
933                                 // replace param usage with `impl Trait`
934                                 (span, format!("impl {}", bounds)),
935                             ],
936                             Applicability::MaybeIncorrect,
937                         );
938                         Some(())
939                     })();
940                 },
941                 _ => unreachable!(),
942             }
943             err.emit();
944             error_found = true;
945         }
946     }
947     if error_found {
948         Err(ErrorReported)
949     } else {
950         Ok(())
951     }
952 }
953
954 pub fn compare_const_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
955                                     impl_c: &ty::AssocItem,
956                                     impl_c_span: Span,
957                                     trait_c: &ty::AssocItem,
958                                     impl_trait_ref: ty::TraitRef<'tcx>) {
959     debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
960
961     tcx.infer_ctxt().enter(|infcx| {
962         let param_env = tcx.param_env(impl_c.def_id);
963         let inh = Inherited::new(infcx, impl_c.def_id);
964         let infcx = &inh.infcx;
965
966         // The below is for the most part highly similar to the procedure
967         // for methods above. It is simpler in many respects, especially
968         // because we shouldn't really have to deal with lifetimes or
969         // predicates. In fact some of this should probably be put into
970         // shared functions because of DRY violations...
971         let trait_to_impl_substs = impl_trait_ref.substs;
972
973         // Create a parameter environment that represents the implementation's
974         // method.
975         let impl_c_hir_id = tcx.hir().as_local_hir_id(impl_c.def_id).unwrap();
976
977         // Compute placeholder form of impl and trait const tys.
978         let impl_ty = tcx.type_of(impl_c.def_id);
979         let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
980         let mut cause = ObligationCause::misc(impl_c_span, impl_c_hir_id);
981
982         // There is no "body" here, so just pass dummy id.
983         let impl_ty = inh.normalize_associated_types_in(impl_c_span,
984                                                         impl_c_hir_id,
985                                                         param_env,
986                                                         &impl_ty);
987
988         debug!("compare_const_impl: impl_ty={:?}", impl_ty);
989
990         let trait_ty = inh.normalize_associated_types_in(impl_c_span,
991                                                          impl_c_hir_id,
992                                                          param_env,
993                                                          &trait_ty);
994
995         debug!("compare_const_impl: trait_ty={:?}", trait_ty);
996
997         let err = infcx.at(&cause, param_env)
998                        .sup(trait_ty, impl_ty)
999                        .map(|ok| inh.register_infer_ok_obligations(ok));
1000
1001         if let Err(terr) = err {
1002             debug!("checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1003                    impl_ty,
1004                    trait_ty);
1005
1006             // Locate the Span containing just the type of the offending impl
1007             match tcx.hir().expect_impl_item(impl_c_hir_id).node {
1008                 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
1009                 _ => bug!("{:?} is not a impl const", impl_c),
1010             }
1011
1012             let mut diag = struct_span_err!(tcx.sess,
1013                                             cause.span,
1014                                             E0326,
1015                                             "implemented const `{}` has an incompatible type for \
1016                                              trait",
1017                                             trait_c.ident);
1018
1019             let trait_c_hir_id = tcx.hir().as_local_hir_id(trait_c.def_id);
1020             let trait_c_span = trait_c_hir_id.map(|trait_c_hir_id| {
1021                 // Add a label to the Span containing just the type of the const
1022                 match tcx.hir().expect_trait_item(trait_c_hir_id).node {
1023                     TraitItemKind::Const(ref ty, _) => ty.span,
1024                     _ => bug!("{:?} is not a trait const", trait_c),
1025                 }
1026             });
1027
1028             infcx.note_type_err(&mut diag,
1029                                 &cause,
1030                                 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1031                                 Some(infer::ValuePairs::Types(ExpectedFound {
1032                                     expected: trait_ty,
1033                                     found: impl_ty,
1034                                 })),
1035                                 &terr);
1036             diag.emit();
1037         }
1038
1039         // Check that all obligations are satisfied by the implementation's
1040         // version.
1041         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
1042             infcx.report_fulfillment_errors(errors, None, false);
1043             return;
1044         }
1045
1046         let fcx = FnCtxt::new(&inh, param_env, impl_c_hir_id);
1047         fcx.regionck_item(impl_c_hir_id, impl_c_span, &[]);
1048     });
1049 }