1 use super::potentially_plural_count;
2 use crate::errors::LifetimesOrBoundsMismatchOnTrait;
3 use crate::outlives::outlives_bounds::InferCtxtExt as _;
4 use rustc_data_structures::fx::FxHashSet;
5 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, ErrorGuaranteed};
7 use rustc_hir::def::{DefKind, Res};
8 use rustc_hir::intravisit;
9 use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind};
10 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
11 use rustc_infer::infer::{self, TyCtxtInferExt};
12 use rustc_infer::traits::util;
13 use rustc_middle::ty::error::{ExpectedFound, TypeError};
14 use rustc_middle::ty::subst::{InternalSubsts, Subst};
15 use rustc_middle::ty::util::ExplicitSelf;
16 use rustc_middle::ty::{self, DefIdTree};
17 use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt};
19 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
20 use rustc_trait_selection::traits::{
21 self, ObligationCause, ObligationCauseCode, ObligationCtxt, Reveal,
25 /// Checks that a method from an impl conforms to the signature of
26 /// the same method as declared in the trait.
30 /// - `impl_m`: type of the method we are checking
31 /// - `impl_m_span`: span to use for reporting errors
32 /// - `trait_m`: the method in the trait
33 /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
34 pub(crate) fn compare_impl_method<'tcx>(
36 impl_m: &ty::AssocItem,
37 trait_m: &ty::AssocItem,
38 impl_trait_ref: ty::TraitRef<'tcx>,
39 trait_item_span: Option<Span>,
41 debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref);
43 let impl_m_span = tcx.def_span(impl_m.def_id);
45 if let Err(_) = compare_self_type(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref) {
49 if let Err(_) = compare_number_of_generics(tcx, impl_m, impl_m_span, trait_m, trait_item_span) {
53 if let Err(_) = compare_generic_param_kinds(tcx, impl_m, trait_m) {
58 compare_number_of_method_arguments(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
63 if let Err(_) = compare_synthetic_generics(tcx, impl_m, trait_m) {
67 if let Err(_) = compare_predicate_entailment(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
73 /// This function is best explained by example. Consider a trait:
75 /// trait Trait<'t, T> {
77 /// fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
82 /// impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
84 /// fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo;
87 /// We wish to decide if those two method types are compatible.
88 /// For this we have to show that, assuming the bounds of the impl hold, the
89 /// bounds of `trait_m` imply the bounds of `impl_m`.
91 /// We start out with `trait_to_impl_substs`, that maps the trait
92 /// type parameters to impl type parameters. This is taken from the
93 /// impl trait reference:
95 /// trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
97 /// We create a mapping `dummy_substs` that maps from the impl type
98 /// parameters to fresh types and regions. For type parameters,
99 /// this is the identity transform, but we could as well use any
100 /// placeholder types. For regions, we convert from bound to free
101 /// regions (Note: but only early-bound regions, i.e., those
102 /// declared on the impl or used in type parameter bounds).
104 /// impl_to_placeholder_substs = {'i => 'i0, U => U0, N => N0 }
106 /// Now we can apply `placeholder_substs` to the type of the impl method
107 /// to yield a new function type in terms of our fresh, placeholder
110 /// <'b> fn(t: &'i0 U0, m: &'b) -> Foo
112 /// We now want to extract and substitute the type of the *trait*
113 /// method and compare it. To do so, we must create a compound
114 /// substitution by combining `trait_to_impl_substs` and
115 /// `impl_to_placeholder_substs`, and also adding a mapping for the method
116 /// type parameters. We extend the mapping to also include
117 /// the method parameters.
119 /// trait_to_placeholder_substs = { T => &'i0 U0, Self => Foo, M => N0 }
121 /// Applying this to the trait method type yields:
123 /// <'a> fn(t: &'i0 U0, m: &'a) -> Foo
125 /// This type is also the same but the name of the bound region (`'a`
126 /// vs `'b`). However, the normal subtyping rules on fn types handle
127 /// this kind of equivalency just fine.
129 /// We now use these substitutions to ensure that all declared bounds are
130 /// satisfied by the implementation's method.
132 /// We do this by creating a parameter environment which contains a
133 /// substitution corresponding to `impl_to_placeholder_substs`. We then build
134 /// `trait_to_placeholder_substs` and use it to convert the predicates contained
135 /// in the `trait_m` generics to the placeholder form.
137 /// Finally we register each of these predicates as an obligation and check that
139 fn compare_predicate_entailment<'tcx>(
141 impl_m: &ty::AssocItem,
143 trait_m: &ty::AssocItem,
144 impl_trait_ref: ty::TraitRef<'tcx>,
145 ) -> Result<(), ErrorGuaranteed> {
146 let trait_to_impl_substs = impl_trait_ref.substs;
148 // This node-id should be used for the `body_id` field on each
149 // `ObligationCause` (and the `FnCtxt`).
151 // FIXME(@lcnr): remove that after removing `cause.body_id` from
153 let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
154 // We sometimes modify the span further down.
155 let mut cause = ObligationCause::new(
158 ObligationCauseCode::CompareImplItemObligation {
159 impl_item_def_id: impl_m.def_id.expect_local(),
160 trait_item_def_id: trait_m.def_id,
165 // Create mapping from impl to placeholder.
166 let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
168 // Create mapping from trait to placeholder.
169 let trait_to_placeholder_substs =
170 impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs);
171 debug!("compare_impl_method: trait_to_placeholder_substs={:?}", trait_to_placeholder_substs);
173 let impl_m_generics = tcx.generics_of(impl_m.def_id);
174 let trait_m_generics = tcx.generics_of(trait_m.def_id);
175 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
176 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
178 // Check region bounds.
179 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, &trait_m_generics, &impl_m_generics)?;
181 // Create obligations for each predicate declared by the impl
182 // definition in the context of the trait's parameter
183 // environment. We can't just use `impl_env.caller_bounds`,
184 // however, because we want to replace all late-bound regions with
186 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
187 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
189 debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);
191 // This is the only tricky bit of the new way we check implementation methods
192 // We need to build a set of predicates where only the method-level bounds
193 // are from the trait and we assume all other bounds from the implementation
194 // to be previously satisfied.
196 // We then register the obligations from the impl_m and check to see
197 // if all constraints hold.
200 .extend(trait_m_predicates.instantiate_own(tcx, trait_to_placeholder_substs).predicates);
202 // Construct trait parameter environment and then shift it into the placeholder viewpoint.
203 // The key step here is to update the caller_bounds's predicates to be
204 // the new hybrid bounds we computed.
205 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
206 let param_env = ty::ParamEnv::new(
207 tcx.intern_predicates(&hybrid_preds.predicates),
209 hir::Constness::NotConst,
211 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
213 tcx.infer_ctxt().enter(|ref infcx| {
214 let ocx = ObligationCtxt::new(infcx);
216 debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds());
218 let mut selcx = traits::SelectionContext::new(&infcx);
219 let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs);
220 for (predicate, span) in iter::zip(impl_m_own_bounds.predicates, impl_m_own_bounds.spans) {
221 let normalize_cause = traits::ObligationCause::misc(span, impl_m_hir_id);
222 let traits::Normalized { value: predicate, obligations } =
223 traits::normalize(&mut selcx, param_env, normalize_cause, predicate);
225 ocx.register_obligations(obligations);
226 let cause = ObligationCause::new(
229 ObligationCauseCode::CompareImplItemObligation {
230 impl_item_def_id: impl_m.def_id.expect_local(),
231 trait_item_def_id: trait_m.def_id,
235 ocx.register_obligation(traits::Obligation::new(cause, param_env, predicate));
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`.
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
251 // Compute placeholder form of impl and trait method tys.
254 let mut wf_tys = FxHashSet::default();
256 let impl_sig = infcx.replace_bound_vars_with_fresh_vars(
258 infer::HigherRankedType,
259 tcx.fn_sig(impl_m.def_id),
262 let norm_cause = ObligationCause::misc(impl_m_span, impl_m_hir_id);
263 let impl_sig = ocx.normalize(norm_cause.clone(), param_env, impl_sig);
264 let impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(impl_sig));
265 debug!("compare_impl_method: impl_fty={:?}", impl_fty);
267 let trait_sig = tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs);
268 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
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 = ocx.normalize(norm_cause, param_env, trait_sig);
274 // We also have to add the normalized trait signature
275 // as we don't normalize during implied bounds computation.
276 wf_tys.extend(trait_sig.inputs_and_output.iter());
277 let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));
279 debug!("compare_impl_method: trait_fty={:?}", trait_fty);
281 // FIXME: We'd want to keep more accurate spans than "the method signature" when
282 // processing the comparison between the trait and impl fn, but we sadly lose them
283 // and point at the whole signature when a trait bound or specific input or output
284 // type would be more appropriate. In other places we have a `Vec<Span>`
285 // corresponding to their `Vec<Predicate>`, but we don't have that here.
286 // Fixing this would improve the output of test `issue-83765.rs`.
287 let sub_result = infcx
288 .at(&cause, param_env)
289 .sup(trait_fty, impl_fty)
290 .map(|infer_ok| ocx.register_infer_ok_obligations(infer_ok));
292 if let Err(terr) = sub_result {
293 debug!("sub_types failed: impl ty {:?}, trait ty {:?}", impl_fty, trait_fty);
295 let (impl_err_span, trait_err_span) =
296 extract_spans_for_error_reporting(&infcx, terr, &cause, impl_m, trait_m);
298 cause.span = impl_err_span;
300 let mut diag = struct_span_err!(
304 "method `{}` has an incompatible type for trait",
308 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
309 if trait_m.fn_has_self_parameter =>
311 let ty = trait_sig.inputs()[0];
312 let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty())
314 ExplicitSelf::ByValue => "self".to_owned(),
315 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
316 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => {
317 "&mut self".to_owned()
319 _ => format!("self: {ty}"),
322 // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
323 // span points only at the type `Box<Self`>, but we want to cover the whole
324 // argument pattern and type.
325 let span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
326 ImplItemKind::Fn(ref sig, body) => tcx
328 .body_param_names(body)
329 .zip(sig.decl.inputs.iter())
330 .map(|(param, ty)| param.span.to(ty.span))
332 .unwrap_or(impl_err_span),
333 _ => bug!("{:?} is not a method", impl_m),
336 diag.span_suggestion(
338 "change the self-receiver type to match the trait",
340 Applicability::MachineApplicable,
343 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
344 if trait_sig.inputs().len() == *i {
345 // Suggestion to change output type. We do not suggest in `async` functions
346 // to avoid complex logic or incorrect output.
347 match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
348 ImplItemKind::Fn(ref sig, _)
349 if sig.header.asyncness == hir::IsAsync::NotAsync =>
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);
358 hir::FnRetTy::Return(hir_ty) => {
359 let sugg = trait_sig.output();
360 diag.span_suggestion(hir_ty.span, msg, sugg, ap);
366 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
367 diag.span_suggestion(
369 "change the parameter type to match the trait",
371 Applicability::MachineApplicable,
381 trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
382 Some(infer::ValuePairs::Terms(ExpectedFound {
383 expected: trait_fty.into(),
384 found: impl_fty.into(),
391 return Err(diag.emit());
394 // Check that all obligations are satisfied by the implementation's
396 let errors = ocx.select_all_or_error();
397 if !errors.is_empty() {
398 let reported = infcx.report_fulfillment_errors(&errors, None, false);
399 return Err(reported);
402 // Finally, resolve all regions. This catches wily misuses of
403 // lifetime parameters.
404 let outlives_environment = OutlivesEnvironment::with_bounds(
407 infcx.implied_bounds_tys(param_env, impl_m_hir_id, wf_tys),
409 infcx.check_region_obligations_and_report_errors(
410 impl_m.def_id.expect_local(),
411 &outlives_environment,
418 fn check_region_bounds_on_impl_item<'tcx>(
420 impl_m: &ty::AssocItem,
421 trait_m: &ty::AssocItem,
422 trait_generics: &ty::Generics,
423 impl_generics: &ty::Generics,
424 ) -> Result<(), ErrorGuaranteed> {
425 let trait_params = trait_generics.own_counts().lifetimes;
426 let impl_params = impl_generics.own_counts().lifetimes;
429 "check_region_bounds_on_impl_item: \
430 trait_generics={:?} \
432 trait_generics, impl_generics
435 // Must have same number of early-bound lifetime parameters.
436 // Unfortunately, if the user screws up the bounds, then this
437 // will change classification between early and late. E.g.,
438 // if in trait we have `<'a,'b:'a>`, and in impl we just have
439 // `<'a,'b>`, then we have 2 early-bound lifetime parameters
440 // in trait but 0 in the impl. But if we report "expected 2
441 // but found 0" it's confusing, because it looks like there
442 // are zero. Since I don't quite know how to phrase things at
443 // the moment, give a kind of vague error message.
444 if trait_params != impl_params {
447 .get_generics(impl_m.def_id.expect_local())
448 .expect("expected impl item to have generics or else we can't compare them")
450 let generics_span = if let Some(local_def_id) = trait_m.def_id.as_local() {
453 .get_generics(local_def_id)
454 .expect("expected trait item to have generics or else we can't compare them")
461 let reported = tcx.sess.emit_err(LifetimesOrBoundsMismatchOnTrait {
463 item_kind: assoc_item_kind_str(impl_m),
464 ident: impl_m.ident(tcx),
467 return Err(reported);
473 #[instrument(level = "debug", skip(infcx))]
474 fn extract_spans_for_error_reporting<'a, 'tcx>(
475 infcx: &infer::InferCtxt<'a, 'tcx>,
477 cause: &ObligationCause<'tcx>,
478 impl_m: &ty::AssocItem,
479 trait_m: &ty::AssocItem,
480 ) -> (Span, Option<Span>) {
482 let mut impl_args = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
483 ImplItemKind::Fn(ref sig, _) => {
484 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
486 _ => bug!("{:?} is not a method", impl_m),
489 trait_m.def_id.as_local().map(|def_id| match tcx.hir().expect_trait_item(def_id).kind {
490 TraitItemKind::Fn(ref sig, _) => {
491 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
493 _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
497 TypeError::ArgumentMutability(i) => {
498 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
500 TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
501 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
503 _ => (cause.span(), tcx.hir().span_if_local(trait_m.def_id)),
507 fn compare_self_type<'tcx>(
509 impl_m: &ty::AssocItem,
511 trait_m: &ty::AssocItem,
512 impl_trait_ref: ty::TraitRef<'tcx>,
513 ) -> Result<(), ErrorGuaranteed> {
514 // Try to give more informative error messages about self typing
515 // mismatches. Note that any mismatch will also be detected
516 // below, where we construct a canonical function type that
517 // includes the self parameter as a normal parameter. It's just
518 // that the error messages you get out of this code are a bit more
519 // inscrutable, particularly for cases where one method has no
522 let self_string = |method: &ty::AssocItem| {
523 let untransformed_self_ty = match method.container {
524 ty::ImplContainer => impl_trait_ref.self_ty(),
525 ty::TraitContainer => tcx.types.self_param,
527 let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
528 let param_env = ty::ParamEnv::reveal_all();
530 tcx.infer_ctxt().enter(|infcx| {
531 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
532 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
533 match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
534 ExplicitSelf::ByValue => "self".to_owned(),
535 ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
536 ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
537 _ => format!("self: {self_arg_ty}"),
542 match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
543 (false, false) | (true, true) => {}
546 let self_descr = self_string(impl_m);
547 let mut err = struct_span_err!(
551 "method `{}` has a `{}` declaration in the impl, but not in the trait",
555 err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
556 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
557 err.span_label(span, format!("trait method declared without `{self_descr}`"));
559 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
561 let reported = err.emit();
562 return Err(reported);
566 let self_descr = self_string(trait_m);
567 let mut err = struct_span_err!(
571 "method `{}` has a `{}` declaration in the trait, but not in the impl",
575 err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
576 if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
577 err.span_label(span, format!("`{self_descr}` used in trait"));
579 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
581 let reported = err.emit();
582 return Err(reported);
589 /// Checks that the number of generics on a given assoc item in a trait impl is the same
590 /// as the number of generics on the respective assoc item in the trait definition.
592 /// For example this code emits the errors in the following code:
599 /// impl Trait for () {
602 /// type Assoc = u32;
607 /// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
608 /// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
609 /// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
610 fn compare_number_of_generics<'tcx>(
612 impl_: &ty::AssocItem,
614 trait_: &ty::AssocItem,
615 trait_span: Option<Span>,
616 ) -> Result<(), ErrorGuaranteed> {
617 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
618 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
620 // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
621 // in `compare_generic_param_kinds` which will give a nicer error message than something like:
622 // "expected 1 type parameter, found 0 type parameters"
623 if (trait_own_counts.types + trait_own_counts.consts)
624 == (impl_own_counts.types + impl_own_counts.consts)
630 ("type", trait_own_counts.types, impl_own_counts.types),
631 ("const", trait_own_counts.consts, impl_own_counts.consts),
634 let item_kind = assoc_item_kind_str(impl_);
636 let mut err_occurred = None;
637 for (kind, trait_count, impl_count) in matchings {
638 if impl_count != trait_count {
639 let arg_spans = |kind: ty::AssocKind, generics: &hir::Generics<'_>| {
640 let mut spans = generics
643 .filter(|p| match p.kind {
644 hir::GenericParamKind::Lifetime {
645 kind: hir::LifetimeParamKind::Elided,
647 // A fn can have an arbitrary number of extra elided lifetimes for the
649 !matches!(kind, ty::AssocKind::Fn)
654 .collect::<Vec<Span>>();
655 if spans.is_empty() {
656 spans = vec![generics.span]
660 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
661 let trait_item = tcx.hir().expect_trait_item(def_id);
662 let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics);
663 let impl_trait_spans: Vec<Span> = trait_item
667 .filter_map(|p| match p.kind {
668 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
672 (Some(arg_spans), impl_trait_spans)
674 (trait_span.map(|s| vec![s]), vec![])
677 let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local());
678 let impl_item_impl_trait_spans: Vec<Span> = impl_item
682 .filter_map(|p| match p.kind {
683 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
687 let spans = arg_spans(impl_.kind, impl_item.generics);
688 let span = spans.first().copied();
690 let mut err = tcx.sess.struct_span_err_with_code(
693 "{} `{}` has {} {kind} parameter{} but its trait \
694 declaration has {} {kind} parameter{}",
698 pluralize!(impl_count),
700 pluralize!(trait_count),
703 DiagnosticId::Error("E0049".into()),
706 let mut suffix = None;
708 if let Some(spans) = trait_spans {
709 let mut spans = spans.iter();
710 if let Some(span) = spans.next() {
714 "expected {} {} parameter{}",
717 pluralize!(trait_count),
722 err.span_label(*span, "");
725 suffix = Some(format!(", expected {trait_count}"));
728 if let Some(span) = span {
732 "found {} {} parameter{}{}",
735 pluralize!(impl_count),
736 suffix.unwrap_or_else(String::new),
741 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
742 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
745 let reported = err.emit();
746 err_occurred = Some(reported);
750 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
753 fn compare_number_of_method_arguments<'tcx>(
755 impl_m: &ty::AssocItem,
757 trait_m: &ty::AssocItem,
758 trait_item_span: Option<Span>,
759 ) -> Result<(), ErrorGuaranteed> {
760 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
761 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
762 let trait_number_args = trait_m_fty.inputs().skip_binder().len();
763 let impl_number_args = impl_m_fty.inputs().skip_binder().len();
764 if trait_number_args != impl_number_args {
765 let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
766 match tcx.hir().expect_trait_item(def_id).kind {
767 TraitItemKind::Fn(ref trait_m_sig, _) => {
768 let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
769 if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
773 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
779 _ => bug!("{:?} is not a method", impl_m),
784 let impl_span = match tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind {
785 ImplItemKind::Fn(ref impl_m_sig, _) => {
786 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
787 if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
791 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
797 _ => bug!("{:?} is not a method", impl_m),
799 let mut err = struct_span_err!(
803 "method `{}` has {} but the declaration in trait `{}` has {}",
805 potentially_plural_count(impl_number_args, "parameter"),
806 tcx.def_path_str(trait_m.def_id),
809 if let Some(trait_span) = trait_span {
814 potentially_plural_count(trait_number_args, "parameter")
818 err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
823 "expected {}, found {}",
824 potentially_plural_count(trait_number_args, "parameter"),
828 let reported = err.emit();
829 return Err(reported);
835 fn compare_synthetic_generics<'tcx>(
837 impl_m: &ty::AssocItem,
838 trait_m: &ty::AssocItem,
839 ) -> Result<(), ErrorGuaranteed> {
840 // FIXME(chrisvittal) Clean up this function, list of FIXME items:
841 // 1. Better messages for the span labels
842 // 2. Explanation as to what is going on
843 // If we get here, we already have the same number of generics, so the zip will
845 let mut error_found = None;
846 let impl_m_generics = tcx.generics_of(impl_m.def_id);
847 let trait_m_generics = tcx.generics_of(trait_m.def_id);
848 let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
849 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
850 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
852 let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
853 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
854 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
856 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
857 iter::zip(impl_m_type_params, trait_m_type_params)
859 if impl_synthetic != trait_synthetic {
860 let impl_def_id = impl_def_id.expect_local();
861 let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_def_id);
862 let impl_span = tcx.hir().span(impl_hir_id);
863 let trait_span = tcx.def_span(trait_def_id);
864 let mut err = struct_span_err!(
868 "method `{}` has incompatible signature for trait",
871 err.span_label(trait_span, "declaration in trait here");
872 match (impl_synthetic, trait_synthetic) {
873 // The case where the impl method uses `impl Trait` but the trait method uses
876 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
878 // try taking the name from the trait impl
879 // FIXME: this is obviously suboptimal since the name can already be used
880 // as another generic argument
881 let new_name = tcx.sess.source_map().span_to_snippet(trait_span).ok()?;
882 let trait_m = trait_m.def_id.as_local()?;
883 let trait_m = tcx.hir().trait_item(hir::TraitItemId { def_id: trait_m });
885 let impl_m = impl_m.def_id.as_local()?;
886 let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
888 // in case there are no generics, take the spot between the function name
889 // and the opening paren of the argument list
890 let new_generics_span =
891 tcx.sess.source_map().generate_fn_name_span(impl_span)?.shrink_to_hi();
892 // in case there are generics, just replace them
894 impl_m.generics.span.substitute_dummy(new_generics_span);
895 // replace with the generics from the trait
897 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
899 err.multipart_suggestion(
900 "try changing the `impl Trait` argument to a generic parameter",
902 // replace `impl Trait` with `T`
903 (impl_span, new_name),
904 // replace impl method generics with trait method generics
905 // This isn't quite right, as users might have changed the names
906 // of the generics, but it works for the common case
907 (generics_span, new_generics),
909 Applicability::MaybeIncorrect,
914 // The case where the trait method uses `impl Trait`, but the impl method uses
915 // explicit generics.
917 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
919 let impl_m = impl_m.def_id.as_local()?;
920 let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
921 let input_tys = match impl_m.kind {
922 hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
925 struct Visitor(Option<Span>, hir::def_id::LocalDefId);
926 impl<'v> intravisit::Visitor<'v> for Visitor {
927 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
928 intravisit::walk_ty(self, ty);
929 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
931 && let Res::Def(DefKind::TyParam, def_id) = path.res
932 && def_id == self.1.to_def_id()
934 self.0 = Some(ty.span);
938 let mut visitor = Visitor(None, impl_def_id);
939 for ty in input_tys {
940 intravisit::Visitor::visit_ty(&mut visitor, ty);
942 let span = visitor.0?;
944 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
945 let bounds = bounds.first()?.span().to(bounds.last()?.span());
946 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
948 err.multipart_suggestion(
949 "try removing the generic parameter and using `impl Trait` instead",
951 // delete generic parameters
952 (impl_m.generics.span, String::new()),
953 // replace param usage with `impl Trait`
954 (span, format!("impl {bounds}")),
956 Applicability::MaybeIncorrect,
963 let reported = err.emit();
964 error_found = Some(reported);
967 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
970 /// Checks that all parameters in the generics of a given assoc item in a trait impl have
971 /// the same kind as the respective generic parameter in the trait def.
973 /// For example all 4 errors in the following code are emitted here:
976 /// fn foo<const N: u8>();
977 /// type bar<const N: u8>;
978 /// fn baz<const N: u32>();
982 /// impl Foo for () {
983 /// fn foo<const N: u64>() {}
985 /// type bar<const N: u64> {}
989 /// type blah<const N: i64> = u32;
994 /// This function does not handle lifetime parameters
995 fn compare_generic_param_kinds<'tcx>(
997 impl_item: &ty::AssocItem,
998 trait_item: &ty::AssocItem,
999 ) -> Result<(), ErrorGuaranteed> {
1000 assert_eq!(impl_item.kind, trait_item.kind);
1002 let ty_const_params_of = |def_id| {
1003 tcx.generics_of(def_id).params.iter().filter(|param| {
1006 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
1011 for (param_impl, param_trait) in
1012 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
1014 use GenericParamDefKind::*;
1015 if match (¶m_impl.kind, ¶m_trait.kind) {
1016 (Const { .. }, Const { .. })
1017 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1021 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
1022 // this is exhaustive so that anyone adding new generic param kinds knows
1023 // to make sure this error is reported for them.
1024 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
1025 (Lifetime { .. }, _) | (_, Lifetime { .. }) => unreachable!(),
1027 let param_impl_span = tcx.def_span(param_impl.def_id);
1028 let param_trait_span = tcx.def_span(param_trait.def_id);
1030 let mut err = struct_span_err!(
1034 "{} `{}` has an incompatible generic parameter for trait `{}`",
1035 assoc_item_kind_str(&impl_item),
1037 &tcx.def_path_str(tcx.parent(trait_item.def_id))
1040 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
1042 format!("{} const parameter of type `{}`", prefix, tcx.type_of(param.def_id))
1044 Type { .. } => format!("{} type parameter", prefix),
1045 Lifetime { .. } => unreachable!(),
1048 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
1049 err.span_label(trait_header_span, "");
1050 err.span_label(param_trait_span, make_param_message("expected", param_trait));
1052 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1053 err.span_label(impl_header_span, "");
1054 err.span_label(param_impl_span, make_param_message("found", param_impl));
1056 let reported = err.emit();
1057 return Err(reported);
1064 pub(crate) fn compare_const_impl<'tcx>(
1066 impl_c: &ty::AssocItem,
1068 trait_c: &ty::AssocItem,
1069 impl_trait_ref: ty::TraitRef<'tcx>,
1071 debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
1073 tcx.infer_ctxt().enter(|infcx| {
1074 let param_env = tcx.param_env(impl_c.def_id);
1075 let ocx = ObligationCtxt::new(&infcx);
1077 // The below is for the most part highly similar to the procedure
1078 // for methods above. It is simpler in many respects, especially
1079 // because we shouldn't really have to deal with lifetimes or
1080 // predicates. In fact some of this should probably be put into
1081 // shared functions because of DRY violations...
1082 let trait_to_impl_substs = impl_trait_ref.substs;
1084 // Create a parameter environment that represents the implementation's
1086 let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_c.def_id.expect_local());
1088 // Compute placeholder form of impl and trait const tys.
1089 let impl_ty = tcx.type_of(impl_c.def_id);
1090 let trait_ty = tcx.bound_type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
1091 let mut cause = ObligationCause::new(
1094 ObligationCauseCode::CompareImplItemObligation {
1095 impl_item_def_id: impl_c.def_id.expect_local(),
1096 trait_item_def_id: trait_c.def_id,
1101 // There is no "body" here, so just pass dummy id.
1102 let impl_ty = ocx.normalize(cause.clone(), param_env, impl_ty);
1104 debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1106 let trait_ty = ocx.normalize(cause.clone(), param_env, trait_ty);
1108 debug!("compare_const_impl: trait_ty={:?}", trait_ty);
1111 .at(&cause, param_env)
1112 .sup(trait_ty, impl_ty)
1113 .map(|ok| ocx.register_infer_ok_obligations(ok));
1115 if let Err(terr) = err {
1117 "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
1121 // Locate the Span containing just the type of the offending impl
1122 match tcx.hir().expect_impl_item(impl_c.def_id.expect_local()).kind {
1123 ImplItemKind::Const(ref ty, _) => cause.span = ty.span,
1124 _ => bug!("{:?} is not a impl const", impl_c),
1127 let mut diag = struct_span_err!(
1131 "implemented const `{}` has an incompatible type for trait",
1135 let trait_c_span = trait_c.def_id.as_local().map(|trait_c_def_id| {
1136 // Add a label to the Span containing just the type of the const
1137 match tcx.hir().expect_trait_item(trait_c_def_id).kind {
1138 TraitItemKind::Const(ref ty, _) => ty.span,
1139 _ => bug!("{:?} is not a trait const", trait_c),
1143 infcx.note_type_err(
1146 trait_c_span.map(|span| (span, "type in trait".to_owned())),
1147 Some(infer::ValuePairs::Terms(ExpectedFound {
1148 expected: trait_ty.into(),
1149 found: impl_ty.into(),
1158 // Check that all obligations are satisfied by the implementation's
1160 let errors = ocx.select_all_or_error();
1161 if !errors.is_empty() {
1162 infcx.report_fulfillment_errors(&errors, None, false);
1166 let outlives_environment = OutlivesEnvironment::new(param_env);
1167 infcx.check_region_obligations_and_report_errors(
1168 impl_c.def_id.expect_local(),
1169 &outlives_environment,
1174 pub(crate) fn compare_ty_impl<'tcx>(
1176 impl_ty: &ty::AssocItem,
1178 trait_ty: &ty::AssocItem,
1179 impl_trait_ref: ty::TraitRef<'tcx>,
1180 trait_item_span: Option<Span>,
1182 debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);
1184 let _: Result<(), ErrorGuaranteed> = (|| {
1185 compare_number_of_generics(tcx, impl_ty, impl_ty_span, trait_ty, trait_item_span)?;
1187 compare_generic_param_kinds(tcx, impl_ty, trait_ty)?;
1189 let sp = tcx.def_span(impl_ty.def_id);
1190 compare_type_predicate_entailment(tcx, impl_ty, sp, trait_ty, impl_trait_ref)?;
1192 check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
1196 /// The equivalent of [compare_predicate_entailment], but for associated types
1197 /// instead of associated functions.
1198 fn compare_type_predicate_entailment<'tcx>(
1200 impl_ty: &ty::AssocItem,
1202 trait_ty: &ty::AssocItem,
1203 impl_trait_ref: ty::TraitRef<'tcx>,
1204 ) -> Result<(), ErrorGuaranteed> {
1205 let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1206 let trait_to_impl_substs =
1207 impl_substs.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.substs);
1209 let impl_ty_generics = tcx.generics_of(impl_ty.def_id);
1210 let trait_ty_generics = tcx.generics_of(trait_ty.def_id);
1211 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
1212 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
1214 check_region_bounds_on_impl_item(
1222 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);
1224 if impl_ty_own_bounds.is_empty() {
1225 // Nothing to check.
1229 // This `HirId` should be used for the `body_id` field on each
1230 // `ObligationCause` (and the `FnCtxt`). This is what
1231 // `regionck_item` expects.
1232 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1233 debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs);
1235 // The predicates declared by the impl definition, the trait and the
1236 // associated type in the trait are assumed.
1237 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
1238 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
1241 .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1243 debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);
1245 let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1246 let param_env = ty::ParamEnv::new(
1247 tcx.intern_predicates(&hybrid_preds.predicates),
1249 hir::Constness::NotConst,
1251 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
1252 tcx.infer_ctxt().enter(|infcx| {
1253 let ocx = ObligationCtxt::new(&infcx);
1255 debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1257 let mut selcx = traits::SelectionContext::new(&infcx);
1259 assert_eq!(impl_ty_own_bounds.predicates.len(), impl_ty_own_bounds.spans.len());
1260 for (span, predicate) in
1261 std::iter::zip(impl_ty_own_bounds.spans, impl_ty_own_bounds.predicates)
1263 let cause = ObligationCause::misc(span, impl_ty_hir_id);
1264 let traits::Normalized { value: predicate, obligations } =
1265 traits::normalize(&mut selcx, param_env, cause, predicate);
1267 let cause = ObligationCause::new(
1270 ObligationCauseCode::CompareImplItemObligation {
1271 impl_item_def_id: impl_ty.def_id.expect_local(),
1272 trait_item_def_id: trait_ty.def_id,
1276 ocx.register_obligations(obligations);
1277 ocx.register_obligation(traits::Obligation::new(cause, param_env, predicate));
1280 // Check that all obligations are satisfied by the implementation's
1282 let errors = ocx.select_all_or_error();
1283 if !errors.is_empty() {
1284 let reported = infcx.report_fulfillment_errors(&errors, None, false);
1285 return Err(reported);
1288 // Finally, resolve all regions. This catches wily misuses of
1289 // lifetime parameters.
1290 let outlives_environment = OutlivesEnvironment::new(param_env);
1291 infcx.check_region_obligations_and_report_errors(
1292 impl_ty.def_id.expect_local(),
1293 &outlives_environment,
1300 /// Validate that `ProjectionCandidate`s created for this associated type will
1305 /// trait X { type Y: Copy } impl X for T { type Y = S; }
1307 /// We are able to normalize `<T as X>::U` to `S`, and so when we check the
1308 /// impl is well-formed we have to prove `S: Copy`.
1310 /// For default associated types the normalization is not possible (the value
1311 /// from the impl could be overridden). We also can't normalize generic
1312 /// associated types (yet) because they contain bound parameters.
1313 #[tracing::instrument(level = "debug", skip(tcx))]
1314 pub fn check_type_bounds<'tcx>(
1316 trait_ty: &ty::AssocItem,
1317 impl_ty: &ty::AssocItem,
1319 impl_trait_ref: ty::TraitRef<'tcx>,
1320 ) -> Result<(), ErrorGuaranteed> {
1323 // impl<A, B> Foo<u32> for (A, B) {
1327 // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>
1328 // - `impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
1329 // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from
1330 // the *trait* with the generic associated type parameters (as bound vars).
1332 // A note regarding the use of bound vars here:
1333 // Imagine as an example
1336 // type Member<C: Eq>;
1339 // impl Family for VecFamily {
1340 // type Member<C: Eq> = i32;
1343 // Here, we would generate
1345 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
1347 // when we really would like to generate
1349 // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
1351 // But, this is probably fine, because although the first clause can be used with types C that
1352 // do not implement Eq, for it to cause some kind of problem, there would have to be a
1353 // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
1354 // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
1355 // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
1356 // the trait (notably, that X: Eq and T: Family).
1357 let defs: &ty::Generics = tcx.generics_of(impl_ty.def_id);
1358 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
1359 if let Some(def_id) = defs.parent {
1360 let parent_defs = tcx.generics_of(def_id);
1361 InternalSubsts::fill_item(&mut substs, tcx, parent_defs, &mut |param, _| {
1362 tcx.mk_param_from_def(param)
1365 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
1366 smallvec::SmallVec::with_capacity(defs.count());
1367 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param.kind {
1368 GenericParamDefKind::Type { .. } => {
1369 let kind = ty::BoundTyKind::Param(param.name);
1370 let bound_var = ty::BoundVariableKind::Ty(kind);
1371 bound_vars.push(bound_var);
1372 tcx.mk_ty(ty::Bound(
1374 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1378 GenericParamDefKind::Lifetime => {
1379 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
1380 let bound_var = ty::BoundVariableKind::Region(kind);
1381 bound_vars.push(bound_var);
1382 tcx.mk_region(ty::ReLateBound(
1384 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
1388 GenericParamDefKind::Const { .. } => {
1389 let bound_var = ty::BoundVariableKind::Const;
1390 bound_vars.push(bound_var);
1391 tcx.mk_const(ty::ConstS {
1392 ty: tcx.type_of(param.def_id),
1393 kind: ty::ConstKind::Bound(
1395 ty::BoundVar::from_usize(bound_vars.len() - 1),
1401 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
1402 let impl_ty_substs = tcx.intern_substs(&substs);
1403 let container_id = impl_ty.container_id(tcx);
1405 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
1406 let impl_ty_value = tcx.type_of(impl_ty.def_id);
1408 let param_env = tcx.param_env(impl_ty.def_id);
1410 // When checking something like
1412 // trait X { type Y: PartialEq<<Self as X>::Y> }
1413 // impl X for T { default type Y = S; }
1415 // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
1416 // we want <T as X>::Y to normalize to S. This is valid because we are
1417 // checking the default value specifically here. Add this equality to the
1418 // ParamEnv for normalization specifically.
1419 let normalize_param_env = {
1420 let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
1421 match impl_ty_value.kind() {
1422 ty::Projection(proj)
1423 if proj.item_def_id == trait_ty.def_id && proj.substs == rebased_substs =>
1425 // Don't include this predicate if the projected type is
1426 // exactly the same as the projection. This can occur in
1427 // (somewhat dubious) code like this:
1429 // impl<T> X for T where T: X { type Y = <T as X>::Y; }
1431 _ => predicates.push(
1432 ty::Binder::bind_with_vars(
1433 ty::ProjectionPredicate {
1434 projection_ty: ty::ProjectionTy {
1435 item_def_id: trait_ty.def_id,
1436 substs: rebased_substs,
1438 term: impl_ty_value.into(),
1446 tcx.intern_predicates(&predicates),
1448 param_env.constness(),
1451 debug!(?normalize_param_env);
1453 let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1454 let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
1455 let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs);
1457 tcx.infer_ctxt().enter(move |infcx| {
1458 let ocx = ObligationCtxt::new(&infcx);
1460 let assumed_wf_types =
1461 ocx.assumed_wf_types(param_env, impl_ty_span, impl_ty.def_id.expect_local());
1463 let mut selcx = traits::SelectionContext::new(&infcx);
1464 let normalize_cause = ObligationCause::new(
1467 ObligationCauseCode::CheckAssociatedTypeBounds {
1468 impl_item_def_id: impl_ty.def_id.expect_local(),
1469 trait_item_def_id: trait_ty.def_id,
1472 let mk_cause = |span: Span| {
1473 let code = if span.is_dummy() {
1474 traits::ItemObligation(trait_ty.def_id)
1476 traits::BindingObligation(trait_ty.def_id, span)
1478 ObligationCause::new(impl_ty_span, impl_ty_hir_id, code)
1481 let obligations = tcx
1482 .bound_explicit_item_bounds(trait_ty.def_id)
1484 .map(|e| e.map_bound(|e| *e).transpose_tuple2())
1485 .map(|(bound, span)| {
1487 // this is where opaque type is found
1488 let concrete_ty_bound = bound.subst(tcx, rebased_substs);
1489 debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
1491 traits::Obligation::new(mk_cause(span.0), param_env, concrete_ty_bound)
1494 debug!("check_type_bounds: item_bounds={:?}", obligations);
1496 for mut obligation in util::elaborate_obligations(tcx, obligations) {
1497 let traits::Normalized { value: normalized_predicate, obligations } = traits::normalize(
1499 normalize_param_env,
1500 normalize_cause.clone(),
1501 obligation.predicate,
1503 debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
1504 obligation.predicate = normalized_predicate;
1506 ocx.register_obligations(obligations);
1507 ocx.register_obligation(obligation);
1509 // Check that all obligations are satisfied by the implementation's
1511 let errors = ocx.select_all_or_error();
1512 if !errors.is_empty() {
1513 let reported = infcx.report_fulfillment_errors(&errors, None, false);
1514 return Err(reported);
1517 // Finally, resolve all regions. This catches wily misuses of
1518 // lifetime parameters.
1519 let implied_bounds = infcx.implied_bounds_tys(param_env, impl_ty_hir_id, assumed_wf_types);
1520 let outlives_environment =
1521 OutlivesEnvironment::with_bounds(param_env, Some(&infcx), implied_bounds);
1523 infcx.check_region_obligations_and_report_errors(
1524 impl_ty.def_id.expect_local(),
1525 &outlives_environment,
1528 let constraints = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
1529 for (key, value) in constraints {
1531 .report_mismatched_types(
1532 &ObligationCause::misc(
1533 value.hidden_type.span,
1534 tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local()),
1536 tcx.mk_opaque(key.def_id.to_def_id(), key.substs),
1537 value.hidden_type.ty,
1538 TypeError::Mismatch,
1547 fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
1548 match impl_item.kind {
1549 ty::AssocKind::Const => "const",
1550 ty::AssocKind::Fn => "method",
1551 ty::AssocKind::Type => "type",