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