]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/compare_method.rs
Rollup merge of #74213 - pickfire:patch-1, r=jonas-schievink
[rust.git] / src / librustc_typeck / check / compare_method.rs
1 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, ErrorReported};
2 use rustc_hir as hir;
3 use rustc_hir::def::{DefKind, Res};
4 use rustc_hir::intravisit;
5 use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind};
6 use rustc_infer::infer::{self, InferOk, TyCtxtInferExt};
7 use rustc_middle::ty;
8 use rustc_middle::ty::error::{ExpectedFound, TypeError};
9 use rustc_middle::ty::subst::{InternalSubsts, Subst, SubstsRef};
10 use rustc_middle::ty::util::ExplicitSelf;
11 use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt, WithConstness};
12 use rustc_span::Span;
13 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
14 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
15
16 use super::{potentially_plural_count, FnCtxt, Inherited};
17 use std::iter;
18
19 /// Checks that a method from an impl conforms to the signature of
20 /// the same method as declared in the trait.
21 ///
22 /// # Parameters
23 ///
24 /// - `impl_m`: type of the method we are checking
25 /// - `impl_m_span`: span to use for reporting errors
26 /// - `trait_m`: the method in the trait
27 /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
28
29 crate fn compare_impl_method<'tcx>(
30     tcx: TyCtxt<'tcx>,
31     impl_m: &ty::AssocItem,
32     impl_m_span: Span,
33     trait_m: &ty::AssocItem,
34     impl_trait_ref: ty::TraitRef<'tcx>,
35     trait_item_span: Option<Span>,
36 ) {
37     debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref);
38
39     let impl_m_span = tcx.sess.source_map().guess_head_span(impl_m_span);
40
41     if let Err(ErrorReported) = compare_self_type(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
42     {
43         return;
44     }
45
46     if let Err(ErrorReported) =
47         compare_number_of_generics(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
48     {
49         return;
50     }
51
52     if let Err(ErrorReported) =
53         compare_number_of_method_arguments(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
54     {
55         return;
56     }
57
58     if let Err(ErrorReported) = compare_synthetic_generics(tcx, impl_m, trait_m) {
59         return;
60     }
61
62     if let Err(ErrorReported) =
63         compare_predicate_entailment(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
64     {
65         return;
66     }
67 }
68
69 fn compare_predicate_entailment<'tcx>(
70     tcx: TyCtxt<'tcx>,
71     impl_m: &ty::AssocItem,
72     impl_m_span: Span,
73     trait_m: &ty::AssocItem,
74     impl_trait_ref: ty::TraitRef<'tcx>,
75 ) -> Result<(), ErrorReported> {
76     let trait_to_impl_substs = impl_trait_ref.substs;
77
78     // This node-id should be used for the `body_id` field on each
79     // `ObligationCause` (and the `FnCtxt`). This is what
80     // `regionck_item` expects.
81     let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id.expect_local());
82
83     // We sometimes modify the span further down.
84     let mut cause = ObligationCause::new(
85         impl_m_span,
86         impl_m_hir_id,
87         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_placeholder_substs = {'i => 'i0, U => U0, N => N0 }
122     //
123     // Now we can apply placeholder_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_placeholder_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_placeholder_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_placeholder_substs. We then build
151     // trait_to_placeholder_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_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
159
160     // Create mapping from trait to placeholder.
161     let trait_to_placeholder_substs =
162         impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container.id(), trait_to_impl_substs);
163     debug!("compare_impl_method: trait_to_placeholder_substs={:?}", trait_to_placeholder_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_placeholder_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.expect_local());
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_placeholder_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_placeholder_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             cause.make_mut().span = impl_err_span;
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().guess_head_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().guess_head_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.expect_local());
406     let (impl_m_output, impl_m_iter) = match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
407         ImplItemKind::Fn(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(def_id) = trait_m.def_id.as_local() {
416                 let trait_m_hir_id = tcx.hir().as_local_hir_id(def_id);
417                 let trait_m_iter = match tcx.hir().expect_trait_item(trait_m_hir_id).kind {
418                     TraitItemKind::Fn(ref trait_m_sig, _) => trait_m_sig.decl.inputs.iter(),
419                     _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
420                 };
421
422                 impl_m_iter
423                     .zip(trait_m_iter)
424                     .find(|&(ref impl_arg, ref trait_arg)| {
425                         match (&impl_arg.kind, &trait_arg.kind) {
426                             (
427                                 &hir::TyKind::Rptr(_, ref impl_mt),
428                                 &hir::TyKind::Rptr(_, ref trait_mt),
429                             )
430                             | (&hir::TyKind::Ptr(ref impl_mt), &hir::TyKind::Ptr(ref trait_mt)) => {
431                                 impl_mt.mutbl != trait_mt.mutbl
432                             }
433                             _ => false,
434                         }
435                     })
436                     .map(|(ref impl_arg, ref trait_arg)| (impl_arg.span, Some(trait_arg.span)))
437                     .unwrap_or_else(|| (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)))
438             } else {
439                 (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
440             }
441         }
442         TypeError::Sorts(ExpectedFound { .. }) => {
443             if let Some(def_id) = trait_m.def_id.as_local() {
444                 let trait_m_hir_id = tcx.hir().as_local_hir_id(def_id);
445                 let (trait_m_output, trait_m_iter) =
446                     match tcx.hir().expect_trait_item(trait_m_hir_id).kind {
447                         TraitItemKind::Fn(ref trait_m_sig, _) => {
448                             (&trait_m_sig.decl.output, trait_m_sig.decl.inputs.iter())
449                         }
450                         _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
451                     };
452
453                 let impl_iter = impl_sig.inputs().iter();
454                 let trait_iter = trait_sig.inputs().iter();
455                 impl_iter
456                     .zip(trait_iter)
457                     .zip(impl_m_iter)
458                     .zip(trait_m_iter)
459                     .find_map(|(((&impl_arg_ty, &trait_arg_ty), impl_arg), trait_arg)| match infcx
460                         .at(&cause, param_env)
461                         .sub(trait_arg_ty, impl_arg_ty)
462                     {
463                         Ok(_) => None,
464                         Err(_) => Some((impl_arg.span, Some(trait_arg.span))),
465                     })
466                     .unwrap_or_else(|| {
467                         if infcx
468                             .at(&cause, param_env)
469                             .sup(trait_sig.output(), impl_sig.output())
470                             .is_err()
471                         {
472                             (impl_m_output.span(), Some(trait_m_output.span()))
473                         } else {
474                             (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
475                         }
476                     })
477             } else {
478                 (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
479             }
480         }
481         _ => (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)),
482     }
483 }
484
485 fn compare_self_type<'tcx>(
486     tcx: TyCtxt<'tcx>,
487     impl_m: &ty::AssocItem,
488     impl_m_span: Span,
489     trait_m: &ty::AssocItem,
490     impl_trait_ref: ty::TraitRef<'tcx>,
491 ) -> Result<(), ErrorReported> {
492     // Try to give more informative error messages about self typing
493     // mismatches.  Note that any mismatch will also be detected
494     // below, where we construct a canonical function type that
495     // includes the self parameter as a normal parameter.  It's just
496     // that the error messages you get out of this code are a bit more
497     // inscrutable, particularly for cases where one method has no
498     // self.
499
500     let self_string = |method: &ty::AssocItem| {
501         let untransformed_self_ty = match method.container {
502             ty::ImplContainer(_) => impl_trait_ref.self_ty(),
503             ty::TraitContainer(_) => tcx.types.self_param,
504         };
505         let self_arg_ty = tcx.fn_sig(method.def_id).input(0).skip_binder();
506         let param_env = ty::ParamEnv::reveal_all();
507
508         tcx.infer_ctxt().enter(|infcx| {
509             let self_arg_ty =
510                 tcx.liberate_late_bound_regions(method.def_id, &ty::Binder::bind(self_arg_ty));
511             let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
512             match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
513                 ExplicitSelf::ByValue => "self".to_owned(),
514                 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
515                 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
516                 _ => format!("self: {}", self_arg_ty),
517             }
518         })
519     };
520
521     match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
522         (false, false) | (true, true) => {}
523
524         (false, true) => {
525             let self_descr = self_string(impl_m);
526             let mut err = struct_span_err!(
527                 tcx.sess,
528                 impl_m_span,
529                 E0185,
530                 "method `{}` has a `{}` declaration in the impl, but \
531                                             not in the trait",
532                 trait_m.ident,
533                 self_descr
534             );
535             err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
536             if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
537                 err.span_label(span, format!("trait method declared without `{}`", self_descr));
538             } else {
539                 err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
540             }
541             err.emit();
542             return Err(ErrorReported);
543         }
544
545         (true, false) => {
546             let self_descr = self_string(trait_m);
547             let mut err = struct_span_err!(
548                 tcx.sess,
549                 impl_m_span,
550                 E0186,
551                 "method `{}` has a `{}` declaration in the trait, but \
552                                             not in the impl",
553                 trait_m.ident,
554                 self_descr
555             );
556             err.span_label(impl_m_span, format!("expected `{}` in impl", self_descr));
557             if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
558                 err.span_label(span, format!("`{}` used in trait", self_descr));
559             } else {
560                 err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
561             }
562             err.emit();
563             return Err(ErrorReported);
564         }
565     }
566
567     Ok(())
568 }
569
570 fn compare_number_of_generics<'tcx>(
571     tcx: TyCtxt<'tcx>,
572     impl_: &ty::AssocItem,
573     _impl_span: Span,
574     trait_: &ty::AssocItem,
575     trait_span: Option<Span>,
576 ) -> Result<(), ErrorReported> {
577     let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
578     let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
579
580     let matchings = [
581         ("type", trait_own_counts.types, impl_own_counts.types),
582         ("const", trait_own_counts.consts, impl_own_counts.consts),
583     ];
584
585     let item_kind = assoc_item_kind_str(impl_);
586
587     let mut err_occurred = false;
588     for &(kind, trait_count, impl_count) in &matchings {
589         if impl_count != trait_count {
590             err_occurred = true;
591
592             let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
593                 let trait_hir_id = tcx.hir().as_local_hir_id(def_id);
594                 let trait_item = tcx.hir().expect_trait_item(trait_hir_id);
595                 if trait_item.generics.params.is_empty() {
596                     (Some(vec![trait_item.generics.span]), vec![])
597                 } else {
598                     let arg_spans: Vec<Span> =
599                         trait_item.generics.params.iter().map(|p| p.span).collect();
600                     let impl_trait_spans: Vec<Span> = trait_item
601                         .generics
602                         .params
603                         .iter()
604                         .filter_map(|p| match p.kind {
605                             GenericParamKind::Type {
606                                 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
607                                 ..
608                             } => Some(p.span),
609                             _ => None,
610                         })
611                         .collect();
612                     (Some(arg_spans), impl_trait_spans)
613                 }
614             } else {
615                 (trait_span.map(|s| vec![s]), vec![])
616             };
617
618             let impl_hir_id = tcx.hir().as_local_hir_id(impl_.def_id.expect_local());
619             let impl_item = tcx.hir().expect_impl_item(impl_hir_id);
620             let impl_item_impl_trait_spans: Vec<Span> = impl_item
621                 .generics
622                 .params
623                 .iter()
624                 .filter_map(|p| match p.kind {
625                     GenericParamKind::Type {
626                         synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
627                         ..
628                     } => Some(p.span),
629                     _ => None,
630                 })
631                 .collect();
632             let spans = impl_item.generics.spans();
633             let span = spans.primary_span();
634
635             let mut err = tcx.sess.struct_span_err_with_code(
636                 spans,
637                 &format!(
638                     "{} `{}` has {} {kind} parameter{} but its trait \
639                      declaration has {} {kind} parameter{}",
640                     item_kind,
641                     trait_.ident,
642                     impl_count,
643                     pluralize!(impl_count),
644                     trait_count,
645                     pluralize!(trait_count),
646                     kind = kind,
647                 ),
648                 DiagnosticId::Error("E0049".into()),
649             );
650
651             let mut suffix = None;
652
653             if let Some(spans) = trait_spans {
654                 let mut spans = spans.iter();
655                 if let Some(span) = spans.next() {
656                     err.span_label(
657                         *span,
658                         format!(
659                             "expected {} {} parameter{}",
660                             trait_count,
661                             kind,
662                             pluralize!(trait_count),
663                         ),
664                     );
665                 }
666                 for span in spans {
667                     err.span_label(*span, "");
668                 }
669             } else {
670                 suffix = Some(format!(", expected {}", trait_count));
671             }
672
673             if let Some(span) = span {
674                 err.span_label(
675                     span,
676                     format!(
677                         "found {} {} parameter{}{}",
678                         impl_count,
679                         kind,
680                         pluralize!(impl_count),
681                         suffix.unwrap_or_else(String::new),
682                     ),
683                 );
684             }
685
686             for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
687                 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
688             }
689
690             err.emit();
691         }
692     }
693
694     if err_occurred { Err(ErrorReported) } else { Ok(()) }
695 }
696
697 fn compare_number_of_method_arguments<'tcx>(
698     tcx: TyCtxt<'tcx>,
699     impl_m: &ty::AssocItem,
700     impl_m_span: Span,
701     trait_m: &ty::AssocItem,
702     trait_item_span: Option<Span>,
703 ) -> Result<(), ErrorReported> {
704     let impl_m_fty = tcx.fn_sig(impl_m.def_id);
705     let trait_m_fty = tcx.fn_sig(trait_m.def_id);
706     let trait_number_args = trait_m_fty.inputs().skip_binder().len();
707     let impl_number_args = impl_m_fty.inputs().skip_binder().len();
708     if trait_number_args != impl_number_args {
709         let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
710             let trait_id = tcx.hir().as_local_hir_id(def_id);
711             match tcx.hir().expect_trait_item(trait_id).kind {
712                 TraitItemKind::Fn(ref trait_m_sig, _) => {
713                     let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
714                     if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
715                         Some(if pos == 0 {
716                             arg.span
717                         } else {
718                             Span::new(
719                                 trait_m_sig.decl.inputs[0].span.lo(),
720                                 arg.span.hi(),
721                                 arg.span.ctxt(),
722                             )
723                         })
724                     } else {
725                         trait_item_span
726                     }
727                 }
728                 _ => bug!("{:?} is not a method", impl_m),
729             }
730         } else {
731             trait_item_span
732         };
733         let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id.expect_local());
734         let impl_span = match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
735             ImplItemKind::Fn(ref impl_m_sig, _) => {
736                 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
737                 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
738                     if pos == 0 {
739                         arg.span
740                     } else {
741                         Span::new(
742                             impl_m_sig.decl.inputs[0].span.lo(),
743                             arg.span.hi(),
744                             arg.span.ctxt(),
745                         )
746                     }
747                 } else {
748                     impl_m_span
749                 }
750             }
751             _ => bug!("{:?} is not a method", impl_m),
752         };
753         let mut err = struct_span_err!(
754             tcx.sess,
755             impl_span,
756             E0050,
757             "method `{}` has {} but the declaration in \
758                                         trait `{}` has {}",
759             trait_m.ident,
760             potentially_plural_count(impl_number_args, "parameter"),
761             tcx.def_path_str(trait_m.def_id),
762             trait_number_args
763         );
764         if let Some(trait_span) = trait_span {
765             err.span_label(
766                 trait_span,
767                 format!(
768                     "trait requires {}",
769                     potentially_plural_count(trait_number_args, "parameter")
770                 ),
771             );
772         } else {
773             err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
774         }
775         err.span_label(
776             impl_span,
777             format!(
778                 "expected {}, found {}",
779                 potentially_plural_count(trait_number_args, "parameter"),
780                 impl_number_args
781             ),
782         );
783         err.emit();
784         return Err(ErrorReported);
785     }
786
787     Ok(())
788 }
789
790 fn compare_synthetic_generics<'tcx>(
791     tcx: TyCtxt<'tcx>,
792     impl_m: &ty::AssocItem,
793     trait_m: &ty::AssocItem,
794 ) -> Result<(), ErrorReported> {
795     // FIXME(chrisvittal) Clean up this function, list of FIXME items:
796     //     1. Better messages for the span labels
797     //     2. Explanation as to what is going on
798     // If we get here, we already have the same number of generics, so the zip will
799     // be okay.
800     let mut error_found = false;
801     let impl_m_generics = tcx.generics_of(impl_m.def_id);
802     let trait_m_generics = tcx.generics_of(trait_m.def_id);
803     let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
804         GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
805         GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
806     });
807     let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
808         GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
809         GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
810     });
811     for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
812         impl_m_type_params.zip(trait_m_type_params)
813     {
814         if impl_synthetic != trait_synthetic {
815             let impl_hir_id = tcx.hir().as_local_hir_id(impl_def_id.expect_local());
816             let impl_span = tcx.hir().span(impl_hir_id);
817             let trait_span = tcx.def_span(trait_def_id);
818             let mut err = struct_span_err!(
819                 tcx.sess,
820                 impl_span,
821                 E0643,
822                 "method `{}` has incompatible signature for trait",
823                 trait_m.ident
824             );
825             err.span_label(trait_span, "declaration in trait here");
826             match (impl_synthetic, trait_synthetic) {
827                 // The case where the impl method uses `impl Trait` but the trait method uses
828                 // explicit generics
829                 (Some(hir::SyntheticTyParamKind::ImplTrait), None) => {
830                     err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
831                     (|| {
832                         // try taking the name from the trait impl
833                         // FIXME: this is obviously suboptimal since the name can already be used
834                         // as another generic argument
835                         let new_name = tcx.sess.source_map().span_to_snippet(trait_span).ok()?;
836                         let trait_m = tcx.hir().as_local_hir_id(trait_m.def_id.as_local()?);
837                         let trait_m = tcx.hir().trait_item(hir::TraitItemId { hir_id: trait_m });
838
839                         let impl_m = tcx.hir().as_local_hir_id(impl_m.def_id.as_local()?);
840                         let impl_m = tcx.hir().impl_item(hir::ImplItemId { hir_id: impl_m });
841
842                         // in case there are no generics, take the spot between the function name
843                         // and the opening paren of the argument list
844                         let new_generics_span =
845                             tcx.sess.source_map().generate_fn_name_span(impl_span)?.shrink_to_hi();
846                         // in case there are generics, just replace them
847                         let generics_span =
848                             impl_m.generics.span.substitute_dummy(new_generics_span);
849                         // replace with the generics from the trait
850                         let new_generics =
851                             tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
852
853                         err.multipart_suggestion(
854                             "try changing the `impl Trait` argument to a generic parameter",
855                             vec![
856                                 // replace `impl Trait` with `T`
857                                 (impl_span, new_name),
858                                 // replace impl method generics with trait method generics
859                                 // This isn't quite right, as users might have changed the names
860                                 // of the generics, but it works for the common case
861                                 (generics_span, new_generics),
862                             ],
863                             Applicability::MaybeIncorrect,
864                         );
865                         Some(())
866                     })();
867                 }
868                 // The case where the trait method uses `impl Trait`, but the impl method uses
869                 // explicit generics.
870                 (None, Some(hir::SyntheticTyParamKind::ImplTrait)) => {
871                     err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
872                     (|| {
873                         let impl_m = tcx.hir().as_local_hir_id(impl_m.def_id.as_local()?);
874                         let impl_m = tcx.hir().impl_item(hir::ImplItemId { hir_id: impl_m });
875                         let input_tys = match impl_m.kind {
876                             hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
877                             _ => unreachable!(),
878                         };
879                         struct Visitor(Option<Span>, hir::def_id::DefId);
880                         impl<'v> intravisit::Visitor<'v> for Visitor {
881                             fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
882                                 intravisit::walk_ty(self, ty);
883                                 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
884                                     ty.kind
885                                 {
886                                     if let Res::Def(DefKind::TyParam, def_id) = path.res {
887                                         if def_id == self.1 {
888                                             self.0 = Some(ty.span);
889                                         }
890                                     }
891                                 }
892                             }
893                             type Map = intravisit::ErasedMap<'v>;
894                             fn nested_visit_map(
895                                 &mut self,
896                             ) -> intravisit::NestedVisitorMap<Self::Map>
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.expect_local());
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.expect_local());
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::new(
972             impl_c_span,
973             impl_c_hir_id,
974             ObligationCauseCode::CompareImplConstObligation,
975         );
976
977         // There is no "body" here, so just pass dummy id.
978         let impl_ty =
979             inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, &impl_ty);
980
981         debug!("compare_const_impl: impl_ty={:?}", impl_ty);
982
983         let trait_ty =
984             inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, &trait_ty);
985
986         debug!("compare_const_impl: trait_ty={:?}", trait_ty);
987
988         let err = infcx
989             .at(&cause, param_env)
990             .sup(trait_ty, impl_ty)
991             .map(|ok| inh.register_infer_ok_obligations(ok));
992
993         if let Err(terr) = err {
994             debug!(
995                 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
996                 impl_ty, trait_ty
997             );
998
999             // Locate the Span containing just the type of the offending impl
1000             match tcx.hir().expect_impl_item(impl_c_hir_id).kind {
1001                 ImplItemKind::Const(ref ty, _) => cause.make_mut().span = ty.span,
1002                 _ => bug!("{:?} is not a impl const", impl_c),
1003             }
1004
1005             let mut diag = struct_span_err!(
1006                 tcx.sess,
1007                 cause.span,
1008                 E0326,
1009                 "implemented const `{}` has an incompatible type for \
1010                                              trait",
1011                 trait_c.ident
1012             );
1013
1014             let trait_c_hir_id =
1015                 trait_c.def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id));
1016             let trait_c_span = trait_c_hir_id.map(|trait_c_hir_id| {
1017                 // Add a label to the Span containing just the type of the const
1018                 match tcx.hir().expect_trait_item(trait_c_hir_id).kind {
1019                     TraitItemKind::Const(ref ty, _) => ty.span,
1020                     _ => bug!("{:?} is not a trait const", trait_c),
1021                 }
1022             });
1023
1024             infcx.note_type_err(
1025                 &mut diag,
1026                 &cause,
1027                 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1028                 Some(infer::ValuePairs::Types(ExpectedFound {
1029                     expected: trait_ty,
1030                     found: impl_ty,
1031                 })),
1032                 &terr,
1033             );
1034             diag.emit();
1035         }
1036
1037         // Check that all obligations are satisfied by the implementation's
1038         // version.
1039         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
1040             infcx.report_fulfillment_errors(errors, None, false);
1041             return;
1042         }
1043
1044         let fcx = FnCtxt::new(&inh, param_env, impl_c_hir_id);
1045         fcx.regionck_item(impl_c_hir_id, impl_c_span, &[]);
1046     });
1047 }
1048
1049 crate fn compare_ty_impl<'tcx>(
1050     tcx: TyCtxt<'tcx>,
1051     impl_ty: &ty::AssocItem,
1052     impl_ty_span: Span,
1053     trait_ty: &ty::AssocItem,
1054     impl_trait_ref: ty::TraitRef<'tcx>,
1055     trait_item_span: Option<Span>,
1056 ) {
1057     debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1058
1059     let _: Result<(), ErrorReported> = (|| {
1060         compare_number_of_generics(tcx, impl_ty, impl_ty_span, trait_ty, trait_item_span)?;
1061
1062         compare_type_predicate_entailment(tcx, impl_ty, impl_ty_span, trait_ty, impl_trait_ref)?;
1063
1064         compare_projection_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
1065     })();
1066 }
1067
1068 /// The equivalent of [compare_predicate_entailment], but for associated types
1069 /// instead of associated functions.
1070 fn compare_type_predicate_entailment<'tcx>(
1071     tcx: TyCtxt<'tcx>,
1072     impl_ty: &ty::AssocItem,
1073     impl_ty_span: Span,
1074     trait_ty: &ty::AssocItem,
1075     impl_trait_ref: ty::TraitRef<'tcx>,
1076 ) -> Result<(), ErrorReported> {
1077     let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1078     let trait_to_impl_substs =
1079         impl_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1080
1081     let impl_ty_generics = tcx.generics_of(impl_ty.def_id);
1082     let trait_ty_generics = tcx.generics_of(trait_ty.def_id);
1083     let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1084     let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1085
1086     check_region_bounds_on_impl_item(
1087         tcx,
1088         impl_ty_span,
1089         impl_ty,
1090         trait_ty,
1091         &trait_ty_generics,
1092         &impl_ty_generics,
1093     )?;
1094
1095     let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1096
1097     if impl_ty_own_bounds.is_empty() {
1098         // Nothing to check.
1099         return Ok(());
1100     }
1101
1102     // This `HirId` should be used for the `body_id` field on each
1103     // `ObligationCause` (and the `FnCtxt`). This is what
1104     // `regionck_item` expects.
1105     let impl_ty_hir_id = tcx.hir().as_local_hir_id(impl_ty.def_id.expect_local());
1106     let cause = ObligationCause::new(
1107         impl_ty_span,
1108         impl_ty_hir_id,
1109         ObligationCauseCode::CompareImplTypeObligation {
1110             item_name: impl_ty.ident.name,
1111             impl_item_def_id: impl_ty.def_id,
1112             trait_item_def_id: trait_ty.def_id,
1113         },
1114     );
1115
1116     debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1117
1118     // The predicates declared by the impl definition, the trait and the
1119     // associated type in the trait are assumed.
1120     let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1121     let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1122     hybrid_preds
1123         .predicates
1124         .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1125
1126     debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1127
1128     let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1129     let param_env = ty::ParamEnv::new(
1130         tcx.intern_predicates(&hybrid_preds.predicates),
1131         Reveal::UserFacing,
1132         None,
1133     );
1134     let param_env = traits::normalize_param_env_or_error(
1135         tcx,
1136         impl_ty.def_id,
1137         param_env,
1138         normalize_cause.clone(),
1139     );
1140     tcx.infer_ctxt().enter(|infcx| {
1141         let inh = Inherited::new(infcx, impl_ty.def_id.expect_local());
1142         let infcx = &inh.infcx;
1143
1144         debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1145
1146         let mut selcx = traits::SelectionContext::new(&infcx);
1147
1148         for predicate in impl_ty_own_bounds.predicates {
1149             let traits::Normalized { value: predicate, obligations } =
1150                 traits::normalize(&mut selcx, param_env, normalize_cause.clone(), &predicate);
1151
1152             inh.register_predicates(obligations);
1153             inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
1154         }
1155
1156         // Check that all obligations are satisfied by the implementation's
1157         // version.
1158         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
1159             infcx.report_fulfillment_errors(errors, None, false);
1160             return Err(ErrorReported);
1161         }
1162
1163         // Finally, resolve all regions. This catches wily misuses of
1164         // lifetime parameters.
1165         let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
1166         fcx.regionck_item(impl_ty_hir_id, impl_ty_span, &[]);
1167
1168         Ok(())
1169     })
1170 }
1171
1172 /// Validate that `ProjectionCandidate`s created for this associated type will
1173 /// be valid.
1174 ///
1175 /// Usually given
1176 ///
1177 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1178 ///
1179 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1180 /// impl is well-formed we have to prove `S: Copy`.
1181 ///
1182 /// For default associated types the normalization is not possible (the value
1183 /// from the impl could be overridden). We also can't normalize generic
1184 /// associated types (yet) because they contain bound parameters.
1185 fn compare_projection_bounds<'tcx>(
1186     tcx: TyCtxt<'tcx>,
1187     trait_ty: &ty::AssocItem,
1188     impl_ty: &ty::AssocItem,
1189     impl_ty_span: Span,
1190     impl_trait_ref: ty::TraitRef<'tcx>,
1191 ) -> Result<(), ErrorReported> {
1192     let have_gats = tcx.features().generic_associated_types;
1193     if impl_ty.defaultness.is_final() && !have_gats {
1194         // For "final", non-generic associate type implementations, we
1195         // don't need this as described above.
1196         return Ok(());
1197     }
1198
1199     let param_env = tcx.param_env(impl_ty.def_id);
1200
1201     // Given
1202     //
1203     // impl<A, B> Foo<u32> for (A, B) {
1204     //     type Bar<C> =...
1205     // }
1206     //
1207     // - `impl_substs` would be `[A, B, C]`
1208     // - `rebased_substs` would be `[(A, B), u32, C]`, combining the substs from
1209     //    the *trait* with the generic associated type parameters.
1210     let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1211     let rebased_substs =
1212         impl_ty_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1213     let impl_ty_value = tcx.type_of(impl_ty.def_id);
1214
1215     // Map the predicate from the trait to the corresponding one for the impl.
1216     // For example:
1217     //
1218     // trait X<A> { type Y<'a>: PartialEq<A> } impl X for T { type Y<'a> = &'a S; }
1219     // impl<'x> X<&'x u32> for () { type Y<'c> = &'c u32; }
1220     //
1221     // For the `for<'a> <<Self as X<A>>::Y<'a>: PartialEq<A>` bound, this
1222     // function would translate and partially normalize
1223     // `[<Self as X<A>>::Y<'a>, A]` to `[&'a u32, &'x u32]`.
1224     let translate_predicate_substs = move |predicate_substs: SubstsRef<'tcx>| {
1225         tcx.mk_substs(
1226             iter::once(impl_ty_value.into())
1227                 .chain(predicate_substs[1..].iter().map(|s| s.subst(tcx, rebased_substs))),
1228         )
1229     };
1230
1231     tcx.infer_ctxt().enter(move |infcx| {
1232         let inh = Inherited::new(infcx, impl_ty.def_id.expect_local());
1233         let infcx = &inh.infcx;
1234         let mut selcx = traits::SelectionContext::new(&infcx);
1235
1236         let impl_ty_hir_id = tcx.hir().as_local_hir_id(impl_ty.def_id.expect_local());
1237         let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1238         let cause = ObligationCause::new(
1239             impl_ty_span,
1240             impl_ty_hir_id,
1241             ObligationCauseCode::ItemObligation(trait_ty.def_id),
1242         );
1243
1244         let predicates = tcx.projection_predicates(trait_ty.def_id);
1245
1246         debug!("compare_projection_bounds: projection_predicates={:?}", predicates);
1247
1248         for predicate in predicates {
1249             let concrete_ty_predicate = match predicate.kind() {
1250                 ty::PredicateKind::Trait(poly_tr, c) => poly_tr
1251                     .map_bound(|tr| {
1252                         let trait_substs = translate_predicate_substs(tr.trait_ref.substs);
1253                         ty::TraitRef { def_id: tr.def_id(), substs: trait_substs }
1254                     })
1255                     .with_constness(*c)
1256                     .to_predicate(tcx),
1257                 ty::PredicateKind::Projection(poly_projection) => poly_projection
1258                     .map_bound(|projection| {
1259                         let projection_substs =
1260                             translate_predicate_substs(projection.projection_ty.substs);
1261                         ty::ProjectionPredicate {
1262                             projection_ty: ty::ProjectionTy {
1263                                 substs: projection_substs,
1264                                 item_def_id: projection.projection_ty.item_def_id,
1265                             },
1266                             ty: projection.ty.subst(tcx, rebased_substs),
1267                         }
1268                     })
1269                     .to_predicate(tcx),
1270                 ty::PredicateKind::TypeOutlives(poly_outlives) => poly_outlives
1271                     .map_bound(|outlives| {
1272                         ty::OutlivesPredicate(impl_ty_value, outlives.1.subst(tcx, rebased_substs))
1273                     })
1274                     .to_predicate(tcx),
1275                 _ => bug!("unexepected projection predicate kind: `{:?}`", predicate),
1276             };
1277
1278             let traits::Normalized { value: normalized_predicate, obligations } = traits::normalize(
1279                 &mut selcx,
1280                 param_env,
1281                 normalize_cause.clone(),
1282                 &concrete_ty_predicate,
1283             );
1284
1285             debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
1286
1287             inh.register_predicates(obligations);
1288             inh.register_predicate(traits::Obligation::new(
1289                 cause.clone(),
1290                 param_env,
1291                 normalized_predicate,
1292             ));
1293         }
1294
1295         // Check that all obligations are satisfied by the implementation's
1296         // version.
1297         if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
1298             infcx.report_fulfillment_errors(errors, None, false);
1299             return Err(ErrorReported);
1300         }
1301
1302         // Finally, resolve all regions. This catches wily misuses of
1303         // lifetime parameters.
1304         let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
1305         fcx.regionck_item(impl_ty_hir_id, impl_ty_span, &[]);
1306
1307         Ok(())
1308     })
1309 }
1310
1311 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
1312     match impl_item.kind {
1313         ty::AssocKind::Const => "const",
1314         ty::AssocKind::Fn => "method",
1315         ty::AssocKind::Type => "type",
1316     }
1317 }