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