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