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