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