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