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