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