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