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