]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/compare_method.rs
Auto merge of #67924 - RalfJung:miri, r=RalfJung
[rust.git] / src / librustc_typeck / check / compare_method.rs
1 use errors::{Applicability, DiagnosticId};
2 use rustc::hir::intravisit;
3 use rustc::infer::{self, InferOk};
4 use rustc::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
5 use rustc::ty::error::{ExpectedFound, TypeError};
6 use rustc::ty::subst::{InternalSubsts, Subst};
7 use rustc::ty::util::ExplicitSelf;
8 use rustc::ty::{self, GenericParamDefKind, TyCtxt};
9 use rustc::util::common::ErrorReported;
10 use rustc_hir as hir;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind};
13 use rustc_span::Span;
14 use syntax::errors::pluralize;
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                             fn nested_visit_map<'this>(
895                                 &'this mut self,
896                             ) -> intravisit::NestedVisitorMap<'this, 'v>
897                             {
898                                 intravisit::NestedVisitorMap::None
899                             }
900                         }
901                         let mut visitor = Visitor(None, impl_def_id);
902                         for ty in input_tys {
903                             intravisit::Visitor::visit_ty(&mut visitor, ty);
904                         }
905                         let span = visitor.0?;
906
907                         let bounds =
908                             impl_m.generics.params.iter().find_map(|param| match param.kind {
909                                 GenericParamKind::Lifetime { .. } => None,
910                                 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
911                                     if param.hir_id == impl_hir_id {
912                                         Some(&param.bounds)
913                                     } else {
914                                         None
915                                     }
916                                 }
917                             })?;
918                         let bounds = bounds.first()?.span().to(bounds.last()?.span());
919                         let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
920
921                         err.multipart_suggestion(
922                             "try removing the generic parameter and using `impl Trait` instead",
923                             vec![
924                                 // delete generic parameters
925                                 (impl_m.generics.span, String::new()),
926                                 // replace param usage with `impl Trait`
927                                 (span, format!("impl {}", bounds)),
928                             ],
929                             Applicability::MaybeIncorrect,
930                         );
931                         Some(())
932                     })();
933                 }
934                 _ => unreachable!(),
935             }
936             err.emit();
937             error_found = true;
938         }
939     }
940     if error_found { Err(ErrorReported) } else { Ok(()) }
941 }
942
943 crate fn compare_const_impl<'tcx>(
944     tcx: TyCtxt<'tcx>,
945     impl_c: &ty::AssocItem,
946     impl_c_span: Span,
947     trait_c: &ty::AssocItem,
948     impl_trait_ref: ty::TraitRef<'tcx>,
949 ) {
950     debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
951
952     tcx.infer_ctxt().enter(|infcx| {
953         let param_env = tcx.param_env(impl_c.def_id);
954         let inh = Inherited::new(infcx, impl_c.def_id);
955         let infcx = &inh.infcx;
956
957         // The below is for the most part highly similar to the procedure
958         // for methods above. It is simpler in many respects, especially
959         // because we shouldn't really have to deal with lifetimes or
960         // predicates. In fact some of this should probably be put into
961         // shared functions because of DRY violations...
962         let trait_to_impl_substs = impl_trait_ref.substs;
963
964         // Create a parameter environment that represents the implementation's
965         // method.
966         let impl_c_hir_id = tcx.hir().as_local_hir_id(impl_c.def_id).unwrap();
967
968         // Compute placeholder form of impl and trait const tys.
969         let impl_ty = tcx.type_of(impl_c.def_id);
970         let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
971         let mut cause = ObligationCause::misc(impl_c_span, impl_c_hir_id);
972
973         // There is no "body" here, so just pass dummy id.
974         let impl_ty =
975             inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, &impl_ty);
976
977         debug!("compare_const_impl: impl_ty={:?}", impl_ty);
978
979         let trait_ty =
980             inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, &trait_ty);
981
982         debug!("compare_const_impl: trait_ty={:?}", trait_ty);
983
984         let err = infcx
985             .at(&cause, param_env)
986             .sup(trait_ty, impl_ty)
987             .map(|ok| inh.register_infer_ok_obligations(ok));
988
989         if let Err(terr) = err {
990             debug!(
991                 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
992                 impl_ty, trait_ty
993             );
994
995             // Locate the Span containing just the type of the offending impl
996             match tcx.hir().expect_impl_item(impl_c_hir_id).kind {
997                 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
998                 _ => bug!("{:?} is not a impl const", impl_c),
999             }
1000
1001             let mut diag = struct_span_err!(
1002                 tcx.sess,
1003                 cause.span,
1004                 E0326,
1005                 "implemented const `{}` has an incompatible type for \
1006                                              trait",
1007                 trait_c.ident
1008             );
1009
1010             let trait_c_hir_id = tcx.hir().as_local_hir_id(trait_c.def_id);
1011             let trait_c_span = trait_c_hir_id.map(|trait_c_hir_id| {
1012                 // Add a label to the Span containing just the type of the const
1013                 match tcx.hir().expect_trait_item(trait_c_hir_id).kind {
1014                     TraitItemKind::Const(ref ty, _) => ty.span,
1015                     _ => bug!("{:?} is not a trait const", trait_c),
1016                 }
1017             });
1018
1019             infcx.note_type_err(
1020                 &mut diag,
1021                 &cause,
1022                 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1023                 Some(infer::ValuePairs::Types(ExpectedFound {
1024                     expected: trait_ty,
1025                     found: impl_ty,
1026                 })),
1027                 &terr,
1028             );
1029             diag.emit();
1030         }
1031
1032         // Check that all obligations are satisfied by the implementation's
1033         // version.
1034         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
1035             infcx.report_fulfillment_errors(errors, None, false);
1036             return;
1037         }
1038
1039         let fcx = FnCtxt::new(&inh, param_env, impl_c_hir_id);
1040         fcx.regionck_item(impl_c_hir_id, impl_c_span, &[]);
1041     });
1042 }
1043
1044 crate fn compare_ty_impl<'tcx>(
1045     tcx: TyCtxt<'tcx>,
1046     impl_ty: &ty::AssocItem,
1047     impl_ty_span: Span,
1048     trait_ty: &ty::AssocItem,
1049     impl_trait_ref: ty::TraitRef<'tcx>,
1050     trait_item_span: Option<Span>,
1051 ) {
1052     debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1053
1054     let _: Result<(), ErrorReported> = (|| {
1055         compare_number_of_generics(tcx, impl_ty, impl_ty_span, trait_ty, trait_item_span)?;
1056
1057         compare_type_predicate_entailment(tcx, impl_ty, impl_ty_span, trait_ty, impl_trait_ref)
1058     })();
1059 }
1060
1061 /// The equivalent of [compare_predicate_entailment], but for associated types
1062 /// instead of associated functions.
1063 fn compare_type_predicate_entailment(
1064     tcx: TyCtxt<'tcx>,
1065     impl_ty: &ty::AssocItem,
1066     impl_ty_span: Span,
1067     trait_ty: &ty::AssocItem,
1068     impl_trait_ref: ty::TraitRef<'tcx>,
1069 ) -> Result<(), ErrorReported> {
1070     let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1071     let trait_to_impl_substs =
1072         impl_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1073
1074     let impl_ty_generics = tcx.generics_of(impl_ty.def_id);
1075     let trait_ty_generics = tcx.generics_of(trait_ty.def_id);
1076     let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1077     let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1078
1079     check_region_bounds_on_impl_item(
1080         tcx,
1081         impl_ty_span,
1082         impl_ty,
1083         trait_ty,
1084         &trait_ty_generics,
1085         &impl_ty_generics,
1086     )?;
1087
1088     let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1089
1090     if impl_ty_own_bounds.is_empty() {
1091         // Nothing to check.
1092         return Ok(());
1093     }
1094
1095     // This `HirId` should be used for the `body_id` field on each
1096     // `ObligationCause` (and the `FnCtxt`). This is what
1097     // `regionck_item` expects.
1098     let impl_ty_hir_id = tcx.hir().as_local_hir_id(impl_ty.def_id).unwrap();
1099     let cause = ObligationCause {
1100         span: impl_ty_span,
1101         body_id: impl_ty_hir_id,
1102         code: ObligationCauseCode::CompareImplTypeObligation {
1103             item_name: impl_ty.ident.name,
1104             impl_item_def_id: impl_ty.def_id,
1105             trait_item_def_id: trait_ty.def_id,
1106         },
1107     };
1108
1109     debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1110
1111     // The predicates declared by the impl definition, the trait and the
1112     // associated type in the trait are assumed.
1113     let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1114     let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1115     hybrid_preds
1116         .predicates
1117         .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1118
1119     debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1120
1121     let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1122     let param_env = ty::ParamEnv::new(
1123         tcx.intern_predicates(&hybrid_preds.predicates),
1124         Reveal::UserFacing,
1125         None,
1126     );
1127     let param_env = traits::normalize_param_env_or_error(
1128         tcx,
1129         impl_ty.def_id,
1130         param_env,
1131         normalize_cause.clone(),
1132     );
1133     tcx.infer_ctxt().enter(|infcx| {
1134         let inh = Inherited::new(infcx, impl_ty.def_id);
1135         let infcx = &inh.infcx;
1136
1137         debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds);
1138
1139         let mut selcx = traits::SelectionContext::new(&infcx);
1140
1141         for predicate in impl_ty_own_bounds.predicates {
1142             let traits::Normalized { value: predicate, obligations } =
1143                 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), &predicate);
1144
1145             inh.register_predicates(obligations);
1146             inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
1147         }
1148
1149         // Check that all obligations are satisfied by the implementation's
1150         // version.
1151         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
1152             infcx.report_fulfillment_errors(errors, None, false);
1153             return Err(ErrorReported);
1154         }
1155
1156         // Finally, resolve all regions. This catches wily misuses of
1157         // lifetime parameters.
1158         let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
1159         fcx.regionck_item(impl_ty_hir_id, impl_ty_span, &[]);
1160
1161         Ok(())
1162     })
1163 }
1164
1165 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
1166     match impl_item.kind {
1167         ty::AssocKind::Const => "const",
1168         ty::AssocKind::Method => "method",
1169         ty::AssocKind::Type | ty::AssocKind::OpaqueTy => "type",
1170     }
1171 }