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