1use core::ops::ControlFlow;
2use std::borrow::Cow;
3use std::cmp::Ordering;
4use std::iter;
5
6use hir::def_id::{DefId, DefIdMap, LocalDefId};
7use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
8use rustc_errors::codes::*;
9use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan, pluralize, struct_span_code_err};
10use rustc_hir::def::{DefKind, Res};
11use rustc_hir::intravisit::VisitorExt;
12use rustc_hir::{self as hir, AmbigArg, GenericParamKind, ImplItemKind, intravisit};
13use rustc_infer::infer::{self, BoundRegionConversionTime, InferCtxt, TyCtxtInferExt};
14use rustc_infer::traits::util;
15use rustc_middle::ty::error::{ExpectedFound, TypeError};
16use rustc_middle::ty::{
17 self, BottomUpFolder, GenericArgs, GenericParamDefKind, Generics, RegionExt,
18 RegionUtilitiesExt, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable,
19 TypeVisitableExt, TypeVisitor, TypingMode, Unnormalized, Upcast,
20};
21use rustc_middle::{bug, span_bug};
22use rustc_span::{BytePos, DUMMY_SP, Span};
23use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
24use rustc_trait_selection::infer::InferCtxtExt;
25use rustc_trait_selection::regions::InferCtxtRegionExt;
26use rustc_trait_selection::traits::{
27 self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
28};
29use tracing::{debug, instrument};
30
31use super::potentially_plural_count;
32use crate::diagnostics::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture};
33
34pub(super) mod refine;
35
36pub(super) fn compare_impl_item(
38 tcx: TyCtxt<'_>,
39 impl_item_def_id: LocalDefId,
40) -> Result<(), ErrorGuaranteed> {
41 let impl_item = tcx.associated_item(impl_item_def_id);
42 let trait_item = tcx.associated_item(impl_item.expect_trait_impl()?);
43 let impl_trait_ref =
44 tcx.impl_trait_ref(impl_item.container_id(tcx)).instantiate_identity().skip_norm_wip();
45 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:45",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(45u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("impl_trait_ref");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?impl_trait_ref);
46
47 match impl_item.kind {
48 ty::AssocKind::Fn { .. } => compare_impl_method(tcx, impl_item, trait_item, impl_trait_ref),
49 ty::AssocKind::Type { .. } => compare_impl_ty(tcx, impl_item, trait_item, impl_trait_ref),
50 ty::AssocKind::Const { .. } => {
51 compare_impl_const(tcx, impl_item, trait_item, impl_trait_ref)
52 }
53 }
54}
55
56#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("compare_impl_method",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(64u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_m")
}> =
::tracing::__macro_support::FieldName::new("impl_m");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_m")
}> =
::tracing::__macro_support::FieldName::new("trait_m");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("impl_trait_ref");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_m)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_m)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
check_method_is_structurally_compatible(tcx, impl_m, trait_m,
impl_trait_ref, false)?;
compare_method_predicate_entailment(tcx, impl_m, trait_m,
impl_trait_ref)?;
Ok(())
}
}
}#[instrument(level = "debug", skip(tcx))]
65fn compare_impl_method<'tcx>(
66 tcx: TyCtxt<'tcx>,
67 impl_m: ty::AssocItem,
68 trait_m: ty::AssocItem,
69 impl_trait_ref: ty::TraitRef<'tcx>,
70) -> Result<(), ErrorGuaranteed> {
71 check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, false)?;
72 compare_method_predicate_entailment(tcx, impl_m, trait_m, impl_trait_ref)?;
73 Ok(())
74}
75
76fn check_method_is_structurally_compatible<'tcx>(
80 tcx: TyCtxt<'tcx>,
81 impl_m: ty::AssocItem,
82 trait_m: ty::AssocItem,
83 impl_trait_ref: ty::TraitRef<'tcx>,
84 delay: bool,
85) -> Result<(), ErrorGuaranteed> {
86 compare_self_type(tcx, impl_m, trait_m, impl_trait_ref, delay)?;
87 compare_number_of_generics(tcx, impl_m, trait_m, delay)?;
88 compare_generic_param_kinds(tcx, impl_m, trait_m, delay)?;
89 compare_number_of_method_arguments(tcx, impl_m, trait_m, delay)?;
90 compare_synthetic_generics(tcx, impl_m, trait_m, delay)?;
91 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, delay)?;
92 Ok(())
93}
94
95#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("compare_method_predicate_entailment",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(173u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_m")
}> =
::tracing::__macro_support::FieldName::new("impl_m");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_m")
}> =
::tracing::__macro_support::FieldName::new("trait_m");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_m)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_m)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let impl_m_def_id = impl_m.def_id.expect_local();
let impl_m_span = tcx.def_span(impl_m_def_id);
let cause =
ObligationCause::new(impl_m_span, impl_m_def_id,
ObligationCauseCode::CompareImplItem {
impl_item_def_id: impl_m_def_id,
trait_item_def_id: trait_m.def_id,
kind: impl_m.kind,
});
let impl_def_id = impl_m.container_id(tcx);
let trait_to_impl_args =
GenericArgs::identity_for_item(tcx,
impl_m.def_id).rebase_onto(tcx, impl_m.container_id(tcx),
impl_trait_ref.args);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:204",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(204u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_to_impl_args")
}> =
::tracing::__macro_support::FieldName::new("trait_to_impl_args");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_to_impl_args)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
let impl_predicates =
tcx.predicates_of(impl_m_predicates.parent.unwrap());
let mut hybrid_preds =
impl_predicates.instantiate_identity(tcx).predicates;
hybrid_preds.extend(trait_m_predicates.instantiate_own(tcx,
trait_to_impl_args).map(|(predicate, _)| predicate));
let is_conditionally_const =
tcx.is_conditionally_const(impl_m.def_id);
if is_conditionally_const {
hybrid_preds.extend(tcx.const_conditions(impl_def_id).instantiate_identity(tcx).into_iter().chain(tcx.const_conditions(trait_m.def_id).instantiate_own(tcx,
trait_to_impl_args)).map(|(trait_ref, _)|
{
trait_ref.to_host_effect_clause(tcx,
ty::BoundConstness::Maybe)
}));
}
let hybrid_preds =
hybrid_preds.into_iter().map(Unnormalized::skip_norm_wip);
let normalize_cause =
traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
let param_env =
ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
let param_env =
traits::normalize_param_env_or_error(tcx, param_env,
normalize_cause);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:257",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(257u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("caller_bounds")
}> =
::tracing::__macro_support::FieldName::new("caller_bounds");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_env.caller_bounds())
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let infcx =
&tcx.infer_ctxt().build(TypingMode::non_body_analysis());
let ocx = ObligationCtxt::new_with_diagnostics(infcx);
let impl_m_own_bounds =
impl_m_predicates.instantiate_own_identity();
for (predicate, span) in impl_m_own_bounds {
let normalize_cause =
traits::ObligationCause::misc(span, impl_m_def_id);
let predicate =
ocx.normalize(&normalize_cause, param_env, predicate);
let cause =
ObligationCause::new(span, impl_m_def_id,
ObligationCauseCode::CompareImplItem {
impl_item_def_id: impl_m_def_id,
trait_item_def_id: trait_m.def_id,
kind: impl_m.kind,
});
ocx.register_obligation(traits::Obligation::new(tcx, cause,
param_env, predicate));
}
if is_conditionally_const {
for (const_condition, span) in
tcx.const_conditions(impl_m.def_id).instantiate_own_identity()
{
let normalize_cause =
traits::ObligationCause::misc(span, impl_m_def_id);
let const_condition =
ocx.normalize(&normalize_cause, param_env, const_condition);
let cause =
ObligationCause::new(span, impl_m_def_id,
ObligationCauseCode::CompareImplItem {
impl_item_def_id: impl_m_def_id,
trait_item_def_id: trait_m.def_id,
kind: impl_m.kind,
});
ocx.register_obligation(traits::Obligation::new(tcx, cause,
param_env,
const_condition.to_host_effect_clause(tcx,
ty::BoundConstness::Maybe)));
}
}
let mut wf_tys = FxIndexSet::default();
let unnormalized_impl_sig =
infcx.instantiate_binder_with_fresh_vars(impl_m_span,
BoundRegionConversionTime::HigherRankedType,
tcx.fn_sig(impl_m.def_id).instantiate_identity().skip_norm_wip());
let norm_cause =
ObligationCause::misc(impl_m_span, impl_m_def_id);
let impl_sig =
ocx.normalize(&norm_cause, param_env,
Unnormalized::new_wip(unnormalized_impl_sig));
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:333",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(333u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_sig")
}> =
::tracing::__macro_support::FieldName::new("impl_sig");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_sig)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let trait_sig =
tcx.fn_sig(trait_m.def_id).instantiate(tcx,
trait_to_impl_args).skip_norm_wip();
let trait_sig =
tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
wf_tys.extend(trait_sig.inputs_and_output.iter());
let trait_sig =
ocx.normalize(&norm_cause, param_env,
Unnormalized::new_wip(trait_sig));
wf_tys.extend(trait_sig.inputs_and_output.iter());
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:346",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(346u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_sig")
}> =
::tracing::__macro_support::FieldName::new("trait_sig");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_sig)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
if let Err(terr) = result {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:358",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(358u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_sig")
}> =
::tracing::__macro_support::FieldName::new("impl_sig");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_sig")
}> =
::tracing::__macro_support::FieldName::new("trait_sig");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("terr")
}> =
::tracing::__macro_support::FieldName::new("terr");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("sub_types failed")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_sig)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_sig)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&terr)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let emitted =
report_trait_method_mismatch(infcx, cause, param_env, terr,
(trait_m, trait_sig), (impl_m, impl_sig), impl_trait_ref);
return Err(emitted);
}
if !(impl_sig, trait_sig).references_error() {
for ty in unnormalized_impl_sig.inputs_and_output {
ocx.register_obligation(traits::Obligation::new(infcx.tcx,
cause.clone(), param_env,
ty::ClauseKind::WellFormed(ty.into())));
}
}
let errors = ocx.evaluate_obligations_error_on_ambiguity();
if !errors.is_empty() {
let reported =
infcx.err_ctxt().report_fulfillment_errors(errors);
return Err(reported);
}
let errors =
infcx.resolve_regions(impl_m_def_id, param_env, wf_tys);
if !errors.is_empty() {
return Err(infcx.tainted_by_errors().unwrap_or_else(||
infcx.err_ctxt().report_region_errors(impl_m_def_id,
&errors)));
}
Ok(())
}
}
}#[instrument(level = "debug", skip(tcx, impl_trait_ref))]
174fn compare_method_predicate_entailment<'tcx>(
175 tcx: TyCtxt<'tcx>,
176 impl_m: ty::AssocItem,
177 trait_m: ty::AssocItem,
178 impl_trait_ref: ty::TraitRef<'tcx>,
179) -> Result<(), ErrorGuaranteed> {
180 let impl_m_def_id = impl_m.def_id.expect_local();
186 let impl_m_span = tcx.def_span(impl_m_def_id);
187 let cause = ObligationCause::new(
188 impl_m_span,
189 impl_m_def_id,
190 ObligationCauseCode::CompareImplItem {
191 impl_item_def_id: impl_m_def_id,
192 trait_item_def_id: trait_m.def_id,
193 kind: impl_m.kind,
194 },
195 );
196
197 let impl_def_id = impl_m.container_id(tcx);
199 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
200 tcx,
201 impl_m.container_id(tcx),
202 impl_trait_ref.args,
203 );
204 debug!(?trait_to_impl_args);
205
206 let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
207 let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
208
209 let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
217 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
218 hybrid_preds.extend(
219 trait_m_predicates.instantiate_own(tcx, trait_to_impl_args).map(|(predicate, _)| predicate),
220 );
221
222 let is_conditionally_const = tcx.is_conditionally_const(impl_m.def_id);
223 if is_conditionally_const {
224 hybrid_preds.extend(
227 tcx.const_conditions(impl_def_id)
228 .instantiate_identity(tcx)
229 .into_iter()
230 .chain(
231 tcx.const_conditions(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args),
232 )
233 .map(|(trait_ref, _)| {
234 trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
235 }),
236 );
237 }
238
239 let hybrid_preds = hybrid_preds.into_iter().map(Unnormalized::skip_norm_wip);
240 let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
241 let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
242 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
257 debug!(caller_bounds=?param_env.caller_bounds());
258
259 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
260 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
261
262 let impl_m_own_bounds = impl_m_predicates.instantiate_own_identity();
267 for (predicate, span) in impl_m_own_bounds {
268 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
269 let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
270
271 let cause = ObligationCause::new(
272 span,
273 impl_m_def_id,
274 ObligationCauseCode::CompareImplItem {
275 impl_item_def_id: impl_m_def_id,
276 trait_item_def_id: trait_m.def_id,
277 kind: impl_m.kind,
278 },
279 );
280 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
281 }
282
283 if is_conditionally_const {
290 for (const_condition, span) in
291 tcx.const_conditions(impl_m.def_id).instantiate_own_identity()
292 {
293 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
294 let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
295
296 let cause = ObligationCause::new(
297 span,
298 impl_m_def_id,
299 ObligationCauseCode::CompareImplItem {
300 impl_item_def_id: impl_m_def_id,
301 trait_item_def_id: trait_m.def_id,
302 kind: impl_m.kind,
303 },
304 );
305 ocx.register_obligation(traits::Obligation::new(
306 tcx,
307 cause,
308 param_env,
309 const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
310 ));
311 }
312 }
313
314 let mut wf_tys = FxIndexSet::default();
323
324 let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars(
325 impl_m_span,
326 BoundRegionConversionTime::HigherRankedType,
327 tcx.fn_sig(impl_m.def_id).instantiate_identity().skip_norm_wip(),
328 );
329
330 let norm_cause = ObligationCause::misc(impl_m_span, impl_m_def_id);
331 let impl_sig =
332 ocx.normalize(&norm_cause, param_env, Unnormalized::new_wip(unnormalized_impl_sig));
333 debug!(?impl_sig);
334
335 let trait_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args).skip_norm_wip();
336 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
337
338 wf_tys.extend(trait_sig.inputs_and_output.iter());
342 let trait_sig = ocx.normalize(&norm_cause, param_env, Unnormalized::new_wip(trait_sig));
343 wf_tys.extend(trait_sig.inputs_and_output.iter());
346 debug!(?trait_sig);
347
348 let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
356
357 if let Err(terr) = result {
358 debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
359
360 let emitted = report_trait_method_mismatch(
361 infcx,
362 cause,
363 param_env,
364 terr,
365 (trait_m, trait_sig),
366 (impl_m, impl_sig),
367 impl_trait_ref,
368 );
369 return Err(emitted);
370 }
371
372 if !(impl_sig, trait_sig).references_error() {
373 for ty in unnormalized_impl_sig.inputs_and_output {
374 ocx.register_obligation(traits::Obligation::new(
375 infcx.tcx,
376 cause.clone(),
377 param_env,
378 ty::ClauseKind::WellFormed(ty.into()),
379 ));
380 }
381 }
382
383 let errors = ocx.evaluate_obligations_error_on_ambiguity();
386 if !errors.is_empty() {
387 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
388 return Err(reported);
389 }
390
391 let errors = infcx.resolve_regions(impl_m_def_id, param_env, wf_tys);
394 if !errors.is_empty() {
395 return Err(infcx
396 .tainted_by_errors()
397 .unwrap_or_else(|| infcx.err_ctxt().report_region_errors(impl_m_def_id, &errors)));
398 }
399
400 Ok(())
401}
402
403struct RemapLateParam<'tcx> {
404 tcx: TyCtxt<'tcx>,
405 mapping: FxIndexMap<ty::LateParamRegionKind, ty::LateParamRegionKind>,
406}
407
408impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateParam<'tcx> {
409 fn cx(&self) -> TyCtxt<'tcx> {
410 self.tcx
411 }
412
413 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
414 if let ty::ReLateParam(fr) = r.kind() {
415 ty::Region::new_late_param(
416 self.tcx,
417 fr.scope,
418 self.mapping.get(&fr.kind).copied().unwrap_or(fr.kind),
419 )
420 } else {
421 r
422 }
423 }
424}
425
426x;#[instrument(skip(tcx), level = "debug", ret)]
458pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
459 tcx: TyCtxt<'tcx>,
460 impl_m_def_id: LocalDefId,
461) -> Result<&'tcx DefIdMap<ty::EarlyBinder<'tcx, Ty<'tcx>>>, ErrorGuaranteed> {
462 let impl_m = tcx.associated_item(impl_m_def_id.to_def_id());
463 let trait_m = tcx.associated_item(impl_m.expect_trait_impl()?);
464 let impl_trait_ref = tcx
465 .impl_trait_ref(tcx.parent(impl_m_def_id.to_def_id()))
466 .instantiate_identity()
467 .skip_norm_wip();
468 check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?;
471
472 let impl_m_hir_id = tcx.local_def_id_to_hir_id(impl_m_def_id);
473 let return_span = tcx.hir_fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
474 let cause = ObligationCause::new(
475 return_span,
476 impl_m_def_id,
477 ObligationCauseCode::CompareImplItem {
478 impl_item_def_id: impl_m_def_id,
479 trait_item_def_id: trait_m.def_id,
480 kind: impl_m.kind,
481 },
482 );
483
484 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
486 tcx,
487 impl_m.container_id(tcx),
488 impl_trait_ref.args,
489 );
490
491 let hybrid_preds = tcx
492 .predicates_of(impl_m.container_id(tcx))
493 .instantiate_identity(tcx)
494 .into_iter()
495 .chain(tcx.predicates_of(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args))
496 .map(|(clause, _)| clause.skip_norm_wip());
497 let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
498 let param_env = traits::normalize_param_env_or_error(
499 tcx,
500 param_env,
501 ObligationCause::misc(tcx.def_span(impl_m_def_id), impl_m_def_id),
502 );
503
504 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
505 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
506
507 let impl_m_own_bounds = tcx.predicates_of(impl_m_def_id).instantiate_own_identity();
514 for (predicate, span) in impl_m_own_bounds {
515 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
516 let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
517
518 let cause = ObligationCause::new(
519 span,
520 impl_m_def_id,
521 ObligationCauseCode::CompareImplItem {
522 impl_item_def_id: impl_m_def_id,
523 trait_item_def_id: trait_m.def_id,
524 kind: impl_m.kind,
525 },
526 );
527 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
528 }
529
530 let misc_cause = ObligationCause::misc(return_span, impl_m_def_id);
532 let impl_sig = ocx.normalize(
533 &misc_cause,
534 param_env,
535 Unnormalized::new_wip(infcx.instantiate_binder_with_fresh_vars(
536 return_span,
537 BoundRegionConversionTime::HigherRankedType,
538 tcx.fn_sig(impl_m.def_id).instantiate_identity().skip_norm_wip(),
539 )),
540 );
541 impl_sig.error_reported()?;
542 let impl_return_ty = impl_sig.output();
543
544 let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_def_id);
549 let unnormalized_trait_sig = tcx
550 .liberate_late_bound_regions(
551 impl_m.def_id,
552 tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args).skip_norm_wip(),
553 )
554 .fold_with(&mut collector);
555
556 let trait_sig =
557 ocx.normalize(&misc_cause, param_env, Unnormalized::new_wip(unnormalized_trait_sig));
558 trait_sig.error_reported()?;
559 let trait_return_ty = trait_sig.output();
560
561 let universe = infcx.create_next_universe();
581 let mut idx = ty::BoundVar::ZERO;
582 let mapping: FxIndexMap<_, _> = collector
583 .types
584 .iter()
585 .map(|(_, &(ty, _))| {
586 assert!(
587 infcx.resolve_vars_if_possible(ty) == ty && ty.is_ty_var(),
588 "{ty:?} should not have been constrained via normalization",
589 ty = infcx.resolve_vars_if_possible(ty)
590 );
591 idx += 1;
592 (
593 ty,
594 Ty::new_placeholder(
595 tcx,
596 ty::PlaceholderType::new(
597 universe,
598 ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
599 ),
600 ),
601 )
602 })
603 .collect();
604 let mut type_mapper = BottomUpFolder {
605 tcx,
606 ty_op: |ty| *mapping.get(&ty).unwrap_or(&ty),
607 lt_op: |lt| lt,
608 ct_op: |ct| ct,
609 };
610 let wf_tys = FxIndexSet::from_iter(
611 unnormalized_trait_sig
612 .inputs_and_output
613 .iter()
614 .chain(trait_sig.inputs_and_output.iter())
615 .map(|ty| ty.fold_with(&mut type_mapper)),
616 );
617
618 match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
619 Ok(()) => {}
620 Err(terr) => {
621 let mut diag = struct_span_code_err!(
622 tcx.dcx(),
623 cause.span,
624 E0053,
625 "method `{}` has an incompatible return type for trait",
626 trait_m.name()
627 );
628 infcx.err_ctxt().note_type_err(
629 &mut diag,
630 &cause,
631 tcx.hir_get_if_local(impl_m.def_id)
632 .and_then(|node| node.fn_decl())
633 .map(|decl| (decl.output.span(), Cow::from("return type in trait"), false)),
634 Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
635 expected: trait_return_ty.into(),
636 found: impl_return_ty.into(),
637 }))),
638 terr,
639 false,
640 None,
641 );
642 return Err(diag.emit());
643 }
644 }
645
646 debug!(?trait_sig, ?impl_sig, "equating function signatures");
647
648 match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
653 Ok(()) => {}
654 Err(terr) => {
655 let emitted = report_trait_method_mismatch(
660 infcx,
661 cause,
662 param_env,
663 terr,
664 (trait_m, trait_sig),
665 (impl_m, impl_sig),
666 impl_trait_ref,
667 );
668 return Err(emitted);
669 }
670 }
671
672 if !unnormalized_trait_sig.output().references_error() && collector.types.is_empty() {
673 tcx.dcx().delayed_bug(
674 "expect >0 RPITITs in call to `collect_return_position_impl_trait_in_trait_tys`",
675 );
676 }
677
678 let collected_types = collector.types;
683 for (_, &(ty, _)) in &collected_types {
684 ocx.register_obligation(traits::Obligation::new(
685 tcx,
686 misc_cause.clone(),
687 param_env,
688 ty::ClauseKind::WellFormed(ty.into()),
689 ));
690 }
691
692 let errors = ocx.evaluate_obligations_error_on_ambiguity();
695 if !errors.is_empty() {
696 if let Err(guar) = try_report_async_mismatch(tcx, infcx, &errors, trait_m, impl_m, impl_sig)
697 {
698 return Err(guar);
699 }
700
701 let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
702 return Err(guar);
703 }
704
705 ocx.resolve_regions_and_report_errors(impl_m_def_id, param_env, wf_tys)?;
708
709 let mut remapped_types = DefIdMap::default();
710 for (def_id, (ty, args)) in collected_types {
711 match infcx.fully_resolve(ty) {
712 Ok(ty) => {
713 let id_args = GenericArgs::identity_for_item(tcx, def_id);
717 debug!(?id_args, ?args);
718 let map: FxIndexMap<_, _> = std::iter::zip(args, id_args)
719 .skip(tcx.generics_of(trait_m.def_id).count())
720 .filter_map(|(a, b)| Some((a.as_region()?, b.as_region()?)))
721 .collect();
722 debug!(?map);
723
724 let num_trait_args = impl_trait_ref.args.len();
745 let num_impl_args = tcx.generics_of(impl_m.container_id(tcx)).own_params.len();
746 let ty = match ty.try_fold_with(&mut RemapHiddenTyRegions {
747 tcx,
748 map,
749 num_trait_args,
750 num_impl_args,
751 def_id,
752 impl_m_def_id: impl_m.def_id,
753 ty,
754 return_span,
755 }) {
756 Ok(ty) => ty,
757 Err(guar) => Ty::new_error(tcx, guar),
758 };
759 remapped_types.insert(def_id, ty::EarlyBinder::bind(tcx, ty));
760 }
761 Err(err) => {
762 tcx.dcx()
767 .span_bug(return_span, format!("could not fully resolve: {ty} => {err:?}"));
768 }
769 }
770 }
771
772 for assoc_item in tcx.associated_types_for_impl_traits_in_associated_fn(trait_m.def_id) {
778 if !remapped_types.contains_key(assoc_item) {
779 remapped_types.insert(
780 *assoc_item,
781 ty::EarlyBinder::bind(
782 tcx,
783 Ty::new_error_with_message(
784 tcx,
785 return_span,
786 "missing synthetic item for RPITIT",
787 ),
788 ),
789 );
790 }
791 }
792
793 Ok(&*tcx.arena.alloc(remapped_types))
794}
795
796struct ImplTraitInTraitCollector<'a, 'tcx, E> {
797 ocx: &'a ObligationCtxt<'a, 'tcx, E>,
798 types: FxIndexMap<DefId, (Ty<'tcx>, ty::GenericArgsRef<'tcx>)>,
799 span: Span,
800 param_env: ty::ParamEnv<'tcx>,
801 impl_m_id: LocalDefId,
802}
803
804impl<'a, 'tcx, E> ImplTraitInTraitCollector<'a, 'tcx, E>
805where
806 E: 'tcx,
807{
808 fn new(
809 ocx: &'a ObligationCtxt<'a, 'tcx, E>,
810 span: Span,
811 param_env: ty::ParamEnv<'tcx>,
812 impl_m_id: LocalDefId,
813 ) -> Self {
814 ImplTraitInTraitCollector { ocx, types: FxIndexMap::default(), span, param_env, impl_m_id }
815 }
816}
817
818impl<'tcx, E> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx, E>
819where
820 E: 'tcx,
821{
822 fn cx(&self) -> TyCtxt<'tcx> {
823 self.ocx.infcx.tcx
824 }
825
826 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
827 if let &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args: proj_args, .. }) =
828 ty.kind()
829 && self.cx().is_impl_trait_in_trait(def_id)
830 {
831 if let Some((ty, _)) = self.types.get(&def_id) {
832 return *ty;
833 }
834 if proj_args.has_escaping_bound_vars() {
836 ::rustc_middle::util::bug::bug_fmt(format_args!("FIXME(RPITIT): error here"));bug!("FIXME(RPITIT): error here");
837 }
838 let infer_ty = self.ocx.infcx.next_ty_var(self.span);
840 self.types.insert(def_id, (infer_ty, proj_args));
841 for (pred, pred_span) in self
843 .cx()
844 .explicit_item_bounds(def_id)
845 .iter_instantiated_copied(self.cx(), proj_args)
846 .map(Unnormalized::skip_norm_wip)
847 {
848 let pred = pred.fold_with(self);
849 let pred = self.ocx.normalize(
850 &ObligationCause::misc(self.span, self.impl_m_id),
851 self.param_env,
852 Unnormalized::new_wip(pred),
853 );
854
855 self.ocx.register_obligation(traits::Obligation::new(
856 self.cx(),
857 ObligationCause::new(
858 self.span,
859 self.impl_m_id,
860 ObligationCauseCode::WhereClause(def_id, pred_span),
861 ),
862 self.param_env,
863 pred,
864 ));
865 }
866 infer_ty
867 } else {
868 ty.super_fold_with(self)
869 }
870 }
871}
872
873struct RemapHiddenTyRegions<'tcx> {
874 tcx: TyCtxt<'tcx>,
875 map: FxIndexMap<ty::Region<'tcx>, ty::Region<'tcx>>,
878 num_trait_args: usize,
879 num_impl_args: usize,
880 def_id: DefId,
882 impl_m_def_id: DefId,
884 ty: Ty<'tcx>,
886 return_span: Span,
888}
889
890impl<'tcx> ty::FallibleTypeFolder<TyCtxt<'tcx>> for RemapHiddenTyRegions<'tcx> {
891 type Error = ErrorGuaranteed;
892
893 fn cx(&self) -> TyCtxt<'tcx> {
894 self.tcx
895 }
896
897 fn try_fold_region(
898 &mut self,
899 region: ty::Region<'tcx>,
900 ) -> Result<ty::Region<'tcx>, Self::Error> {
901 match region.kind() {
902 ty::ReBound(..) | ty::ReStatic | ty::ReError(_) => return Ok(region),
904 ty::ReLateParam(_) => {}
906 ty::ReEarlyParam(ebr) => {
909 if ebr.index as usize >= self.num_impl_args {
910 } else {
912 return Ok(region);
913 }
914 }
915 ty::ReVar(_) | ty::RePlaceholder(_) | ty::ReErased => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("should not have leaked vars or placeholders into hidden type of RPITIT")));
}unreachable!(
916 "should not have leaked vars or placeholders into hidden type of RPITIT"
917 ),
918 }
919
920 let e = if let Some(id_region) = self.map.get(®ion) {
921 if let ty::ReEarlyParam(e) = id_region.kind() {
922 e
923 } else {
924 ::rustc_middle::util::bug::bug_fmt(format_args!("expected to map region {0} to early-bound identity region, but got {1}",
region, id_region));bug!(
925 "expected to map region {region} to early-bound identity region, but got {id_region}"
926 );
927 }
928 } else {
929 let guar = match region.opt_param_def_id(self.tcx, self.impl_m_def_id) {
930 Some(def_id) => {
931 let return_span = if let &ty::Alias(
932 _,
933 ty::AliasTy { kind: ty::Opaque { def_id: opaque_ty_def_id }, .. },
934 ) = self.ty.kind()
935 {
936 self.tcx.def_span(opaque_ty_def_id)
937 } else {
938 self.return_span
939 };
940 self.tcx
941 .dcx()
942 .struct_span_err(
943 return_span,
944 "return type captures more lifetimes than trait definition",
945 )
946 .with_span_label(self.tcx.def_span(def_id), "this lifetime was captured")
947 .with_span_note(
948 self.tcx.def_span(self.def_id),
949 "hidden type must only reference lifetimes captured by this impl trait",
950 )
951 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("hidden type inferred to be `{0}`",
self.ty))
})format!("hidden type inferred to be `{}`", self.ty))
952 .emit()
953 }
954 None => {
955 self.tcx.dcx().bug("should've been able to remap region");
960 }
961 };
962 return Err(guar);
963 };
964
965 Ok(ty::Region::new_early_param(
966 self.tcx,
967 ty::EarlyParamRegion {
968 name: e.name,
969 index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32,
970 },
971 ))
972 }
973}
974
975fn get_self_string<'tcx, P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> String
978where
979 P: Fn(Ty<'tcx>) -> bool,
980{
981 if is_self_ty(self_arg_ty) {
982 "self".to_owned()
983 } else if let ty::Ref(_, ty, mutbl) = self_arg_ty.kind()
984 && is_self_ty(*ty)
985 {
986 match mutbl {
987 hir::Mutability::Not => "&self".to_owned(),
988 hir::Mutability::Mut => "&mut self".to_owned(),
989 }
990 } else {
991 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("self: {0}", self_arg_ty))
})format!("self: {self_arg_ty}")
992 }
993}
994
995fn report_trait_method_mismatch<'tcx>(
996 infcx: &InferCtxt<'tcx>,
997 mut cause: ObligationCause<'tcx>,
998 param_env: ty::ParamEnv<'tcx>,
999 terr: TypeError<'tcx>,
1000 (trait_m, trait_sig): (ty::AssocItem, ty::FnSig<'tcx>),
1001 (impl_m, impl_sig): (ty::AssocItem, ty::FnSig<'tcx>),
1002 impl_trait_ref: ty::TraitRef<'tcx>,
1003) -> ErrorGuaranteed {
1004 let tcx = infcx.tcx;
1005 let (impl_err_span, trait_err_span) =
1006 extract_spans_for_error_reporting(infcx, terr, &cause, impl_m, trait_m);
1007
1008 let mut diag = {
tcx.dcx().struct_span_err(impl_err_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("method `{0}` has an incompatible type for trait",
trait_m.name()))
})).with_code(E0053)
}struct_span_code_err!(
1009 tcx.dcx(),
1010 impl_err_span,
1011 E0053,
1012 "method `{}` has an incompatible type for trait",
1013 trait_m.name()
1014 );
1015 match &terr {
1016 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
1017 if trait_m.is_method() =>
1018 {
1019 let ty = trait_sig.inputs()[0];
1020 let sugg = get_self_string(ty, |ty| ty == impl_trait_ref.self_ty());
1021
1022 let (sig, body) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1026 let span = tcx
1027 .hir_body_param_idents(body)
1028 .zip(sig.decl.inputs.iter())
1029 .map(|(param_ident, ty)| {
1030 if let Some(param_ident) = param_ident {
1031 param_ident.span.to(ty.span)
1032 } else {
1033 ty.span
1034 }
1035 })
1036 .next()
1037 .unwrap_or(impl_err_span);
1038
1039 diag.span_suggestion_verbose(
1040 span,
1041 "change the self-receiver type to match the trait",
1042 sugg,
1043 Applicability::MachineApplicable,
1044 );
1045 }
1046 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
1047 if trait_sig.inputs().len() == *i {
1048 if let ImplItemKind::Fn(sig, _) =
1051 &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).kind
1052 && !sig.header.asyncness.is_async()
1053 {
1054 let msg = "change the output type to match the trait";
1055 let ap = Applicability::MachineApplicable;
1056 match sig.decl.output {
1057 hir::FnRetTy::DefaultReturn(sp) => {
1058 let sugg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" -> {0}", trait_sig.output()))
})format!(" -> {}", trait_sig.output());
1059 diag.span_suggestion_verbose(sp, msg, sugg, ap);
1060 }
1061 hir::FnRetTy::Return(hir_ty) => {
1062 let sugg = trait_sig.output();
1063 diag.span_suggestion_verbose(hir_ty.span, msg, sugg, ap);
1064 }
1065 };
1066 };
1067 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
1068 diag.span_suggestion_verbose(
1069 impl_err_span,
1070 "change the parameter type to match the trait",
1071 trait_ty,
1072 Applicability::MachineApplicable,
1073 );
1074 }
1075 }
1076 _ => {}
1077 }
1078
1079 cause.span = impl_err_span;
1080 infcx.err_ctxt().note_type_err(
1081 &mut diag,
1082 &cause,
1083 trait_err_span.map(|sp| (sp, Cow::from("type in trait"), false)),
1084 Some(param_env.and(infer::ValuePairs::PolySigs(ExpectedFound {
1085 expected: ty::Binder::dummy(trait_sig),
1086 found: ty::Binder::dummy(impl_sig),
1087 }))),
1088 terr,
1089 false,
1090 None,
1091 );
1092
1093 diag.emit()
1094}
1095
1096fn check_region_bounds_on_impl_item<'tcx>(
1097 tcx: TyCtxt<'tcx>,
1098 impl_m: ty::AssocItem,
1099 trait_m: ty::AssocItem,
1100 delay: bool,
1101) -> Result<(), ErrorGuaranteed> {
1102 let impl_generics = tcx.generics_of(impl_m.def_id);
1103 let impl_params = impl_generics.own_counts().lifetimes;
1104
1105 let trait_generics = tcx.generics_of(trait_m.def_id);
1106 let trait_params = trait_generics.own_counts().lifetimes;
1107
1108 let Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span }) =
1109 check_number_of_early_bound_regions(
1110 tcx,
1111 impl_m.def_id.expect_local(),
1112 trait_m.def_id,
1113 impl_generics,
1114 impl_params,
1115 trait_generics,
1116 trait_params,
1117 )
1118 else {
1119 return Ok(());
1120 };
1121
1122 if !delay && let Some(guar) = check_region_late_boundedness(tcx, impl_m, trait_m) {
1123 return Err(guar);
1124 }
1125
1126 let reported = tcx
1127 .dcx()
1128 .create_err(LifetimesOrBoundsMismatchOnTrait {
1129 span,
1130 item_kind: impl_m.descr(),
1131 ident: impl_m.ident(tcx),
1132 generics_span,
1133 bounds_span,
1134 where_span,
1135 })
1136 .emit_unless_delay(delay);
1137
1138 Err(reported)
1139}
1140
1141pub(super) struct CheckNumberOfEarlyBoundRegionsError {
1142 pub(super) span: Span,
1143 pub(super) generics_span: Span,
1144 pub(super) bounds_span: Vec<Span>,
1145 pub(super) where_span: Option<Span>,
1146}
1147
1148pub(super) fn check_number_of_early_bound_regions<'tcx>(
1149 tcx: TyCtxt<'tcx>,
1150 impl_def_id: LocalDefId,
1151 trait_def_id: DefId,
1152 impl_generics: &Generics,
1153 impl_params: usize,
1154 trait_generics: &Generics,
1155 trait_params: usize,
1156) -> Result<(), CheckNumberOfEarlyBoundRegionsError> {
1157 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:1157",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(1157u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_generics")
}> =
::tracing::__macro_support::FieldName::new("trait_generics");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_generics")
}> =
::tracing::__macro_support::FieldName::new("impl_generics");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_generics)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_generics)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?trait_generics, ?impl_generics);
1158
1159 if trait_params == impl_params {
1169 return Ok(());
1170 }
1171
1172 let span = tcx
1173 .hir_get_generics(impl_def_id)
1174 .expect("expected impl item to have generics or else we can't compare them")
1175 .span;
1176
1177 let mut generics_span = tcx.def_span(trait_def_id);
1178 let mut bounds_span = ::alloc::vec::Vec::new()vec![];
1179 let mut where_span = None;
1180
1181 if let Some(trait_node) = tcx.hir_get_if_local(trait_def_id)
1182 && let Some(trait_generics) = trait_node.generics()
1183 {
1184 generics_span = trait_generics.span;
1185 for p in trait_generics.predicates {
1188 match p.kind {
1189 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1190 bounds,
1191 ..
1192 })
1193 | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1194 bounds,
1195 ..
1196 }) => {
1197 for b in *bounds {
1198 if let hir::GenericBound::Outlives(lt) = b {
1199 bounds_span.push(lt.ident.span);
1200 }
1201 }
1202 }
1203 }
1204 }
1205 if let Some(impl_node) = tcx.hir_get_if_local(impl_def_id.into())
1206 && let Some(impl_generics) = impl_node.generics()
1207 {
1208 let mut impl_bounds = 0;
1209 for p in impl_generics.predicates {
1210 match p.kind {
1211 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1212 bounds,
1213 ..
1214 })
1215 | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1216 bounds,
1217 ..
1218 }) => {
1219 for b in *bounds {
1220 if let hir::GenericBound::Outlives(_) = b {
1221 impl_bounds += 1;
1222 }
1223 }
1224 }
1225 }
1226 }
1227 if impl_bounds == bounds_span.len() {
1228 bounds_span = ::alloc::vec::Vec::new()vec![];
1229 } else if impl_generics.has_where_clause_predicates {
1230 where_span = Some(impl_generics.where_clause_span);
1231 }
1232 }
1233 }
1234
1235 Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span })
1236}
1237
1238#[allow(unused)]
1239enum LateEarlyMismatch<'tcx> {
1240 EarlyInImpl(DefId, DefId, ty::Region<'tcx>),
1241 LateInImpl(DefId, DefId, ty::Region<'tcx>),
1242}
1243
1244fn check_region_late_boundedness<'tcx>(
1245 tcx: TyCtxt<'tcx>,
1246 impl_m: ty::AssocItem,
1247 trait_m: ty::AssocItem,
1248) -> Option<ErrorGuaranteed> {
1249 if !impl_m.is_fn() {
1250 return None;
1251 }
1252
1253 let (infcx, param_env) = tcx
1254 .infer_ctxt()
1255 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, impl_m.def_id));
1256
1257 let impl_m_args = infcx.fresh_args_for_item(DUMMY_SP, impl_m.def_id);
1258 let impl_m_sig = tcx.fn_sig(impl_m.def_id).instantiate(tcx, impl_m_args).skip_norm_wip();
1259 let impl_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, impl_m_sig);
1260
1261 let trait_m_args = infcx.fresh_args_for_item(DUMMY_SP, trait_m.def_id);
1262 let trait_m_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_args).skip_norm_wip();
1263 let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_m_sig);
1264
1265 let ocx = ObligationCtxt::new(&infcx);
1266
1267 let Ok(()) = ocx.eq(
1272 &ObligationCause::dummy(),
1273 param_env,
1274 ty::Binder::dummy(trait_m_sig),
1275 ty::Binder::dummy(impl_m_sig),
1276 ) else {
1277 return None;
1278 };
1279
1280 let errors = ocx.try_evaluate_obligations();
1281 if !errors.is_empty() {
1282 return None;
1283 }
1284
1285 let mut mismatched = ::alloc::vec::Vec::new()vec![];
1286
1287 let impl_generics = tcx.generics_of(impl_m.def_id);
1288 for (id_arg, arg) in
1289 std::iter::zip(ty::GenericArgs::identity_for_item(tcx, impl_m.def_id), impl_m_args)
1290 {
1291 if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1292 && let ty::ReVar(vid) = r.kind()
1293 && let r = infcx
1294 .inner
1295 .borrow_mut()
1296 .unwrap_region_constraints()
1297 .opportunistic_resolve_var(tcx, vid)
1298 && let ty::ReLateParam(ty::LateParamRegion {
1299 kind: ty::LateParamRegionKind::Named(trait_param_def_id),
1300 ..
1301 }) = r.kind()
1302 && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1303 {
1304 mismatched.push(LateEarlyMismatch::EarlyInImpl(
1305 impl_generics.region_param(ebr, tcx).def_id,
1306 trait_param_def_id,
1307 id_arg.expect_region(),
1308 ));
1309 }
1310 }
1311
1312 let trait_generics = tcx.generics_of(trait_m.def_id);
1313 for (id_arg, arg) in
1314 std::iter::zip(ty::GenericArgs::identity_for_item(tcx, trait_m.def_id), trait_m_args)
1315 {
1316 if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1317 && let ty::ReVar(vid) = r.kind()
1318 && let r = infcx
1319 .inner
1320 .borrow_mut()
1321 .unwrap_region_constraints()
1322 .opportunistic_resolve_var(tcx, vid)
1323 && let ty::ReLateParam(ty::LateParamRegion {
1324 kind: ty::LateParamRegionKind::Named(impl_param_def_id),
1325 ..
1326 }) = r.kind()
1327 && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1328 {
1329 mismatched.push(LateEarlyMismatch::LateInImpl(
1330 impl_param_def_id,
1331 trait_generics.region_param(ebr, tcx).def_id,
1332 id_arg.expect_region(),
1333 ));
1334 }
1335 }
1336
1337 if mismatched.is_empty() {
1338 return None;
1339 }
1340
1341 let spans: Vec<_> = mismatched
1342 .iter()
1343 .map(|param| {
1344 let (LateEarlyMismatch::EarlyInImpl(impl_param_def_id, ..)
1345 | LateEarlyMismatch::LateInImpl(impl_param_def_id, ..)) = *param;
1346 tcx.def_span(impl_param_def_id)
1347 })
1348 .collect();
1349
1350 let mut diag = tcx
1351 .dcx()
1352 .struct_span_err(spans, "lifetime parameters do not match the trait definition")
1353 .with_note("lifetime parameters differ in whether they are early- or late-bound")
1354 .with_code(E0195);
1355 for mismatch in mismatched {
1356 match mismatch {
1357 LateEarlyMismatch::EarlyInImpl(
1358 impl_param_def_id,
1359 trait_param_def_id,
1360 early_bound_region,
1361 ) => {
1362 let mut multispan = MultiSpan::from_spans(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[tcx.def_span(impl_param_def_id), tcx.def_span(trait_param_def_id)]))vec![
1363 tcx.def_span(impl_param_def_id),
1364 tcx.def_span(trait_param_def_id),
1365 ]);
1366 multispan
1367 .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1368 multispan
1369 .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1370 multispan.push_span_label(
1371 tcx.def_span(impl_param_def_id),
1372 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is early-bound",
tcx.item_name(impl_param_def_id)))
})format!("`{}` is early-bound", tcx.item_name(impl_param_def_id)),
1373 );
1374 multispan.push_span_label(
1375 tcx.def_span(trait_param_def_id),
1376 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is late-bound",
tcx.item_name(trait_param_def_id)))
})format!("`{}` is late-bound", tcx.item_name(trait_param_def_id)),
1377 );
1378 if let Some(span) =
1379 find_region_in_predicates(tcx, impl_m.def_id, early_bound_region)
1380 {
1381 multispan.push_span_label(
1382 span,
1383 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
tcx.item_name(impl_param_def_id)))
})format!(
1384 "this lifetime bound makes `{}` early-bound",
1385 tcx.item_name(impl_param_def_id)
1386 ),
1387 );
1388 }
1389 diag.span_note(
1390 multispan,
1391 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
tcx.item_name(impl_param_def_id)))
})format!(
1392 "`{}` differs between the trait and impl",
1393 tcx.item_name(impl_param_def_id)
1394 ),
1395 );
1396 }
1397 LateEarlyMismatch::LateInImpl(
1398 impl_param_def_id,
1399 trait_param_def_id,
1400 early_bound_region,
1401 ) => {
1402 let mut multispan = MultiSpan::from_spans(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[tcx.def_span(impl_param_def_id), tcx.def_span(trait_param_def_id)]))vec![
1403 tcx.def_span(impl_param_def_id),
1404 tcx.def_span(trait_param_def_id),
1405 ]);
1406 multispan
1407 .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1408 multispan
1409 .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1410 multispan.push_span_label(
1411 tcx.def_span(impl_param_def_id),
1412 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is late-bound",
tcx.item_name(impl_param_def_id)))
})format!("`{}` is late-bound", tcx.item_name(impl_param_def_id)),
1413 );
1414 multispan.push_span_label(
1415 tcx.def_span(trait_param_def_id),
1416 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is early-bound",
tcx.item_name(trait_param_def_id)))
})format!("`{}` is early-bound", tcx.item_name(trait_param_def_id)),
1417 );
1418 if let Some(span) =
1419 find_region_in_predicates(tcx, trait_m.def_id, early_bound_region)
1420 {
1421 multispan.push_span_label(
1422 span,
1423 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
tcx.item_name(trait_param_def_id)))
})format!(
1424 "this lifetime bound makes `{}` early-bound",
1425 tcx.item_name(trait_param_def_id)
1426 ),
1427 );
1428 }
1429 diag.span_note(
1430 multispan,
1431 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
tcx.item_name(impl_param_def_id)))
})format!(
1432 "`{}` differs between the trait and impl",
1433 tcx.item_name(impl_param_def_id)
1434 ),
1435 );
1436 }
1437 }
1438 }
1439
1440 Some(diag.emit())
1441}
1442
1443fn find_region_in_predicates<'tcx>(
1444 tcx: TyCtxt<'tcx>,
1445 def_id: DefId,
1446 early_bound_region: ty::Region<'tcx>,
1447) -> Option<Span> {
1448 for (pred, span) in tcx.explicit_predicates_of(def_id).instantiate_identity(tcx) {
1449 if pred.skip_norm_wip().visit_with(&mut FindRegion(early_bound_region)).is_break() {
1450 return Some(span);
1451 }
1452 }
1453
1454 struct FindRegion<'tcx>(ty::Region<'tcx>);
1455 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindRegion<'tcx> {
1456 type Result = ControlFlow<()>;
1457 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
1458 if r == self.0 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
1459 }
1460 }
1461
1462 None
1463}
1464
1465#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("extract_spans_for_error_reporting",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(1465u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("terr")
}> =
::tracing::__macro_support::FieldName::new("terr");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("cause")
}> =
::tracing::__macro_support::FieldName::new("cause");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_m")
}> =
::tracing::__macro_support::FieldName::new("impl_m");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_m")
}> =
::tracing::__macro_support::FieldName::new("trait_m");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&terr)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_m)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_m)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: (Span, Option<Span>) = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = infcx.tcx;
let mut impl_args =
{
let (sig, _) =
tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
sig.decl.inputs.iter().map(|t|
t.span).chain(iter::once(sig.decl.output.span()))
};
let trait_args =
trait_m.def_id.as_local().map(|def_id|
{
let (sig, _) =
tcx.hir_expect_trait_item(def_id).expect_fn();
sig.decl.inputs.iter().map(|t|
t.span).chain(iter::once(sig.decl.output.span()))
});
match terr {
TypeError::ArgumentMutability(i) |
TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
(impl_args.nth(i).unwrap(),
trait_args.and_then(|mut args| args.nth(i)))
}
_ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
}
}
}
}#[instrument(level = "debug", skip(infcx))]
1466fn extract_spans_for_error_reporting<'tcx>(
1467 infcx: &infer::InferCtxt<'tcx>,
1468 terr: TypeError<'_>,
1469 cause: &ObligationCause<'tcx>,
1470 impl_m: ty::AssocItem,
1471 trait_m: ty::AssocItem,
1472) -> (Span, Option<Span>) {
1473 let tcx = infcx.tcx;
1474 let mut impl_args = {
1475 let (sig, _) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1476 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1477 };
1478
1479 let trait_args = trait_m.def_id.as_local().map(|def_id| {
1480 let (sig, _) = tcx.hir_expect_trait_item(def_id).expect_fn();
1481 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1482 });
1483
1484 match terr {
1485 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1486 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1487 }
1488 _ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
1489 }
1490}
1491
1492fn compare_self_type<'tcx>(
1493 tcx: TyCtxt<'tcx>,
1494 impl_m: ty::AssocItem,
1495 trait_m: ty::AssocItem,
1496 impl_trait_ref: ty::TraitRef<'tcx>,
1497 delay: bool,
1498) -> Result<(), ErrorGuaranteed> {
1499 let self_string = |method: ty::AssocItem| {
1508 let untransformed_self_ty = match method.container {
1509 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1510 impl_trait_ref.self_ty()
1511 }
1512 ty::AssocContainer::Trait => tcx.types.self_param,
1513 };
1514 let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip().input(0);
1515 let (infcx, param_env) = tcx
1516 .infer_ctxt()
1517 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, method.def_id));
1518 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1519 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
1520 get_self_string(self_arg_ty, can_eq_self)
1521 };
1522
1523 match (trait_m.is_method(), impl_m.is_method()) {
1524 (false, false) | (true, true) => {}
1525
1526 (false, true) => {
1527 let self_descr = self_string(impl_m);
1528 let impl_m_span = tcx.def_span(impl_m.def_id);
1529 let mut err = {
tcx.dcx().struct_span_err(impl_m_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("method `{0}` has a `{1}` declaration in the impl, but not in the trait",
trait_m.name(), self_descr))
})).with_code(E0185)
}struct_span_code_err!(
1530 tcx.dcx(),
1531 impl_m_span,
1532 E0185,
1533 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1534 trait_m.name(),
1535 self_descr
1536 );
1537 err.span_label(impl_m_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` used in impl", self_descr))
})format!("`{self_descr}` used in impl"));
1538 if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1539 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait method declared without `{0}`",
self_descr))
})format!("trait method declared without `{self_descr}`"));
1540 } else {
1541 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1542 }
1543 return Err(err.emit_unless_delay(delay));
1544 }
1545
1546 (true, false) => {
1547 let self_descr = self_string(trait_m);
1548 let impl_m_span = tcx.def_span(impl_m.def_id);
1549 let mut err = {
tcx.dcx().struct_span_err(impl_m_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("method `{0}` has a `{1}` declaration in the trait, but not in the impl",
trait_m.name(), self_descr))
})).with_code(E0186)
}struct_span_code_err!(
1550 tcx.dcx(),
1551 impl_m_span,
1552 E0186,
1553 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1554 trait_m.name(),
1555 self_descr
1556 );
1557 err.span_label(impl_m_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}` in impl",
self_descr))
})format!("expected `{self_descr}` in impl"));
1558 if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1559 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` used in trait", self_descr))
})format!("`{self_descr}` used in trait"));
1560 } else {
1561 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1562 }
1563
1564 return Err(err.emit_unless_delay(delay));
1565 }
1566 }
1567
1568 Ok(())
1569}
1570
1571fn compare_number_of_generics<'tcx>(
1593 tcx: TyCtxt<'tcx>,
1594 impl_: ty::AssocItem,
1595 trait_: ty::AssocItem,
1596 delay: bool,
1597) -> Result<(), ErrorGuaranteed> {
1598 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1599 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1600
1601 if (trait_own_counts.types + trait_own_counts.consts)
1605 == (impl_own_counts.types + impl_own_counts.consts)
1606 {
1607 return Ok(());
1608 }
1609
1610 if trait_.is_impl_trait_in_trait() {
1615 tcx.dcx()
1618 .bug("errors comparing numbers of generics of trait/impl functions were not emitted");
1619 }
1620
1621 let matchings = [
1622 ("type", trait_own_counts.types, impl_own_counts.types),
1623 ("const", trait_own_counts.consts, impl_own_counts.consts),
1624 ];
1625
1626 let item_kind = impl_.descr();
1627
1628 let mut err_occurred = None;
1629 for (kind, trait_count, impl_count) in matchings {
1630 if impl_count != trait_count {
1631 let arg_spans = |item: &ty::AssocItem, generics: &hir::Generics<'_>| {
1632 let mut spans = generics
1633 .params
1634 .iter()
1635 .filter(|p| match p.kind {
1636 hir::GenericParamKind::Lifetime {
1637 kind: hir::LifetimeParamKind::Elided(_),
1638 } => {
1639 !item.is_fn()
1642 }
1643 _ => true,
1644 })
1645 .map(|p| p.span)
1646 .collect::<Vec<Span>>();
1647 if spans.is_empty() {
1648 spans = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[generics.span]))vec![generics.span]
1649 }
1650 spans
1651 };
1652 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1653 let trait_item = tcx.hir_expect_trait_item(def_id);
1654 let arg_spans: Vec<Span> = arg_spans(&trait_, trait_item.generics);
1655 let impl_trait_spans: Vec<Span> = trait_item
1656 .generics
1657 .params
1658 .iter()
1659 .filter_map(|p| match p.kind {
1660 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1661 _ => None,
1662 })
1663 .collect();
1664 (Some(arg_spans), impl_trait_spans)
1665 } else {
1666 let trait_span = tcx.hir_span_if_local(trait_.def_id);
1667 (trait_span.map(|s| ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[s]))vec![s]), ::alloc::vec::Vec::new()vec![])
1668 };
1669
1670 let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
1671 let impl_item_impl_trait_spans: Vec<Span> = impl_item
1672 .generics
1673 .params
1674 .iter()
1675 .filter_map(|p| match p.kind {
1676 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1677 _ => None,
1678 })
1679 .collect();
1680 let spans = arg_spans(&impl_, impl_item.generics);
1681 let span = spans.first().copied();
1682
1683 let mut err = tcx.dcx().struct_span_err(
1684 spans,
1685 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` has {2} {6} parameter{3} but its trait declaration has {4} {6} parameter{5}",
item_kind, trait_.name(), impl_count,
if impl_count == 1 { "" } else { "s" }, trait_count,
if trait_count == 1 { "" } else { "s" }, kind))
})format!(
1686 "{} `{}` has {} {kind} parameter{} but its trait \
1687 declaration has {} {kind} parameter{}",
1688 item_kind,
1689 trait_.name(),
1690 impl_count,
1691 pluralize!(impl_count),
1692 trait_count,
1693 pluralize!(trait_count),
1694 kind = kind,
1695 ),
1696 );
1697 err.code(E0049);
1698
1699 let msg =
1700 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {1} {2} parameter{0}",
if trait_count == 1 { "" } else { "s" }, trait_count, kind))
})format!("expected {trait_count} {kind} parameter{}", pluralize!(trait_count),);
1701 if let Some(spans) = trait_spans {
1702 let mut spans = spans.iter();
1703 if let Some(span) = spans.next() {
1704 err.span_label(*span, msg);
1705 }
1706 for span in spans {
1707 err.span_label(*span, "");
1708 }
1709 } else {
1710 err.span_label(tcx.def_span(trait_.def_id), msg);
1711 }
1712
1713 if let Some(span) = span {
1714 err.span_label(
1715 span,
1716 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("found {0} {1} parameter{2}",
impl_count, kind, if impl_count == 1 { "" } else { "s" }))
})format!("found {} {} parameter{}", impl_count, kind, pluralize!(impl_count),),
1717 );
1718 }
1719
1720 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1721 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1722 }
1723
1724 let reported = err.emit_unless_delay(delay);
1725 err_occurred = Some(reported);
1726 }
1727 }
1728
1729 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1730}
1731
1732fn compare_number_of_method_arguments<'tcx>(
1733 tcx: TyCtxt<'tcx>,
1734 impl_m: ty::AssocItem,
1735 trait_m: ty::AssocItem,
1736 delay: bool,
1737) -> Result<(), ErrorGuaranteed> {
1738 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1739 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1740 let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
1741 let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1742
1743 if trait_number_args != impl_number_args {
1744 let trait_span = trait_m
1745 .def_id
1746 .as_local()
1747 .and_then(|def_id| {
1748 let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
1749 let pos = trait_number_args.saturating_sub(1);
1750 trait_m_sig.decl.inputs.get(pos).map(|arg| {
1751 if pos == 0 {
1752 arg.span
1753 } else {
1754 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1755 }
1756 })
1757 })
1758 .or_else(|| tcx.hir_span_if_local(trait_m.def_id));
1759
1760 let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1761 let pos = impl_number_args.saturating_sub(1);
1762 let impl_span = impl_m_sig
1763 .decl
1764 .inputs
1765 .get(pos)
1766 .map(|arg| {
1767 if pos == 0 {
1768 arg.span
1769 } else {
1770 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1771 }
1772 })
1773 .unwrap_or_else(|| tcx.def_span(impl_m.def_id));
1774
1775 let mut err = {
tcx.dcx().struct_span_err(impl_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("method `{0}` has {1} but the declaration in trait `{2}` has {3}",
trait_m.name(),
potentially_plural_count(impl_number_args, "parameter"),
tcx.def_path_str(trait_m.def_id), trait_number_args))
})).with_code(E0050)
}struct_span_code_err!(
1776 tcx.dcx(),
1777 impl_span,
1778 E0050,
1779 "method `{}` has {} but the declaration in trait `{}` has {}",
1780 trait_m.name(),
1781 potentially_plural_count(impl_number_args, "parameter"),
1782 tcx.def_path_str(trait_m.def_id),
1783 trait_number_args
1784 );
1785
1786 if let Some(trait_span) = trait_span {
1787 err.span_label(
1788 trait_span,
1789 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait requires {0}",
potentially_plural_count(trait_number_args, "parameter")))
})format!(
1790 "trait requires {}",
1791 potentially_plural_count(trait_number_args, "parameter")
1792 ),
1793 );
1794 } else {
1795 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1796 }
1797
1798 err.span_label(
1799 impl_span,
1800 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}, found {1}",
potentially_plural_count(trait_number_args, "parameter"),
impl_number_args))
})format!(
1801 "expected {}, found {}",
1802 potentially_plural_count(trait_number_args, "parameter"),
1803 impl_number_args
1804 ),
1805 );
1806
1807 if !trait_m.def_id.is_local() {
1809 let trait_sig = tcx.fn_sig(trait_m.def_id);
1810 let trait_arg_idents = tcx.fn_arg_idents(trait_m.def_id);
1811 let sm = tcx.sess.source_map();
1812 let impl_inputs_span = if let (Some(first), Some(last)) =
1816 (impl_m_sig.decl.inputs.first(), impl_m_sig.decl.inputs.last())
1817 {
1818 let arg_idents = tcx.fn_arg_idents(impl_m.def_id);
1822 let first_lo = arg_idents
1823 .get(0)
1824 .and_then(|id| id.map(|id| id.span.lo()))
1825 .unwrap_or(first.span.lo());
1826 Some(impl_m_sig.span.with_lo(first_lo).with_hi(last.span.hi()))
1827 } else {
1828 sm.span_to_snippet(impl_m_sig.span).ok().and_then(|s| {
1833 let right_paren = s.as_bytes().iter().rposition(|&b| b == b')')?;
1834 let pos = impl_m_sig.span.lo() + BytePos(right_paren as u32);
1835 Some(impl_m_sig.span.with_lo(pos).with_hi(pos))
1836 })
1837 };
1838 let suggestion = match trait_number_args.cmp(&impl_number_args) {
1839 Ordering::Greater => {
1840 let trait_inputs = trait_sig.skip_binder().inputs().skip_binder();
1844 let missing = trait_inputs
1845 .iter()
1846 .enumerate()
1847 .skip(impl_number_args)
1848 .map(|(idx, ty)| {
1849 let name = trait_arg_idents
1850 .get(idx)
1851 .and_then(|ident| *ident)
1852 .map(|ident| ident.to_string())
1853 .unwrap_or_else(|| "_".to_string());
1854 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", name, ty))
})format!("{name}: {ty}")
1855 })
1856 .collect::<Vec<_>>();
1857
1858 if missing.is_empty() {
1859 None
1860 } else {
1861 impl_inputs_span.map(|s| {
1862 let span = s.shrink_to_hi();
1863 let prefix = if impl_number_args == 0 { "" } else { ", " };
1864 let replacement = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}", missing.join(", "),
prefix))
})format!("{prefix}{}", missing.join(", "));
1865 (
1866 span,
1867 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add the missing parameter{0} from the trait",
if trait_number_args - impl_number_args == 1 {
""
} else { "s" }))
})format!(
1868 "add the missing parameter{} from the trait",
1869 pluralize!(trait_number_args - impl_number_args)
1870 ),
1871 replacement,
1872 )
1873 })
1874 }
1875 }
1876 Ordering::Less => impl_inputs_span.and_then(|full| {
1877 let lo = if trait_number_args == 0 {
1881 full.lo()
1882 } else {
1883 impl_m_sig
1884 .decl
1885 .inputs
1886 .get(trait_number_args - 1)
1887 .map(|arg| arg.span.hi())?
1888 };
1889 let span = full.with_lo(lo);
1890 Some((
1891 span,
1892 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("remove the extra parameter{0} to match the trait",
if impl_number_args - trait_number_args == 1 {
""
} else { "s" }))
})format!(
1893 "remove the extra parameter{} to match the trait",
1894 pluralize!(impl_number_args - trait_number_args)
1895 ),
1896 String::new(),
1897 ))
1898 }),
1899 Ordering::Equal => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1900 };
1901 if let Some((span, msg, replacement)) = suggestion {
1902 err.span_suggestion_verbose(span, msg, replacement, Applicability::MaybeIncorrect);
1903 }
1904 }
1905
1906 return Err(err.emit_unless_delay(delay));
1907 }
1908
1909 Ok(())
1910}
1911
1912fn compare_synthetic_generics<'tcx>(
1913 tcx: TyCtxt<'tcx>,
1914 impl_m: ty::AssocItem,
1915 trait_m: ty::AssocItem,
1916 delay: bool,
1917) -> Result<(), ErrorGuaranteed> {
1918 let mut error_found = None;
1924 let impl_m_generics = tcx.generics_of(impl_m.def_id);
1925 let trait_m_generics = tcx.generics_of(trait_m.def_id);
1926 let impl_m_type_params =
1927 impl_m_generics.own_params.iter().filter_map(|param| match param.kind {
1928 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1929 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1930 });
1931 let trait_m_type_params =
1932 trait_m_generics.own_params.iter().filter_map(|param| match param.kind {
1933 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1934 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1935 });
1936 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1937 iter::zip(impl_m_type_params, trait_m_type_params)
1938 {
1939 if impl_synthetic != trait_synthetic {
1940 let impl_def_id = impl_def_id.expect_local();
1941 let impl_span = tcx.def_span(impl_def_id);
1942 let trait_span = tcx.def_span(trait_def_id);
1943 let mut err = {
tcx.dcx().struct_span_err(impl_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("method `{0}` has incompatible signature for trait",
trait_m.name()))
})).with_code(E0643)
}struct_span_code_err!(
1944 tcx.dcx(),
1945 impl_span,
1946 E0643,
1947 "method `{}` has incompatible signature for trait",
1948 trait_m.name()
1949 );
1950 err.span_label(trait_span, "declaration in trait here");
1951 if impl_synthetic {
1952 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1955 try {
1956 let new_name = tcx.opt_item_name(trait_def_id)?;
1960 let trait_m = trait_m.def_id.as_local()?;
1961 let trait_m = tcx.hir_expect_trait_item(trait_m);
1962
1963 let impl_m = impl_m.def_id.as_local()?;
1964 let impl_m = tcx.hir_expect_impl_item(impl_m);
1965
1966 let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1969 let generics_span = impl_m.generics.span.substitute_dummy(new_generics_span);
1971 let new_generics =
1973 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1974
1975 err.multipart_suggestion(
1976 "try changing the `impl Trait` argument to a generic parameter",
1977 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(impl_span, new_name.to_string()), (generics_span, new_generics)]))vec![
1978 (impl_span, new_name.to_string()),
1980 (generics_span, new_generics),
1984 ],
1985 Applicability::MaybeIncorrect,
1986 );
1987 };
1988 } else {
1989 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1992 try {
1993 let impl_m = impl_m.def_id.as_local()?;
1994 let impl_m = tcx.hir_expect_impl_item(impl_m);
1995 let (sig, _) = impl_m.expect_fn();
1996 let input_tys = sig.decl.inputs;
1997
1998 struct Visitor(hir::def_id::LocalDefId);
1999 impl<'v> intravisit::Visitor<'v> for Visitor {
2000 type Result = ControlFlow<Span>;
2001 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) -> Self::Result {
2002 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
2003 && let Res::Def(DefKind::TyParam, def_id) = path.res
2004 && def_id == self.0.to_def_id()
2005 {
2006 ControlFlow::Break(ty.span)
2007 } else {
2008 intravisit::walk_ty(self, ty)
2009 }
2010 }
2011 }
2012
2013 let span = input_tys
2014 .iter()
2015 .find_map(|ty| Visitor(impl_def_id).visit_ty_unambig(ty).break_value())?;
2016
2017 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
2018 let bounds = bounds.first()?.span().to(bounds.last()?.span());
2019 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
2020
2021 err.multipart_suggestion(
2022 "try removing the generic parameter and using `impl Trait` instead",
2023 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(impl_m.generics.span, String::new()),
(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("impl {0}", bounds))
}))]))vec![
2024 (impl_m.generics.span, String::new()),
2026 (span, format!("impl {bounds}")),
2028 ],
2029 Applicability::MaybeIncorrect,
2030 );
2031 };
2032 }
2033 error_found = Some(err.emit_unless_delay(delay));
2034 }
2035 }
2036 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
2037}
2038
2039fn compare_generic_param_kinds<'tcx>(
2065 tcx: TyCtxt<'tcx>,
2066 impl_item: ty::AssocItem,
2067 trait_item: ty::AssocItem,
2068 delay: bool,
2069) -> Result<(), ErrorGuaranteed> {
2070 {
match (&impl_item.tag(), &trait_item.tag()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(impl_item.tag(), trait_item.tag());
2071
2072 let ty_const_params_of = |def_id| {
2073 tcx.generics_of(def_id).own_params.iter().filter(|param| {
2074 #[allow(non_exhaustive_omitted_patterns)] match param.kind {
GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. } =>
true,
_ => false,
}matches!(
2075 param.kind,
2076 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
2077 )
2078 })
2079 };
2080
2081 for (param_impl, param_trait) in
2082 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
2083 {
2084 use GenericParamDefKind::*;
2085 if match (¶m_impl.kind, ¶m_trait.kind) {
2086 (Const { .. }, Const { .. })
2087 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
2088 {
2089 true
2090 }
2091 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
2092 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
2095 (Lifetime { .. }, _) | (_, Lifetime { .. }) => {
2096 ::rustc_middle::util::bug::bug_fmt(format_args!("lifetime params are expected to be filtered by `ty_const_params_of`"))bug!("lifetime params are expected to be filtered by `ty_const_params_of`")
2097 }
2098 } {
2099 let param_impl_span = tcx.def_span(param_impl.def_id);
2100 let param_trait_span = tcx.def_span(param_trait.def_id);
2101
2102 let mut err = {
tcx.dcx().struct_span_err(param_impl_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` has an incompatible generic parameter for trait `{2}`",
impl_item.descr(), trait_item.name(),
&tcx.def_path_str(tcx.parent(trait_item.def_id))))
})).with_code(E0053)
}struct_span_code_err!(
2103 tcx.dcx(),
2104 param_impl_span,
2105 E0053,
2106 "{} `{}` has an incompatible generic parameter for trait `{}`",
2107 impl_item.descr(),
2108 trait_item.name(),
2109 &tcx.def_path_str(tcx.parent(trait_item.def_id))
2110 );
2111
2112 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
2113 Const { .. } => {
2114 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} const parameter of type `{1}`",
prefix,
tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip()))
})format!(
2115 "{} const parameter of type `{}`",
2116 prefix,
2117 tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip()
2118 )
2119 }
2120 Type { .. } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} type parameter", prefix))
})format!("{prefix} type parameter"),
2121 Lifetime { .. } => ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(param.def_id),
format_args!("lifetime params are expected to be filtered by `ty_const_params_of`"))span_bug!(
2122 tcx.def_span(param.def_id),
2123 "lifetime params are expected to be filtered by `ty_const_params_of`"
2124 ),
2125 };
2126
2127 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
2128 err.span_label(trait_header_span, "");
2129 err.span_label(param_trait_span, make_param_message("expected", param_trait));
2130
2131 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
2132 err.span_label(impl_header_span, "");
2133 err.span_label(param_impl_span, make_param_message("found", param_impl));
2134
2135 let reported = err.emit_unless_delay(delay);
2136 return Err(reported);
2137 }
2138 }
2139
2140 Ok(())
2141}
2142
2143fn compare_impl_const<'tcx>(
2144 tcx: TyCtxt<'tcx>,
2145 impl_const_item: ty::AssocItem,
2146 trait_const_item: ty::AssocItem,
2147 impl_trait_ref: ty::TraitRef<'tcx>,
2148) -> Result<(), ErrorGuaranteed> {
2149 compare_type_const(tcx, impl_const_item, trait_const_item)?;
2150 compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
2151 compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
2152 check_region_bounds_on_impl_item(tcx, impl_const_item, trait_const_item, false)?;
2153 compare_const_predicate_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
2154}
2155
2156fn compare_type_const<'tcx>(
2157 tcx: TyCtxt<'tcx>,
2158 impl_const_item: ty::AssocItem,
2159 trait_const_item: ty::AssocItem,
2160) -> Result<(), ErrorGuaranteed> {
2161 let impl_is_type_const = tcx.is_type_const(impl_const_item.def_id);
2162 let trait_type_const_span = tcx.type_const_span(trait_const_item.def_id);
2163
2164 if let Some(trait_type_const_span) = trait_type_const_span
2165 && !impl_is_type_const
2166 {
2167 return Err(tcx
2168 .dcx()
2169 .struct_span_err(
2170 tcx.def_span(impl_const_item.def_id),
2171 "implementation of a `type const` must also be marked as `type const`",
2172 )
2173 .with_span_note(
2174 MultiSpan::from_spans(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[tcx.def_span(trait_const_item.def_id), trait_type_const_span]))vec![
2175 tcx.def_span(trait_const_item.def_id),
2176 trait_type_const_span,
2177 ]),
2178 "trait declaration of const is marked as `type const`",
2179 )
2180 .emit());
2181 }
2182 Ok(())
2183}
2184
2185#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("compare_const_predicate_entailment",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2188u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_ct")
}> =
::tracing::__macro_support::FieldName::new("impl_ct");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ct")
}> =
::tracing::__macro_support::FieldName::new("trait_ct");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("impl_trait_ref");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ct)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ct)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let impl_ct_def_id = impl_ct.def_id.expect_local();
let impl_ct_span = tcx.def_span(impl_ct_def_id);
let trait_to_impl_args =
GenericArgs::identity_for_item(tcx,
impl_ct.def_id).rebase_onto(tcx, impl_ct.container_id(tcx),
impl_trait_ref.args);
let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
let trait_ty =
tcx.type_of(trait_ct.def_id).instantiate(tcx,
trait_to_impl_args);
let code =
ObligationCauseCode::CompareImplItem {
impl_item_def_id: impl_ct_def_id,
trait_item_def_id: trait_ct.def_id,
kind: impl_ct.kind,
};
let mut cause =
ObligationCause::new(impl_ct_span, impl_ct_def_id,
code.clone());
let impl_ct_predicates = tcx.predicates_of(impl_ct.def_id);
let trait_ct_predicates = tcx.predicates_of(trait_ct.def_id);
let impl_predicates =
tcx.predicates_of(impl_ct_predicates.parent.unwrap());
let mut hybrid_preds =
impl_predicates.instantiate_identity(tcx).predicates;
hybrid_preds.extend(trait_ct_predicates.instantiate_own(tcx,
trait_to_impl_args).map(|(predicate, _)| predicate));
let hybrid_preds =
hybrid_preds.into_iter().map(Unnormalized::skip_norm_wip);
let param_env =
ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
let param_env =
traits::normalize_param_env_or_error(tcx, param_env,
ObligationCause::misc(impl_ct_span, impl_ct_def_id));
let infcx =
tcx.infer_ctxt().build(TypingMode::non_body_analysis());
let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
let impl_ct_own_bounds =
impl_ct_predicates.instantiate_own_identity();
for (predicate, span) in impl_ct_own_bounds {
let cause = ObligationCause::misc(span, impl_ct_def_id);
let predicate = ocx.normalize(&cause, param_env, predicate);
let cause =
ObligationCause::new(span, impl_ct_def_id, code.clone());
ocx.register_obligation(traits::Obligation::new(tcx, cause,
param_env, predicate));
}
let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2256",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2256u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_ty")
}> =
::tracing::__macro_support::FieldName::new("impl_ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2259",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2259u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ty")
}> =
::tracing::__macro_support::FieldName::new("trait_ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
if let Err(terr) = err {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2264",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2264u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_ty")
}> =
::tracing::__macro_support::FieldName::new("impl_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ty")
}> =
::tracing::__macro_support::FieldName::new("trait_ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let (ty, _) =
tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
cause.span = ty.span;
let mut diag =
{
tcx.dcx().struct_span_err(cause.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("implemented const `{0}` has an incompatible type for trait",
trait_ct.name()))
})).with_code(E0326)
};
let trait_c_span =
trait_ct.def_id.as_local().map(|trait_ct_def_id|
{
let (ty, _) =
tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
ty.span
});
infcx.err_ctxt().note_type_err(&mut diag, &cause,
trait_c_span.map(|span|
(span, Cow::from("type in trait"), false)),
Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
expected: trait_ty.into(),
found: impl_ty.into(),
}))), terr, false, None);
return Err(diag.emit());
};
let errors = ocx.evaluate_obligations_error_on_ambiguity();
if !errors.is_empty() {
return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
}
ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env,
[])
}
}
}#[instrument(level = "debug", skip(tcx))]
2189fn compare_const_predicate_entailment<'tcx>(
2190 tcx: TyCtxt<'tcx>,
2191 impl_ct: ty::AssocItem,
2192 trait_ct: ty::AssocItem,
2193 impl_trait_ref: ty::TraitRef<'tcx>,
2194) -> Result<(), ErrorGuaranteed> {
2195 let impl_ct_def_id = impl_ct.def_id.expect_local();
2196 let impl_ct_span = tcx.def_span(impl_ct_def_id);
2197
2198 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id).rebase_onto(
2204 tcx,
2205 impl_ct.container_id(tcx),
2206 impl_trait_ref.args,
2207 );
2208
2209 let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
2212
2213 let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
2214 let code = ObligationCauseCode::CompareImplItem {
2215 impl_item_def_id: impl_ct_def_id,
2216 trait_item_def_id: trait_ct.def_id,
2217 kind: impl_ct.kind,
2218 };
2219 let mut cause = ObligationCause::new(impl_ct_span, impl_ct_def_id, code.clone());
2220
2221 let impl_ct_predicates = tcx.predicates_of(impl_ct.def_id);
2222 let trait_ct_predicates = tcx.predicates_of(trait_ct.def_id);
2223
2224 let impl_predicates = tcx.predicates_of(impl_ct_predicates.parent.unwrap());
2227 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2228 hybrid_preds.extend(
2229 trait_ct_predicates
2230 .instantiate_own(tcx, trait_to_impl_args)
2231 .map(|(predicate, _)| predicate),
2232 );
2233 let hybrid_preds = hybrid_preds.into_iter().map(Unnormalized::skip_norm_wip);
2234
2235 let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
2236 let param_env = traits::normalize_param_env_or_error(
2237 tcx,
2238 param_env,
2239 ObligationCause::misc(impl_ct_span, impl_ct_def_id),
2240 );
2241
2242 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2243 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2244
2245 let impl_ct_own_bounds = impl_ct_predicates.instantiate_own_identity();
2246 for (predicate, span) in impl_ct_own_bounds {
2247 let cause = ObligationCause::misc(span, impl_ct_def_id);
2248 let predicate = ocx.normalize(&cause, param_env, predicate);
2249
2250 let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
2251 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2252 }
2253
2254 let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
2256 debug!(?impl_ty);
2257
2258 let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
2259 debug!(?trait_ty);
2260
2261 let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
2262
2263 if let Err(terr) = err {
2264 debug!(?impl_ty, ?trait_ty);
2265
2266 let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
2268 cause.span = ty.span;
2269
2270 let mut diag = struct_span_code_err!(
2271 tcx.dcx(),
2272 cause.span,
2273 E0326,
2274 "implemented const `{}` has an incompatible type for trait",
2275 trait_ct.name()
2276 );
2277
2278 let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
2279 let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
2281 ty.span
2282 });
2283
2284 infcx.err_ctxt().note_type_err(
2285 &mut diag,
2286 &cause,
2287 trait_c_span.map(|span| (span, Cow::from("type in trait"), false)),
2288 Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2289 expected: trait_ty.into(),
2290 found: impl_ty.into(),
2291 }))),
2292 terr,
2293 false,
2294 None,
2295 );
2296 return Err(diag.emit());
2297 };
2298
2299 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2302 if !errors.is_empty() {
2303 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2304 }
2305
2306 ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env, [])
2307}
2308
2309#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("compare_impl_ty",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2309u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_ty")
}> =
::tracing::__macro_support::FieldName::new("impl_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ty")
}> =
::tracing::__macro_support::FieldName::new("trait_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("impl_trait_ref");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
compare_type_predicate_entailment(tcx, impl_ty, trait_ty,
impl_trait_ref)?;
check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
}
}
}#[instrument(level = "debug", skip(tcx))]
2310fn compare_impl_ty<'tcx>(
2311 tcx: TyCtxt<'tcx>,
2312 impl_ty: ty::AssocItem,
2313 trait_ty: ty::AssocItem,
2314 impl_trait_ref: ty::TraitRef<'tcx>,
2315) -> Result<(), ErrorGuaranteed> {
2316 compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
2317 compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
2318 check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
2319 compare_type_predicate_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
2320 check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
2321}
2322
2323#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("compare_type_predicate_entailment",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2325u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_ty")
}> =
::tracing::__macro_support::FieldName::new("impl_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ty")
}> =
::tracing::__macro_support::FieldName::new("trait_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("impl_trait_ref");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let impl_def_id = impl_ty.container_id(tcx);
let trait_to_impl_args =
GenericArgs::identity_for_item(tcx,
impl_ty.def_id).rebase_onto(tcx, impl_def_id,
impl_trait_ref.args);
let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
let impl_ty_own_bounds =
impl_ty_predicates.instantiate_own_identity();
if impl_ty_own_bounds.len() == 0 { return Ok(()); }
let impl_ty_def_id = impl_ty.def_id.expect_local();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2353",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2353u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_to_impl_args")
}> =
::tracing::__macro_support::FieldName::new("trait_to_impl_args");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_to_impl_args)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let impl_predicates =
tcx.predicates_of(impl_ty_predicates.parent.unwrap());
let mut hybrid_preds =
impl_predicates.instantiate_identity(tcx).predicates;
hybrid_preds.extend(trait_ty_predicates.instantiate_own(tcx,
trait_to_impl_args).map(|(predicate, _)| predicate));
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2364",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2364u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("hybrid_preds")
}> =
::tracing::__macro_support::FieldName::new("hybrid_preds");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hybrid_preds)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let impl_ty_span = tcx.def_span(impl_ty_def_id);
let normalize_cause =
ObligationCause::misc(impl_ty_span, impl_ty_def_id);
let is_conditionally_const =
tcx.is_conditionally_const(impl_ty.def_id);
if is_conditionally_const {
hybrid_preds.extend(tcx.const_conditions(impl_ty_predicates.parent.unwrap()).instantiate_identity(tcx).into_iter().chain(tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx,
trait_to_impl_args)).map(|(trait_ref, _)|
{
trait_ref.to_host_effect_clause(tcx,
ty::BoundConstness::Maybe)
}));
}
let hybrid_preds =
hybrid_preds.into_iter().map(Unnormalized::skip_norm_wip);
let param_env =
ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
let param_env =
traits::normalize_param_env_or_error(tcx, param_env,
normalize_cause);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2389",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2389u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("caller_bounds")
}> =
::tracing::__macro_support::FieldName::new("caller_bounds");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_env.caller_bounds())
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let infcx =
tcx.infer_ctxt().build(TypingMode::non_body_analysis());
let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
for (predicate, span) in impl_ty_own_bounds {
let cause = ObligationCause::misc(span, impl_ty_def_id);
let predicate = ocx.normalize(&cause, param_env, predicate);
let cause =
ObligationCause::new(span, impl_ty_def_id,
ObligationCauseCode::CompareImplItem {
impl_item_def_id: impl_ty.def_id.expect_local(),
trait_item_def_id: trait_ty.def_id,
kind: impl_ty.kind,
});
ocx.register_obligation(traits::Obligation::new(tcx, cause,
param_env, predicate));
}
if is_conditionally_const {
let impl_ty_own_const_conditions =
tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
for (const_condition, span) in impl_ty_own_const_conditions {
let normalize_cause =
traits::ObligationCause::misc(span, impl_ty_def_id);
let const_condition =
ocx.normalize(&normalize_cause, param_env, const_condition);
let cause =
ObligationCause::new(span, impl_ty_def_id,
ObligationCauseCode::CompareImplItem {
impl_item_def_id: impl_ty_def_id,
trait_item_def_id: trait_ty.def_id,
kind: impl_ty.kind,
});
ocx.register_obligation(traits::Obligation::new(tcx, cause,
param_env,
const_condition.to_host_effect_clause(tcx,
ty::BoundConstness::Maybe)));
}
}
let errors = ocx.evaluate_obligations_error_on_ambiguity();
if !errors.is_empty() {
let reported =
infcx.err_ctxt().report_fulfillment_errors(errors);
return Err(reported);
}
ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env,
[])
}
}
}#[instrument(level = "debug", skip(tcx))]
2326fn compare_type_predicate_entailment<'tcx>(
2327 tcx: TyCtxt<'tcx>,
2328 impl_ty: ty::AssocItem,
2329 trait_ty: ty::AssocItem,
2330 impl_trait_ref: ty::TraitRef<'tcx>,
2331) -> Result<(), ErrorGuaranteed> {
2332 let impl_def_id = impl_ty.container_id(tcx);
2333 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
2334 tcx,
2335 impl_def_id,
2336 impl_trait_ref.args,
2337 );
2338
2339 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
2340 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
2341
2342 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own_identity();
2343 if impl_ty_own_bounds.len() == 0 {
2345 return Ok(());
2347 }
2348
2349 let impl_ty_def_id = impl_ty.def_id.expect_local();
2353 debug!(?trait_to_impl_args);
2354
2355 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
2358 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2359 hybrid_preds.extend(
2360 trait_ty_predicates
2361 .instantiate_own(tcx, trait_to_impl_args)
2362 .map(|(predicate, _)| predicate),
2363 );
2364 debug!(?hybrid_preds);
2365
2366 let impl_ty_span = tcx.def_span(impl_ty_def_id);
2367 let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
2368
2369 let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
2370 if is_conditionally_const {
2371 hybrid_preds.extend(
2374 tcx.const_conditions(impl_ty_predicates.parent.unwrap())
2375 .instantiate_identity(tcx)
2376 .into_iter()
2377 .chain(
2378 tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
2379 )
2380 .map(|(trait_ref, _)| {
2381 trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
2382 }),
2383 );
2384 }
2385
2386 let hybrid_preds = hybrid_preds.into_iter().map(Unnormalized::skip_norm_wip);
2387 let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
2388 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
2389 debug!(caller_bounds=?param_env.caller_bounds());
2390
2391 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2392 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2393
2394 for (predicate, span) in impl_ty_own_bounds {
2395 let cause = ObligationCause::misc(span, impl_ty_def_id);
2396 let predicate = ocx.normalize(&cause, param_env, predicate);
2397
2398 let cause = ObligationCause::new(
2399 span,
2400 impl_ty_def_id,
2401 ObligationCauseCode::CompareImplItem {
2402 impl_item_def_id: impl_ty.def_id.expect_local(),
2403 trait_item_def_id: trait_ty.def_id,
2404 kind: impl_ty.kind,
2405 },
2406 );
2407 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2408 }
2409
2410 if is_conditionally_const {
2411 let impl_ty_own_const_conditions =
2413 tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2414 for (const_condition, span) in impl_ty_own_const_conditions {
2415 let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2416 let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2417
2418 let cause = ObligationCause::new(
2419 span,
2420 impl_ty_def_id,
2421 ObligationCauseCode::CompareImplItem {
2422 impl_item_def_id: impl_ty_def_id,
2423 trait_item_def_id: trait_ty.def_id,
2424 kind: impl_ty.kind,
2425 },
2426 );
2427 ocx.register_obligation(traits::Obligation::new(
2428 tcx,
2429 cause,
2430 param_env,
2431 const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2432 ));
2433 }
2434 }
2435
2436 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2439 if !errors.is_empty() {
2440 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2441 return Err(reported);
2442 }
2443
2444 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2447}
2448
2449#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_type_bounds",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2462u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ty")
}> =
::tracing::__macro_support::FieldName::new("trait_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_ty")
}> =
::tracing::__macro_support::FieldName::new("impl_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("impl_trait_ref");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
tcx.ensure_result().coherent_trait(impl_trait_ref.def_id)?;
let param_env = tcx.param_env(impl_ty.def_id);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2474",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2474u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param_env")
}> =
::tracing::__macro_support::FieldName::new("param_env");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_env)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let container_id = impl_ty.container_id(tcx);
let impl_ty_def_id = impl_ty.def_id.expect_local();
let impl_ty_args =
GenericArgs::identity_for_item(tcx, impl_ty.def_id);
let rebased_args =
impl_ty_args.rebase_onto(tcx, container_id,
impl_trait_ref.args);
let infcx =
tcx.infer_ctxt().build(TypingMode::non_body_analysis());
let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
let impl_ty_span =
if impl_ty.is_impl_trait_in_trait() {
tcx.def_span(impl_ty_def_id)
} else {
match tcx.hir_node_by_def_id(impl_ty_def_id) {
hir::Node::TraitItem(hir::TraitItem {
kind: hir::TraitItemKind::Type(_, Some(ty)), .. }) =>
ty.span,
hir::Node::ImplItem(hir::ImplItem {
kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
item =>
::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(impl_ty_def_id),
format_args!("cannot call `check_type_bounds` on item: {0:?}",
item)),
}
};
let assumed_wf_types =
ocx.assumed_wf_types_and_report_errors(param_env,
impl_ty_def_id)?;
let normalize_cause =
ObligationCause::new(impl_ty_span, impl_ty_def_id,
ObligationCauseCode::CheckAssociatedTypeBounds {
impl_item_def_id: impl_ty.def_id.expect_local(),
trait_item_def_id: trait_ty.def_id,
});
let mk_cause =
|span: Span|
{
let code =
ObligationCauseCode::WhereClause(trait_ty.def_id, span);
ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
};
let mut obligations: Vec<_> =
util::elaborate(tcx,
tcx.explicit_item_bounds(trait_ty.def_id).iter_instantiated_copied(tcx,
rebased_args).map(Unnormalized::skip_norm_wip).map(|(concrete_ty_bound,
span)|
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2523",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2523u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("concrete_ty_bound")
}> =
::tracing::__macro_support::FieldName::new("concrete_ty_bound");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&concrete_ty_bound)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
traits::Obligation::new(tcx, mk_cause(span), param_env,
concrete_ty_bound)
})).collect();
if tcx.is_conditionally_const(impl_ty_def_id) {
obligations.extend(util::elaborate(tcx,
tcx.explicit_implied_const_bounds(trait_ty.def_id).iter_instantiated_copied(tcx,
rebased_args).map(Unnormalized::skip_norm_wip).map(|(c,
span)|
{
traits::Obligation::new(tcx, mk_cause(span), param_env,
c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe))
})));
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2546",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2546u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item_bounds")
}> =
::tracing::__macro_support::FieldName::new("item_bounds");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligations)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let normalize_param_env =
param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
for obligation in &mut obligations {
match ocx.deeply_normalize(&normalize_cause,
normalize_param_env,
Unnormalized::new_wip(obligation.predicate)) {
Ok(pred) => obligation.predicate = pred,
Err(e) => {
return Err(infcx.err_ctxt().report_fulfillment_errors(e));
}
}
}
ocx.register_obligations(obligations);
let errors = ocx.evaluate_obligations_error_on_ambiguity();
if !errors.is_empty() {
let reported =
infcx.err_ctxt().report_fulfillment_errors(errors);
return Err(reported);
}
ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env,
assumed_wf_types)
}
}
}#[instrument(level = "debug", skip(tcx))]
2463pub(super) fn check_type_bounds<'tcx>(
2464 tcx: TyCtxt<'tcx>,
2465 trait_ty: ty::AssocItem,
2466 impl_ty: ty::AssocItem,
2467 impl_trait_ref: ty::TraitRef<'tcx>,
2468) -> Result<(), ErrorGuaranteed> {
2469 tcx.ensure_result().coherent_trait(impl_trait_ref.def_id)?;
2472
2473 let param_env = tcx.param_env(impl_ty.def_id);
2474 debug!(?param_env);
2475
2476 let container_id = impl_ty.container_id(tcx);
2477 let impl_ty_def_id = impl_ty.def_id.expect_local();
2478 let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2479 let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2480
2481 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2482 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2483
2484 let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2488 tcx.def_span(impl_ty_def_id)
2489 } else {
2490 match tcx.hir_node_by_def_id(impl_ty_def_id) {
2491 hir::Node::TraitItem(hir::TraitItem {
2492 kind: hir::TraitItemKind::Type(_, Some(ty)),
2493 ..
2494 }) => ty.span,
2495 hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2496 item => span_bug!(
2497 tcx.def_span(impl_ty_def_id),
2498 "cannot call `check_type_bounds` on item: {item:?}",
2499 ),
2500 }
2501 };
2502 let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2503
2504 let normalize_cause = ObligationCause::new(
2505 impl_ty_span,
2506 impl_ty_def_id,
2507 ObligationCauseCode::CheckAssociatedTypeBounds {
2508 impl_item_def_id: impl_ty.def_id.expect_local(),
2509 trait_item_def_id: trait_ty.def_id,
2510 },
2511 );
2512 let mk_cause = |span: Span| {
2513 let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2514 ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2515 };
2516
2517 let mut obligations: Vec<_> = util::elaborate(
2518 tcx,
2519 tcx.explicit_item_bounds(trait_ty.def_id)
2520 .iter_instantiated_copied(tcx, rebased_args)
2521 .map(Unnormalized::skip_norm_wip)
2522 .map(|(concrete_ty_bound, span)| {
2523 debug!(?concrete_ty_bound);
2524 traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2525 }),
2526 )
2527 .collect();
2528
2529 if tcx.is_conditionally_const(impl_ty_def_id) {
2531 obligations.extend(util::elaborate(
2532 tcx,
2533 tcx.explicit_implied_const_bounds(trait_ty.def_id)
2534 .iter_instantiated_copied(tcx, rebased_args)
2535 .map(Unnormalized::skip_norm_wip)
2536 .map(|(c, span)| {
2537 traits::Obligation::new(
2538 tcx,
2539 mk_cause(span),
2540 param_env,
2541 c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2542 )
2543 }),
2544 ));
2545 }
2546 debug!(item_bounds=?obligations);
2547
2548 let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2553 for obligation in &mut obligations {
2554 match ocx.deeply_normalize(
2555 &normalize_cause,
2556 normalize_param_env,
2557 Unnormalized::new_wip(obligation.predicate),
2558 ) {
2559 Ok(pred) => obligation.predicate = pred,
2560 Err(e) => {
2561 return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2562 }
2563 }
2564 }
2565
2566 ocx.register_obligations(obligations);
2569 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2570 if !errors.is_empty() {
2571 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2572 return Err(reported);
2573 }
2574
2575 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2578}
2579
2580fn param_env_with_gat_bounds<'tcx>(
2628 tcx: TyCtxt<'tcx>,
2629 impl_ty: ty::AssocItem,
2630 impl_trait_ref: ty::TraitRef<'tcx>,
2631) -> ty::ParamEnv<'tcx> {
2632 let param_env = tcx.param_env(impl_ty.def_id);
2633 let container_id = impl_ty.container_id(tcx);
2634 let mut clauses = param_env.caller_bounds().to_vec();
2635
2636 let impl_tys_to_install = match impl_ty.kind {
2641 ty::AssocKind::Type {
2642 data:
2643 ty::AssocTypeData::Rpitit(
2644 ty::ImplTraitInTraitData::Impl { fn_def_id }
2645 | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2646 ),
2647 } => tcx
2648 .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2649 .iter()
2650 .map(|def_id| tcx.associated_item(*def_id))
2651 .collect(),
2652 _ => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[impl_ty]))vec![impl_ty],
2653 };
2654
2655 for impl_ty in impl_tys_to_install {
2656 let trait_ty = match impl_ty.container {
2657 ty::AssocContainer::InherentImpl => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
2658 ty::AssocContainer::Trait => impl_ty,
2659 ty::AssocContainer::TraitImpl(Err(_)) => continue,
2660 ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
2661 tcx.associated_item(trait_item_def_id)
2662 }
2663 };
2664
2665 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind<'tcx>; 8]> =
2666 smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2667 let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2669 .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2670 GenericParamDefKind::Type { .. } => {
2671 let kind = ty::BoundTyKind::Param(param.def_id);
2672 let bound_var = ty::BoundVariableKind::Ty(kind);
2673 bound_vars.push(bound_var);
2674 Ty::new_bound(
2675 tcx,
2676 ty::INNERMOST,
2677 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2678 )
2679 .into()
2680 }
2681 GenericParamDefKind::Lifetime => {
2682 let kind = ty::BoundRegionKind::Named(param.def_id);
2683 let bound_var = ty::BoundVariableKind::Region(kind);
2684 bound_vars.push(bound_var);
2685 ty::Region::new_bound(
2686 tcx,
2687 ty::INNERMOST,
2688 ty::BoundRegion {
2689 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2690 kind,
2691 },
2692 )
2693 .into()
2694 }
2695 GenericParamDefKind::Const { .. } => {
2696 let bound_var = ty::BoundVariableKind::Const;
2697 bound_vars.push(bound_var);
2698 ty::Const::new_bound(
2699 tcx,
2700 ty::INNERMOST,
2701 ty::BoundConst::new(ty::BoundVar::from_usize(bound_vars.len() - 1)),
2702 )
2703 .into()
2704 }
2705 });
2706 let normalize_impl_ty =
2716 tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args).skip_norm_wip();
2717 let rebased_args =
2718 normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2719 let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2720
2721 match normalize_impl_ty.kind() {
2722 &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
2723 if def_id == trait_ty.def_id && args == rebased_args =>
2724 {
2725 }
2731 _ => clauses.push(
2732 ty::Binder::bind_with_vars(
2733 ty::ProjectionPredicate {
2734 projection_term: ty::AliasTerm::new_from_def_id(
2735 tcx,
2736 trait_ty.def_id,
2737 rebased_args,
2738 ),
2739 term: normalize_impl_ty.into(),
2740 },
2741 bound_vars,
2742 )
2743 .upcast(tcx),
2744 ),
2745 };
2746 }
2747
2748 ty::ParamEnv::new(tcx.mk_clauses(&clauses))
2749}
2750
2751fn try_report_async_mismatch<'tcx>(
2754 tcx: TyCtxt<'tcx>,
2755 infcx: &InferCtxt<'tcx>,
2756 errors: &[FulfillmentError<'tcx>],
2757 trait_m: ty::AssocItem,
2758 impl_m: ty::AssocItem,
2759 impl_sig: ty::FnSig<'tcx>,
2760) -> Result<(), ErrorGuaranteed> {
2761 if !tcx.asyncness(trait_m.def_id).is_async() {
2762 return Ok(());
2763 }
2764
2765 let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id: async_future_def_id }, .. }) =
2766 *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2767 else {
2768 ::rustc_middle::util::bug::bug_fmt(format_args!("expected `async fn` to return an RPITIT"));bug!("expected `async fn` to return an RPITIT");
2769 };
2770
2771 for error in errors {
2772 if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2773 && def_id == async_future_def_id
2774 && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2775 && let Some(proj) = proj.no_bound_vars()
2776 && infcx.can_eq(
2777 error.root_obligation.param_env,
2778 proj.term.expect_type(),
2779 impl_sig.output(),
2780 )
2781 {
2782 return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2785 span: tcx.def_span(impl_m.def_id),
2786 method_name: tcx.item_ident(impl_m.def_id),
2787 trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
2788 }));
2789 }
2790 }
2791
2792 Ok(())
2793}