use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use core::ops::ControlFlow;
use alloc::borrow::Cow;
use core::cmp::Ordering;
use core::iter;
use hir::def_id::{DefId, DefIdMap, LocalDefId};
use crate::rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
use crate::rustc_errors::codes::*;
use crate::rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan, pluralize, struct_span_code_err};
use crate::rustc_hir::def::{DefKind, Res};
use crate::rustc_hir::intravisit::VisitorExt;
use crate::rustc_hir::{self as hir, AmbigArg, GenericParamKind, ImplItemKind, intravisit};
use crate::rustc_infer::infer::{self, BoundRegionConversionTime, InferCtxt, TyCtxtInferExt};
use crate::rustc_infer::traits::{TraitErrors, util};
use crate::rustc_middle::ty::error::{ExpectedFound, TypeError};
use crate::rustc_middle::ty::{
self, BottomUpFolder, GenericArgs, GenericParamDefKind, Generics, RegionExt, Ty, TyCtxt,
TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypeVisitor,
TypingMode, Unnormalized, Upcast,
};
use crate::rustc_middle::{bug, span_bug};
use crate::rustc_span::{BytePos, DUMMY_SP, Span};
use crate::rustc_trait_selection::error_reporting::InferCtxtErrorExt;
use crate::rustc_trait_selection::infer::InferCtxtExt;
use crate::rustc_trait_selection::regions::InferCtxtRegionExt;
use crate::rustc_trait_selection::solve::NextSolverError;
use crate::rustc_trait_selection::traits::{
self, FromSolverError, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
};
use tracing::{debug, instrument};
use super::potentially_plural_count;
use crate::rustc_hir_analysis::diagnostics::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture};
pub(super) mod refine;
pub(super) fn compare_impl_item(
tcx: TyCtxt<'_>,
impl_item_def_id: LocalDefId,
) -> Result<(), ErrorGuaranteed> {
let impl_item = tcx.associated_item(impl_item_def_id);
let trait_item = tcx.associated_item(impl_item.expect_trait_impl()?);
let impl_trait_ref =
tcx.impl_trait_ref(impl_item.container_id(tcx)).instantiate_identity().skip_norm_wip();
debug!(?impl_trait_ref);
match impl_item.kind {
ty::AssocKind::Fn { .. } => compare_impl_method(tcx, impl_item, trait_item, impl_trait_ref),
ty::AssocKind::Type { .. } => compare_impl_ty(tcx, impl_item, trait_item, impl_trait_ref),
ty::AssocKind::Const { .. } => {
compare_impl_const(tcx, impl_item, trait_item, impl_trait_ref)
}
}
}
#[instrument(level = "debug", skip(tcx))]
fn compare_impl_method<'tcx>(
tcx: TyCtxt<'tcx>,
impl_m: ty::AssocItem,
trait_m: ty::AssocItem,
impl_trait_ref: ty::TraitRef<'tcx>,
) -> Result<(), ErrorGuaranteed> {
check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, false)?;
compare_method_clause_entailment(tcx, impl_m, trait_m, impl_trait_ref)?;
Ok(())
}
fn check_method_is_structurally_compatible<'tcx>(
tcx: TyCtxt<'tcx>,
impl_m: ty::AssocItem,
trait_m: ty::AssocItem,
impl_trait_ref: ty::TraitRef<'tcx>,
delay: bool,
) -> Result<(), ErrorGuaranteed> {
compare_self_type(tcx, impl_m, trait_m, impl_trait_ref, delay)?;
compare_number_of_generics(tcx, impl_m, trait_m, delay)?;
compare_generic_param_kinds(tcx, impl_m, trait_m, delay)?;
compare_number_of_method_arguments(tcx, impl_m, trait_m, delay)?;
compare_synthetic_generics(tcx, impl_m, trait_m, delay)?;
check_region_bounds_on_impl_item(tcx, impl_m, trait_m, delay)?;
Ok(())
}
#[instrument(level = "debug", skip(tcx, impl_trait_ref))]
fn compare_method_clause_entailment<'tcx>(
tcx: TyCtxt<'tcx>,
impl_m: ty::AssocItem,
trait_m: ty::AssocItem,
impl_trait_ref: ty::TraitRef<'tcx>,
) -> Result<(), ErrorGuaranteed> {
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,
);
debug!(?trait_to_impl_args);
let impl_m_clauses = tcx.clauses_of(impl_m.def_id);
let trait_m_clauses = tcx.clauses_of(trait_m.def_id);
let impl_clauses = tcx.clauses_of(impl_m_clauses.parent.unwrap());
let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
hybrid_clauses
.extend(trait_m_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(clause, _)| clause));
let is_conditionally_const = tcx.is_conditionally_const(impl_m.def_id);
if is_conditionally_const {
hybrid_clauses.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_clauses = hybrid_clauses.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, hybrid_clauses);
let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
debug!(?param_env);
let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
let ocx = ObligationCtxt::new_with_diagnostics(infcx);
let impl_m_own_bounds = impl_m_clauses.instantiate_own_identity();
for (clause, span) in impl_m_own_bounds {
let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
let clause = ocx.normalize(&normalize_cause, param_env, clause);
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, clause));
}
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));
debug!(?impl_sig);
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());
debug!(?trait_sig);
let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
if let Err(terr) = result {
debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
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 let TraitErrors::HasErrors(errors) = errors {
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(())
}
struct RemapLateParam<'tcx> {
tcx: TyCtxt<'tcx>,
mapping: FxIndexMap<ty::LateParamRegionKind, ty::LateParamRegionKind>,
}
impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateParam<'tcx> {
fn cx(&self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
if let ty::ReLateParam(fr) = r.kind() {
ty::Region::new_late_param(
self.tcx,
fr.scope,
self.mapping.get(&fr.kind).copied().unwrap_or(fr.kind),
)
} else {
r
}
}
}
#[instrument(skip(tcx), level = "debug", ret)]
pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
tcx: TyCtxt<'tcx>,
impl_m_def_id: LocalDefId,
) -> Result<&'tcx DefIdMap<ty::EarlyBinder<'tcx, Ty<'tcx>>>, ErrorGuaranteed> {
let impl_m = tcx.associated_item(impl_m_def_id.to_def_id());
let trait_m = tcx.associated_item(impl_m.expect_trait_impl()?);
let impl_trait_ref = tcx
.impl_trait_ref(tcx.parent(impl_m_def_id.to_def_id()))
.instantiate_identity()
.skip_norm_wip();
check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?;
let impl_m_hir_id = tcx.local_def_id_to_hir_id(impl_m_def_id);
let return_span = tcx.hir_fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
let cause = ObligationCause::new(
return_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 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,
);
let hybrid_clauses = tcx
.clauses_of(impl_m.container_id(tcx))
.instantiate_identity(tcx)
.into_iter()
.chain(tcx.clauses_of(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args))
.map(|(clause, _)| clause.skip_norm_wip());
let param_env = ty::ParamEnv::new(tcx, hybrid_clauses);
let param_env = traits::normalize_param_env_or_error(
tcx,
param_env,
ObligationCause::misc(tcx.def_span(impl_m_def_id), impl_m_def_id),
);
let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
let ocx = ObligationCtxt::new_with_diagnostics(infcx);
let impl_m_own_bounds = tcx.clauses_of(impl_m_def_id).instantiate_own_identity();
for (clause, span) in impl_m_own_bounds {
let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
let clause = ocx.normalize(&normalize_cause, param_env, clause);
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, clause));
}
let misc_cause = ObligationCause::misc(return_span, impl_m_def_id);
let impl_sig = ocx.normalize(
&misc_cause,
param_env,
Unnormalized::new_wip(infcx.instantiate_binder_with_fresh_vars(
return_span,
BoundRegionConversionTime::HigherRankedType,
tcx.fn_sig(impl_m.def_id).instantiate_identity().skip_norm_wip(),
)),
);
impl_sig.error_reported()?;
let impl_return_ty = impl_sig.output();
let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_def_id);
let unnormalized_trait_sig = tcx
.liberate_late_bound_regions(
impl_m.def_id,
tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args).skip_norm_wip(),
)
.fold_with(&mut collector);
let trait_sig =
ocx.normalize(&misc_cause, param_env, Unnormalized::new_wip(unnormalized_trait_sig));
trait_sig.error_reported()?;
let trait_return_ty = trait_sig.output();
let universe = infcx.create_next_universe();
let mut idx = ty::BoundVar::ZERO;
let mapping: FxIndexMap<_, _> = collector
.types
.iter()
.map(|(_, &(ty, _))| {
assert!(
infcx.resolve_vars_if_possible(ty) == ty && ty.is_ty_var(),
"{ty:?} should not have been constrained via normalization",
ty = infcx.resolve_vars_if_possible(ty)
);
idx += 1;
(
ty,
Ty::new_placeholder(
tcx,
ty::PlaceholderType::new(
universe,
ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
),
),
)
})
.collect();
let mut type_mapper = BottomUpFolder {
tcx,
ty_op: |ty| *mapping.get(&ty).unwrap_or(&ty),
lt_op: |lt| lt,
ct_op: |ct| ct,
};
let wf_tys = FxIndexSet::from_iter(
unnormalized_trait_sig
.inputs_and_output
.iter()
.chain(trait_sig.inputs_and_output.iter())
.map(|ty| ty.fold_with(&mut type_mapper)),
);
match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
Ok(()) => {}
Err(terr) => {
let mut diag = struct_span_code_err!(
tcx.dcx(),
cause.span,
E0053,
"method `{}` has an incompatible return type for trait",
trait_m.name()
);
infcx.err_ctxt().note_type_err(
&mut diag,
&cause,
tcx.hir_get_if_local(impl_m.def_id)
.and_then(|node| node.fn_decl())
.map(|decl| (decl.output.span(), Cow::from("return type in trait"), false)),
Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
expected: trait_return_ty.into(),
found: impl_return_ty.into(),
}))),
terr,
false,
None,
);
return Err(diag.emit());
}
}
debug!(?trait_sig, ?impl_sig, "equating function signatures");
match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
Ok(()) => {}
Err(terr) => {
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 !unnormalized_trait_sig.output().references_error() && collector.types.is_empty() {
tcx.dcx().delayed_bug(
"expect >0 RPITITs in call to `collect_return_position_impl_trait_in_trait_tys`",
);
}
let collected_types = collector.types;
for (_, &(ty, _)) in &collected_types {
ocx.register_obligation(traits::Obligation::new(
tcx,
misc_cause.clone(),
param_env,
ty::ClauseKind::WellFormed(ty.into()),
));
}
let errors = ocx.evaluate_obligations_error_on_ambiguity();
if let TraitErrors::HasErrors(errors) = errors {
if let Err(guar) = try_report_async_mismatch(tcx, infcx, &errors, trait_m, impl_m, impl_sig)
{
return Err(guar);
}
let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
return Err(guar);
}
ocx.resolve_regions_and_report_errors(impl_m_def_id, param_env, wf_tys)?;
let mut remapped_types = DefIdMap::default();
for (def_id, (ty, args)) in collected_types {
match infcx.fully_resolve(ty) {
Ok(ty) => {
let id_args = GenericArgs::identity_for_item(tcx, def_id);
debug!(?id_args, ?args);
let map: FxIndexMap<_, _> = core::iter::zip(args, id_args)
.skip(tcx.generics_of(trait_m.def_id).count())
.filter_map(|(a, b)| Some((a.as_region()?, b.as_region()?)))
.collect();
debug!(?map);
let num_trait_args = impl_trait_ref.args.len();
let num_impl_args = tcx.generics_of(impl_m.container_id(tcx)).own_params.len();
let ty = match ty.try_fold_with(&mut RemapHiddenTyRegions {
tcx,
map,
num_trait_args,
num_impl_args,
def_id,
impl_m_def_id: impl_m.def_id,
ty,
return_span,
}) {
Ok(ty) => ty,
Err(guar) => Ty::new_error(tcx, guar),
};
remapped_types.insert(def_id, ty::EarlyBinder::bind(tcx, ty));
}
Err(err) => {
tcx.dcx()
.span_bug(return_span, format!("could not fully resolve: {ty} => {err:?}"));
}
}
}
for assoc_item in tcx.associated_types_for_impl_traits_in_associated_fn(trait_m.def_id) {
if !remapped_types.contains_key(assoc_item) {
remapped_types.insert(
*assoc_item,
ty::EarlyBinder::bind(
tcx,
Ty::new_error_with_message(
tcx,
return_span,
"missing synthetic item for RPITIT",
),
),
);
}
}
Ok(&*tcx.arena.alloc(remapped_types))
}
struct ImplTraitInTraitCollector<'a, 'tcx, E> {
ocx: &'a ObligationCtxt<'a, 'tcx, E>,
types: FxIndexMap<DefId, (Ty<'tcx>, ty::GenericArgsRef<'tcx>)>,
span: Span,
param_env: ty::ParamEnv<'tcx>,
impl_m_id: LocalDefId,
}
impl<'a, 'tcx, E> ImplTraitInTraitCollector<'a, 'tcx, E>
where
E: FromSolverError<'tcx, NextSolverError<'tcx>>
+ FromSolverError<'tcx, traits::OldSolverError<'tcx>>,
{
fn new(
ocx: &'a ObligationCtxt<'a, 'tcx, E>,
span: Span,
param_env: ty::ParamEnv<'tcx>,
impl_m_id: LocalDefId,
) -> Self {
ImplTraitInTraitCollector { ocx, types: FxIndexMap::default(), span, param_env, impl_m_id }
}
}
impl<'tcx, E> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx, E>
where
E: FromSolverError<'tcx, NextSolverError<'tcx>>
+ FromSolverError<'tcx, traits::OldSolverError<'tcx>>,
{
fn cx(&self) -> TyCtxt<'tcx> {
self.ocx.infcx.tcx
}
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
if let &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args: proj_args, .. }) =
ty.kind()
&& self.cx().is_impl_trait_in_trait(def_id)
{
if let Some((ty, _)) = self.types.get(&def_id) {
return *ty;
}
if proj_args.has_escaping_bound_vars() {
bug!("FIXME(RPITIT): error here");
}
let infer_ty = self.ocx.infcx.next_ty_var(self.span);
self.types.insert(def_id, (infer_ty, proj_args));
for (pred, pred_span) in self
.cx()
.explicit_item_bounds(def_id)
.iter_instantiated_copied(self.cx(), proj_args)
.map(Unnormalized::skip_norm_wip)
{
let pred = pred.fold_with(self);
let pred = self.ocx.normalize(
&ObligationCause::misc(self.span, self.impl_m_id),
self.param_env,
Unnormalized::new_wip(pred),
);
self.ocx.register_obligation(traits::Obligation::new(
self.cx(),
ObligationCause::new(
self.span,
self.impl_m_id,
ObligationCauseCode::WhereClause(def_id, pred_span),
),
self.param_env,
pred,
));
}
infer_ty
} else {
ty.super_fold_with(self)
}
}
}
struct RemapHiddenTyRegions<'tcx> {
tcx: TyCtxt<'tcx>,
map: FxIndexMap<ty::Region<'tcx>, ty::Region<'tcx>>,
num_trait_args: usize,
num_impl_args: usize,
def_id: DefId,
impl_m_def_id: DefId,
ty: Ty<'tcx>,
return_span: Span,
}
impl<'tcx> ty::FallibleTypeFolder<TyCtxt<'tcx>> for RemapHiddenTyRegions<'tcx> {
type Error = ErrorGuaranteed;
fn cx(&self) -> TyCtxt<'tcx> {
self.tcx
}
fn try_fold_region(
&mut self,
region: ty::Region<'tcx>,
) -> Result<ty::Region<'tcx>, Self::Error> {
match region.kind() {
ty::ReBound(..) | ty::ReStatic | ty::ReError(_) => return Ok(region),
ty::ReLateParam(_) => {}
ty::ReEarlyParam(ebr) => {
if ebr.index as usize >= self.num_impl_args {
} else {
return Ok(region);
}
}
ty::ReVar(_) | ty::RePlaceholder(_) | ty::ReErased => unreachable!(
"should not have leaked vars or placeholders into hidden type of RPITIT"
),
}
let e = if let Some(id_region) = self.map.get(®ion) {
if let ty::ReEarlyParam(e) = id_region.kind() {
e
} else {
bug!(
"expected to map region {region} to early-bound identity region, but got {id_region}"
);
}
} else {
let guar = match region.opt_param_def_id(self.tcx, self.impl_m_def_id) {
Some(def_id) => {
let return_span = if let &ty::Alias(
_,
ty::AliasTy { kind: ty::Opaque { def_id: opaque_ty_def_id }, .. },
) = self.ty.kind()
{
self.tcx.def_span(opaque_ty_def_id)
} else {
self.return_span
};
self.tcx
.dcx()
.struct_span_err(
return_span,
"return type captures more lifetimes than trait definition",
)
.with_span_label(self.tcx.def_span(def_id), "this lifetime was captured")
.with_span_note(
self.tcx.def_span(self.def_id),
"hidden type must only reference lifetimes captured by this impl trait",
)
.with_note(format!("hidden type inferred to be `{}`", self.ty))
.emit()
}
None => {
self.tcx.dcx().bug("should've been able to remap region");
}
};
return Err(guar);
};
Ok(ty::Region::new_early_param(
self.tcx,
ty::EarlyParamRegion {
name: e.name,
index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32,
},
))
}
}
fn get_self_string<'tcx, P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> String
where
P: Fn(Ty<'tcx>) -> bool,
{
if is_self_ty(self_arg_ty) {
"self".to_owned()
} else if let ty::Ref(_, ty, mutbl) = self_arg_ty.kind()
&& is_self_ty(*ty)
{
match mutbl {
hir::Mutability::Not => "&self".to_owned(),
hir::Mutability::Mut => "&mut self".to_owned(),
}
} else {
format!("self: {self_arg_ty}")
}
}
fn report_trait_method_mismatch<'tcx>(
infcx: &InferCtxt<'tcx>,
mut cause: ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
terr: TypeError<'tcx>,
(trait_m, trait_sig): (ty::AssocItem, ty::FnSig<'tcx>),
(impl_m, impl_sig): (ty::AssocItem, ty::FnSig<'tcx>),
impl_trait_ref: ty::TraitRef<'tcx>,
) -> ErrorGuaranteed {
let tcx = infcx.tcx;
let (impl_err_span, trait_err_span) =
extract_spans_for_error_reporting(infcx, terr, &cause, impl_m, trait_m);
let mut diag = struct_span_code_err!(
tcx.dcx(),
impl_err_span,
E0053,
"method `{}` has an incompatible type for trait",
trait_m.name()
);
match &terr {
TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
if trait_m.is_method() =>
{
let ty = trait_sig.inputs()[0];
let sugg = get_self_string(ty, |ty| ty == impl_trait_ref.self_ty());
let (sig, body) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
let span = tcx
.hir_body_param_idents(body)
.zip(sig.decl.inputs.iter())
.map(|(param_ident, ty)| {
if let Some(param_ident) = param_ident {
param_ident.span.to(ty.span)
} else {
ty.span
}
})
.next()
.unwrap_or(impl_err_span);
diag.span_suggestion_verbose(
span,
"change the self-receiver type to match the trait",
sugg,
Applicability::MachineApplicable,
);
}
TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
if trait_sig.inputs().len() == *i {
if let ImplItemKind::Fn(sig, _) =
&tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).kind
&& !sig.header.asyncness.is_async()
{
let msg = "change the output type to match the trait";
let ap = Applicability::MachineApplicable;
match sig.decl.output {
hir::FnRetTy::DefaultReturn(sp) => {
let sugg = format!(" -> {}", trait_sig.output());
diag.span_suggestion_verbose(sp, msg, sugg, ap);
}
hir::FnRetTy::Return(hir_ty) => {
let sugg = trait_sig.output();
diag.span_suggestion_verbose(hir_ty.span, msg, sugg, ap);
}
};
};
} else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
diag.span_suggestion_verbose(
impl_err_span,
"change the parameter type to match the trait",
trait_ty,
Applicability::MachineApplicable,
);
}
}
_ => {}
}
cause.span = impl_err_span;
infcx.err_ctxt().note_type_err(
&mut diag,
&cause,
trait_err_span.map(|sp| (sp, Cow::from("type in trait"), false)),
Some(param_env.and(infer::ValuePairs::PolySigs(ExpectedFound {
expected: ty::Binder::dummy(trait_sig),
found: ty::Binder::dummy(impl_sig),
}))),
terr,
false,
None,
);
diag.emit()
}
fn check_region_bounds_on_impl_item<'tcx>(
tcx: TyCtxt<'tcx>,
impl_m: ty::AssocItem,
trait_m: ty::AssocItem,
delay: bool,
) -> Result<(), ErrorGuaranteed> {
let impl_generics = tcx.generics_of(impl_m.def_id);
let impl_params = impl_generics.own_counts().lifetimes;
let trait_generics = tcx.generics_of(trait_m.def_id);
let trait_params = trait_generics.own_counts().lifetimes;
let Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span }) =
check_number_of_early_bound_regions(
tcx,
impl_m.def_id.expect_local(),
trait_m.def_id,
impl_generics,
impl_params,
trait_generics,
trait_params,
)
else {
return Ok(());
};
if !delay && let Some(guar) = check_region_late_boundedness(tcx, impl_m, trait_m) {
return Err(guar);
}
let reported = tcx
.dcx()
.create_err(LifetimesOrBoundsMismatchOnTrait {
span,
item_kind: impl_m.descr(),
ident: impl_m.ident(tcx),
generics_span,
bounds_span,
where_span,
})
.emit_unless_delay(delay);
Err(reported)
}
pub(super) struct CheckNumberOfEarlyBoundRegionsError {
pub(super) span: Span,
pub(super) generics_span: Span,
pub(super) bounds_span: Vec<Span>,
pub(super) where_span: Option<Span>,
}
pub(super) fn check_number_of_early_bound_regions<'tcx>(
tcx: TyCtxt<'tcx>,
impl_def_id: LocalDefId,
trait_def_id: DefId,
impl_generics: &Generics,
impl_params: usize,
trait_generics: &Generics,
trait_params: usize,
) -> Result<(), CheckNumberOfEarlyBoundRegionsError> {
debug!(?trait_generics, ?impl_generics);
if trait_params == impl_params {
return Ok(());
}
let span = tcx
.hir_get_generics(impl_def_id)
.expect("expected impl item to have generics or else we can't compare them")
.span;
let mut generics_span = tcx.def_span(trait_def_id);
let mut bounds_span = vec![];
let mut where_span = None;
if let Some(trait_node) = tcx.hir_get_if_local(trait_def_id)
&& let Some(trait_generics) = trait_node.generics()
{
generics_span = trait_generics.span;
for p in trait_generics.predicates {
match p.kind {
hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
bounds,
..
})
| hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
bounds,
..
}) => {
for b in *bounds {
if let hir::GenericBound::Outlives(lt) = b {
bounds_span.push(lt.ident.span);
}
}
}
}
}
if let Some(impl_node) = tcx.hir_get_if_local(impl_def_id.into())
&& let Some(impl_generics) = impl_node.generics()
{
let mut impl_bounds = 0;
for p in impl_generics.predicates {
match p.kind {
hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
bounds,
..
})
| hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
bounds,
..
}) => {
for b in *bounds {
if let hir::GenericBound::Outlives(_) = b {
impl_bounds += 1;
}
}
}
}
}
if impl_bounds == bounds_span.len() {
bounds_span = vec![];
} else if impl_generics.has_where_clause_predicates {
where_span = Some(impl_generics.where_clause_span);
}
}
}
Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span })
}
#[allow(unused)]
enum LateEarlyMismatch<'tcx> {
EarlyInImpl(DefId, DefId, ty::Region<'tcx>),
LateInImpl(DefId, DefId, ty::Region<'tcx>),
}
fn check_region_late_boundedness<'tcx>(
tcx: TyCtxt<'tcx>,
impl_m: ty::AssocItem,
trait_m: ty::AssocItem,
) -> Option<ErrorGuaranteed> {
if !impl_m.is_fn() {
return None;
}
let (infcx, param_env) = tcx
.infer_ctxt()
.build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, impl_m.def_id));
let impl_m_args = infcx.fresh_args_for_item(DUMMY_SP, impl_m.def_id);
let impl_m_sig = tcx.fn_sig(impl_m.def_id).instantiate(tcx, impl_m_args).skip_norm_wip();
let impl_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, impl_m_sig);
let trait_m_args = infcx.fresh_args_for_item(DUMMY_SP, trait_m.def_id);
let trait_m_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_args).skip_norm_wip();
let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_m_sig);
let ocx = ObligationCtxt::new(&infcx);
let Ok(()) = ocx.eq(
&ObligationCause::dummy(),
param_env,
ty::Binder::dummy(trait_m_sig),
ty::Binder::dummy(impl_m_sig),
) else {
return None;
};
let errors = ocx.try_evaluate_obligations();
if !errors.no_errors() {
return None;
}
let mut mismatched = vec![];
let impl_generics = tcx.generics_of(impl_m.def_id);
for (id_arg, arg) in
core::iter::zip(ty::GenericArgs::identity_for_item(tcx, impl_m.def_id), impl_m_args)
{
if let ty::GenericArgKind::Lifetime(r) = arg.kind()
&& let ty::ReVar(vid) = r.kind()
&& let r = infcx
.inner
.borrow_mut()
.unwrap_region_constraints()
.opportunistic_resolve_var(tcx, vid)
&& let ty::ReLateParam(ty::LateParamRegion {
kind: ty::LateParamRegionKind::Named(trait_param_def_id),
..
}) = r.kind()
&& let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
{
mismatched.push(LateEarlyMismatch::EarlyInImpl(
impl_generics.region_param(ebr, tcx).def_id,
trait_param_def_id,
id_arg.expect_region(),
));
}
}
let trait_generics = tcx.generics_of(trait_m.def_id);
for (id_arg, arg) in
core::iter::zip(ty::GenericArgs::identity_for_item(tcx, trait_m.def_id), trait_m_args)
{
if let ty::GenericArgKind::Lifetime(r) = arg.kind()
&& let ty::ReVar(vid) = r.kind()
&& let r = infcx
.inner
.borrow_mut()
.unwrap_region_constraints()
.opportunistic_resolve_var(tcx, vid)
&& let ty::ReLateParam(ty::LateParamRegion {
kind: ty::LateParamRegionKind::Named(impl_param_def_id),
..
}) = r.kind()
&& let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
{
mismatched.push(LateEarlyMismatch::LateInImpl(
impl_param_def_id,
trait_generics.region_param(ebr, tcx).def_id,
id_arg.expect_region(),
));
}
}
if mismatched.is_empty() {
return None;
}
let spans: Vec<_> = mismatched
.iter()
.map(|param| {
let (LateEarlyMismatch::EarlyInImpl(impl_param_def_id, ..)
| LateEarlyMismatch::LateInImpl(impl_param_def_id, ..)) = *param;
tcx.def_span(impl_param_def_id)
})
.collect();
let mut diag = tcx
.dcx()
.struct_span_err(spans, "lifetime parameters do not match the trait definition")
.with_note("lifetime parameters differ in whether they are early- or late-bound")
.with_code(E0195);
for mismatch in mismatched {
match mismatch {
LateEarlyMismatch::EarlyInImpl(
impl_param_def_id,
trait_param_def_id,
early_bound_region,
) => {
let mut multispan = MultiSpan::from_spans(vec![
tcx.def_span(impl_param_def_id),
tcx.def_span(trait_param_def_id),
]);
multispan
.push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
multispan
.push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
multispan.push_span_label(
tcx.def_span(impl_param_def_id),
format!("`{}` is early-bound", tcx.item_name(impl_param_def_id)),
);
multispan.push_span_label(
tcx.def_span(trait_param_def_id),
format!("`{}` is late-bound", tcx.item_name(trait_param_def_id)),
);
if let Some(span) = find_region_in_clauses(tcx, impl_m.def_id, early_bound_region) {
multispan.push_span_label(
span,
format!(
"this lifetime bound makes `{}` early-bound",
tcx.item_name(impl_param_def_id)
),
);
}
diag.span_note(
multispan,
format!(
"`{}` differs between the trait and impl",
tcx.item_name(impl_param_def_id)
),
);
}
LateEarlyMismatch::LateInImpl(
impl_param_def_id,
trait_param_def_id,
early_bound_region,
) => {
let mut multispan = MultiSpan::from_spans(vec![
tcx.def_span(impl_param_def_id),
tcx.def_span(trait_param_def_id),
]);
multispan
.push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
multispan
.push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
multispan.push_span_label(
tcx.def_span(impl_param_def_id),
format!("`{}` is late-bound", tcx.item_name(impl_param_def_id)),
);
multispan.push_span_label(
tcx.def_span(trait_param_def_id),
format!("`{}` is early-bound", tcx.item_name(trait_param_def_id)),
);
if let Some(span) = find_region_in_clauses(tcx, trait_m.def_id, early_bound_region)
{
multispan.push_span_label(
span,
format!(
"this lifetime bound makes `{}` early-bound",
tcx.item_name(trait_param_def_id)
),
);
}
diag.span_note(
multispan,
format!(
"`{}` differs between the trait and impl",
tcx.item_name(impl_param_def_id)
),
);
}
}
}
Some(diag.emit())
}
fn find_region_in_clauses<'tcx>(
tcx: TyCtxt<'tcx>,
def_id: DefId,
early_bound_region: ty::Region<'tcx>,
) -> Option<Span> {
for (clause, span) in tcx.explicit_clauses_of(def_id).instantiate_identity(tcx) {
if clause.skip_norm_wip().visit_with(&mut FindRegion(early_bound_region)).is_break() {
return Some(span);
}
}
struct FindRegion<'tcx>(ty::Region<'tcx>);
impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindRegion<'tcx> {
type Result = ControlFlow<()>;
fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
if r == self.0 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
}
}
None
}
#[instrument(level = "debug", skip(infcx))]
fn extract_spans_for_error_reporting<'tcx>(
infcx: &infer::InferCtxt<'tcx>,
terr: TypeError<'_>,
cause: &ObligationCause<'tcx>,
impl_m: ty::AssocItem,
trait_m: ty::AssocItem,
) -> (Span, Option<Span>) {
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)),
}
}
fn compare_self_type<'tcx>(
tcx: TyCtxt<'tcx>,
impl_m: ty::AssocItem,
trait_m: ty::AssocItem,
impl_trait_ref: ty::TraitRef<'tcx>,
delay: bool,
) -> Result<(), ErrorGuaranteed> {
let self_string = |method: ty::AssocItem| {
let untransformed_self_ty = match method.container {
ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
impl_trait_ref.self_ty()
}
ty::AssocContainer::Trait => tcx.types.self_param,
};
let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip().input(0);
let (infcx, param_env) = tcx
.infer_ctxt()
.build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, method.def_id));
let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
get_self_string(self_arg_ty, can_eq_self)
};
match (trait_m.is_method(), impl_m.is_method()) {
(false, false) | (true, true) => {}
(false, true) => {
let self_descr = self_string(impl_m);
let impl_m_span = tcx.def_span(impl_m.def_id);
let mut err = struct_span_code_err!(
tcx.dcx(),
impl_m_span,
E0185,
"method `{}` has a `{}` declaration in the impl, but not in the trait",
trait_m.name(),
self_descr
);
err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
err.span_label(span, format!("trait method declared without `{self_descr}`"));
} else {
err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
}
return Err(err.emit_unless_delay(delay));
}
(true, false) => {
let self_descr = self_string(trait_m);
let impl_m_span = tcx.def_span(impl_m.def_id);
let mut err = struct_span_code_err!(
tcx.dcx(),
impl_m_span,
E0186,
"method `{}` has a `{}` declaration in the trait, but not in the impl",
trait_m.name(),
self_descr
);
err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
err.span_label(span, format!("`{self_descr}` used in trait"));
} else {
err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
}
return Err(err.emit_unless_delay(delay));
}
}
Ok(())
}
fn compare_number_of_generics<'tcx>(
tcx: TyCtxt<'tcx>,
impl_: ty::AssocItem,
trait_: ty::AssocItem,
delay: bool,
) -> Result<(), ErrorGuaranteed> {
let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
if (trait_own_counts.types + trait_own_counts.consts)
== (impl_own_counts.types + impl_own_counts.consts)
{
return Ok(());
}
if trait_.is_impl_trait_in_trait() {
tcx.dcx()
.bug("errors comparing numbers of generics of trait/impl functions were not emitted");
}
let matchings = [
("type", trait_own_counts.types, impl_own_counts.types),
("const", trait_own_counts.consts, impl_own_counts.consts),
];
let item_kind = impl_.descr();
let mut err_occurred = None;
for (kind, trait_count, impl_count) in matchings {
if impl_count != trait_count {
let arg_spans = |item: &ty::AssocItem, generics: &hir::Generics<'_>| {
let mut spans = generics
.params
.iter()
.filter(|p| match p.kind {
hir::GenericParamKind::Lifetime {
kind: hir::LifetimeParamKind::Elided(_),
} => {
!item.is_fn()
}
_ => true,
})
.map(|p| p.span)
.collect::<Vec<Span>>();
if spans.is_empty() {
spans = vec![generics.span]
}
spans
};
let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
let trait_item = tcx.hir_expect_trait_item(def_id);
let arg_spans: Vec<Span> = arg_spans(&trait_, trait_item.generics);
let impl_trait_spans: Vec<Span> = trait_item
.generics
.params
.iter()
.filter_map(|p| match p.kind {
GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
_ => None,
})
.collect();
(Some(arg_spans), impl_trait_spans)
} else {
let trait_span = tcx.hir_span_if_local(trait_.def_id);
(trait_span.map(|s| vec![s]), vec![])
};
let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
let impl_item_impl_trait_spans: Vec<Span> = impl_item
.generics
.params
.iter()
.filter_map(|p| match p.kind {
GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
_ => None,
})
.collect();
let spans = arg_spans(&impl_, impl_item.generics);
let span = spans.first().copied();
let mut err = tcx.dcx().struct_span_err(
spans,
format!(
"{} `{}` has {} {kind} parameter{} but its trait \
declaration has {} {kind} parameter{}",
item_kind,
trait_.name(),
impl_count,
pluralize!(impl_count),
trait_count,
pluralize!(trait_count),
kind = kind,
),
);
err.code(E0049);
let msg =
format!("expected {trait_count} {kind} parameter{}", pluralize!(trait_count),);
if let Some(spans) = trait_spans {
let mut spans = spans.iter();
if let Some(span) = spans.next() {
err.span_label(*span, msg);
}
for span in spans {
err.span_label(*span, "");
}
} else {
err.span_label(tcx.def_span(trait_.def_id), msg);
}
if let Some(span) = span {
err.span_label(
span,
format!("found {} {} parameter{}", impl_count, kind, pluralize!(impl_count),),
);
}
for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
}
let reported = err.emit_unless_delay(delay);
err_occurred = Some(reported);
}
}
if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
}
fn compare_number_of_method_arguments<'tcx>(
tcx: TyCtxt<'tcx>,
impl_m: ty::AssocItem,
trait_m: ty::AssocItem,
delay: bool,
) -> Result<(), ErrorGuaranteed> {
let impl_m_fty = tcx.fn_sig(impl_m.def_id);
let trait_m_fty = tcx.fn_sig(trait_m.def_id);
let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
if trait_number_args != impl_number_args {
let trait_span = trait_m
.def_id
.as_local()
.and_then(|def_id| {
let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
let pos = trait_number_args.saturating_sub(1);
trait_m_sig.decl.inputs.get(pos).map(|arg| {
if pos == 0 {
arg.span
} else {
arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
}
})
})
.or_else(|| tcx.hir_span_if_local(trait_m.def_id));
let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
let pos = impl_number_args.saturating_sub(1);
let impl_span = impl_m_sig
.decl
.inputs
.get(pos)
.map(|arg| {
if pos == 0 {
arg.span
} else {
arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
}
})
.unwrap_or_else(|| tcx.def_span(impl_m.def_id));
let mut err = struct_span_code_err!(
tcx.dcx(),
impl_span,
E0050,
"method `{}` has {} but the declaration in trait `{}` has {}",
trait_m.name(),
potentially_plural_count(impl_number_args, "parameter"),
tcx.def_path_str(trait_m.def_id),
trait_number_args
);
if let Some(trait_span) = trait_span {
err.span_label(
trait_span,
format!(
"trait requires {}",
potentially_plural_count(trait_number_args, "parameter")
),
);
} else {
err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
}
err.span_label(
impl_span,
format!(
"expected {}, found {}",
potentially_plural_count(trait_number_args, "parameter"),
impl_number_args
),
);
if !trait_m.def_id.is_local() {
let trait_sig = tcx.fn_sig(trait_m.def_id);
let trait_arg_idents = tcx.fn_arg_idents(trait_m.def_id);
let sm = tcx.sess.source_map();
let impl_inputs_span = if let (Some(first), Some(last)) =
(impl_m_sig.decl.inputs.first(), impl_m_sig.decl.inputs.last())
{
let arg_idents = tcx.fn_arg_idents(impl_m.def_id);
let first_lo = arg_idents
.get(0)
.and_then(|id| id.map(|id| id.span.lo()))
.unwrap_or(first.span.lo());
Some(impl_m_sig.span.with_lo(first_lo).with_hi(last.span.hi()))
} else {
sm.span_to_snippet(impl_m_sig.span).ok().and_then(|s| {
let right_paren = s.as_bytes().iter().rposition(|&b| b == b')')?;
let pos = impl_m_sig.span.lo() + BytePos(right_paren as u32);
Some(impl_m_sig.span.with_lo(pos).with_hi(pos))
})
};
let suggestion = match trait_number_args.cmp(&impl_number_args) {
Ordering::Greater => {
let trait_inputs = trait_sig.skip_binder().inputs().skip_binder();
let missing = trait_inputs
.iter()
.enumerate()
.skip(impl_number_args)
.map(|(idx, ty)| {
let name = trait_arg_idents
.get(idx)
.and_then(|ident| *ident)
.map(|ident| ident.to_string())
.unwrap_or_else(|| "_".to_string());
format!("{name}: {ty}")
})
.collect::<Vec<_>>();
if missing.is_empty() {
None
} else {
impl_inputs_span.map(|s| {
let span = s.shrink_to_hi();
let prefix = if impl_number_args == 0 { "" } else { ", " };
let replacement = format!("{prefix}{}", missing.join(", "));
(
span,
format!(
"add the missing parameter{} from the trait",
pluralize!(trait_number_args - impl_number_args)
),
replacement,
)
})
}
}
Ordering::Less => impl_inputs_span.and_then(|full| {
let lo = if trait_number_args == 0 {
full.lo()
} else {
impl_m_sig
.decl
.inputs
.get(trait_number_args - 1)
.map(|arg| arg.span.hi())?
};
let span = full.with_lo(lo);
Some((
span,
format!(
"remove the extra parameter{} to match the trait",
pluralize!(impl_number_args - trait_number_args)
),
String::new(),
))
}),
Ordering::Equal => unreachable!(),
};
if let Some((span, msg, replacement)) = suggestion {
err.span_suggestion_verbose(span, msg, replacement, Applicability::MaybeIncorrect);
}
}
return Err(err.emit_unless_delay(delay));
}
Ok(())
}
fn compare_synthetic_generics<'tcx>(
tcx: TyCtxt<'tcx>,
impl_m: ty::AssocItem,
trait_m: ty::AssocItem,
delay: bool,
) -> Result<(), ErrorGuaranteed> {
let mut error_found = None;
let impl_m_generics = tcx.generics_of(impl_m.def_id);
let trait_m_generics = tcx.generics_of(trait_m.def_id);
let impl_m_type_params =
impl_m_generics.own_params.iter().filter_map(|param| match param.kind {
GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
});
let trait_m_type_params =
trait_m_generics.own_params.iter().filter_map(|param| match param.kind {
GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
});
for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
iter::zip(impl_m_type_params, trait_m_type_params)
{
if impl_synthetic != trait_synthetic {
let impl_def_id = impl_def_id.expect_local();
let impl_span = tcx.def_span(impl_def_id);
let trait_span = tcx.def_span(trait_def_id);
let mut err = struct_span_code_err!(
tcx.dcx(),
impl_span,
E0643,
"method `{}` has incompatible signature for trait",
trait_m.name()
);
err.span_label(trait_span, "declaration in trait here");
if impl_synthetic {
err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
(|| {
let new_name = tcx.opt_item_name(trait_def_id)?;
let trait_m = trait_m.def_id.as_local()?;
let trait_m = tcx.hir_expect_trait_item(trait_m);
let impl_m = impl_m.def_id.as_local()?;
let impl_m = tcx.hir_expect_impl_item(impl_m);
let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
let generics_span = impl_m.generics.span.substitute_dummy(new_generics_span);
let new_generics =
tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
err.multipart_suggestion(
"try changing the `impl Trait` argument to a generic parameter",
vec![
(impl_span, new_name.to_string()),
(generics_span, new_generics),
],
Applicability::MaybeIncorrect,
);
Some(())
})();
} else {
err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
(|| {
let impl_m = impl_m.def_id.as_local()?;
let impl_m = tcx.hir_expect_impl_item(impl_m);
let (sig, _) = impl_m.expect_fn();
let input_tys = sig.decl.inputs;
struct Visitor(hir::def_id::LocalDefId);
impl<'v> intravisit::Visitor<'v> for Visitor {
type NestedFilter = intravisit::IgnoreNested;
type Result = ControlFlow<Span>;
fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) -> Self::Result {
if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
&& let Res::Def(DefKind::TyParam, def_id) = path.res
&& def_id == self.0.to_def_id()
{
ControlFlow::Break(ty.span)
} else {
intravisit::walk_ty(self, ty)
}
}
}
let span = input_tys
.iter()
.find_map(|ty| Visitor(impl_def_id).visit_ty_unambig(ty).break_value())?;
let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
let bounds = bounds.first()?.span().to(bounds.last()?.span());
let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
err.multipart_suggestion(
"try removing the generic parameter and using `impl Trait` instead",
vec![
(impl_m.generics.span, String::new()),
(span, format!("impl {bounds}")),
],
Applicability::MaybeIncorrect,
);
Some(())
})();
}
error_found = Some(err.emit_unless_delay(delay));
}
}
if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
}
fn compare_generic_param_kinds<'tcx>(
tcx: TyCtxt<'tcx>,
impl_item: ty::AssocItem,
trait_item: ty::AssocItem,
delay: bool,
) -> Result<(), ErrorGuaranteed> {
assert_eq!(impl_item.tag(), trait_item.tag());
let ty_const_params_of = |def_id| {
tcx.generics_of(def_id).own_params.iter().filter(|param| {
matches!(
param.kind,
GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
)
})
};
for (param_impl, param_trait) in
iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
{
use GenericParamDefKind::*;
if match (¶m_impl.kind, ¶m_trait.kind) {
(Const { .. }, Const { .. })
if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
{
true
}
(Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
(Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
(Lifetime { .. }, _) | (_, Lifetime { .. }) => {
bug!("lifetime params are expected to be filtered by `ty_const_params_of`")
}
} {
let param_impl_span = tcx.def_span(param_impl.def_id);
let param_trait_span = tcx.def_span(param_trait.def_id);
let mut err = struct_span_code_err!(
tcx.dcx(),
param_impl_span,
E0053,
"{} `{}` has an incompatible generic parameter for trait `{}`",
impl_item.descr(),
trait_item.name(),
&tcx.def_path_str(tcx.parent(trait_item.def_id))
);
let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
Const { .. } => {
format!(
"{} const parameter of type `{}`",
prefix,
tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip()
)
}
Type { .. } => format!("{prefix} type parameter"),
Lifetime { .. } => span_bug!(
tcx.def_span(param.def_id),
"lifetime params are expected to be filtered by `ty_const_params_of`"
),
};
let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
err.span_label(trait_header_span, "");
err.span_label(param_trait_span, make_param_message("expected", param_trait));
let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
err.span_label(impl_header_span, "");
err.span_label(param_impl_span, make_param_message("found", param_impl));
let reported = err.emit_unless_delay(delay);
return Err(reported);
}
}
Ok(())
}
fn compare_impl_const<'tcx>(
tcx: TyCtxt<'tcx>,
impl_const_item: ty::AssocItem,
trait_const_item: ty::AssocItem,
impl_trait_ref: ty::TraitRef<'tcx>,
) -> Result<(), ErrorGuaranteed> {
compare_type_const(tcx, impl_const_item, trait_const_item)?;
compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
check_region_bounds_on_impl_item(tcx, impl_const_item, trait_const_item, false)?;
compare_const_clause_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
}
fn compare_type_const<'tcx>(
tcx: TyCtxt<'tcx>,
impl_const_item: ty::AssocItem,
trait_const_item: ty::AssocItem,
) -> Result<(), ErrorGuaranteed> {
let impl_is_type_const = tcx.is_type_const(impl_const_item.def_id);
let trait_type_const_span = tcx.type_const_span(trait_const_item.def_id);
if let Some(trait_type_const_span) = trait_type_const_span
&& !impl_is_type_const
{
return Err(tcx
.dcx()
.struct_span_err(
tcx.def_span(impl_const_item.def_id),
"implementation of a `type const` must also be marked as `type const`",
)
.with_span_note(
MultiSpan::from_spans(vec![
tcx.def_span(trait_const_item.def_id),
trait_type_const_span,
]),
"trait declaration of const is marked as `type const`",
)
.emit());
}
Ok(())
}
#[instrument(level = "debug", skip(tcx))]
fn compare_const_clause_entailment<'tcx>(
tcx: TyCtxt<'tcx>,
impl_ct: ty::AssocItem,
trait_ct: ty::AssocItem,
impl_trait_ref: ty::TraitRef<'tcx>,
) -> Result<(), ErrorGuaranteed> {
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_clauses = tcx.clauses_of(impl_ct.def_id);
let trait_ct_clauses = tcx.clauses_of(trait_ct.def_id);
let impl_clauses = tcx.clauses_of(impl_ct_clauses.parent.unwrap());
let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
hybrid_clauses.extend(
trait_ct_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(clause, _)| clause),
);
let hybrid_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
let param_env = ty::ParamEnv::new(tcx, hybrid_clauses);
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_clauses.instantiate_own_identity();
for (clause, span) in impl_ct_own_bounds {
let cause = ObligationCause::misc(span, impl_ct_def_id);
let clause = ocx.normalize(&cause, param_env, clause);
let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
}
let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
debug!(?impl_ty);
let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
debug!(?trait_ty);
let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
if let Err(terr) = err {
debug!(?impl_ty, ?trait_ty);
let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
cause.span = ty.span;
let mut diag = struct_span_code_err!(
tcx.dcx(),
cause.span,
E0326,
"implemented const `{}` has an incompatible type for trait",
trait_ct.name()
);
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 let TraitErrors::HasErrors(errors) = errors {
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))]
fn compare_impl_ty<'tcx>(
tcx: TyCtxt<'tcx>,
impl_ty: ty::AssocItem,
trait_ty: ty::AssocItem,
impl_trait_ref: ty::TraitRef<'tcx>,
) -> Result<(), ErrorGuaranteed> {
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_clause_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))]
fn compare_type_clause_entailment<'tcx>(
tcx: TyCtxt<'tcx>,
impl_ty: ty::AssocItem,
trait_ty: ty::AssocItem,
impl_trait_ref: ty::TraitRef<'tcx>,
) -> Result<(), ErrorGuaranteed> {
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_clauses = tcx.clauses_of(impl_ty.def_id);
let trait_ty_clauses = tcx.clauses_of(trait_ty.def_id);
let impl_ty_own_bounds = impl_ty_clauses.instantiate_own_identity();
if impl_ty_own_bounds.len() == 0 {
return Ok(());
}
let impl_ty_def_id = impl_ty.def_id.expect_local();
debug!(?trait_to_impl_args);
let impl_clauses = tcx.clauses_of(impl_ty_clauses.parent.unwrap());
let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
hybrid_clauses.extend(
trait_ty_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(predicate, _)| predicate),
);
debug!(?hybrid_clauses);
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_clauses.extend(
tcx.const_conditions(impl_ty_clauses.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_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
let param_env = ty::ParamEnv::new(tcx, hybrid_clauses);
let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
debug!(?param_env);
let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
for (clause, span) in impl_ty_own_bounds {
let cause = ObligationCause::misc(span, impl_ty_def_id);
let clause = ocx.normalize(&cause, param_env, clause);
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, clause));
}
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 let TraitErrors::HasErrors(errors) = errors {
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))]
pub(super) fn check_type_bounds<'tcx>(
tcx: TyCtxt<'tcx>,
trait_ty: ty::AssocItem,
impl_ty: ty::AssocItem,
impl_trait_ref: ty::TraitRef<'tcx>,
) -> Result<(), ErrorGuaranteed> {
tcx.ensure_result().coherent_trait(impl_trait_ref.def_id)?;
let param_env = tcx.param_env(impl_ty.def_id);
debug!(?param_env);
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 => span_bug!(
tcx.def_span(impl_ty_def_id),
"cannot call `check_type_bounds` on item: {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)| {
debug!(?concrete_ty_bound);
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),
)
}),
));
}
debug!(item_bounds=?obligations);
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 let TraitErrors::HasErrors(errors) = errors {
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)
}
fn param_env_with_gat_bounds<'tcx>(
tcx: TyCtxt<'tcx>,
impl_ty: ty::AssocItem,
impl_trait_ref: ty::TraitRef<'tcx>,
) -> ty::ParamEnv<'tcx> {
let param_env = tcx.param_env(impl_ty.def_id);
let container_id = impl_ty.container_id(tcx);
let mut clauses = param_env.caller_bounds().collect::<Vec<_>>();
let impl_tys_to_install = match impl_ty.kind {
ty::AssocKind::Type {
data:
ty::AssocTypeData::Rpitit(
ty::ImplTraitInTraitData::Impl { fn_def_id }
| ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
),
} => tcx
.associated_types_for_impl_traits_in_associated_fn(fn_def_id)
.iter()
.map(|def_id| tcx.associated_item(*def_id))
.collect(),
_ => vec![impl_ty],
};
for impl_ty in impl_tys_to_install {
let trait_ty = match impl_ty.container {
ty::AssocContainer::InherentImpl => bug!(),
ty::AssocContainer::Trait => impl_ty,
ty::AssocContainer::TraitImpl(Err(_)) => continue,
ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
tcx.associated_item(trait_item_def_id)
}
};
let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind<'tcx>; 8]> =
smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
.extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
GenericParamDefKind::Type { .. } => {
let kind = ty::BoundTyKind::Param(param.def_id);
let bound_var = ty::BoundVariableKind::Ty(kind);
bound_vars.push(bound_var);
Ty::new_bound(
tcx,
ty::INNERMOST,
ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
)
.into()
}
GenericParamDefKind::Lifetime => {
let kind = ty::BoundRegionKind::Named(param.def_id);
let bound_var = ty::BoundVariableKind::Region(kind);
bound_vars.push(bound_var);
ty::Region::new_bound(
tcx,
ty::INNERMOST,
ty::BoundRegion {
var: ty::BoundVar::from_usize(bound_vars.len() - 1),
kind,
},
)
.into()
}
GenericParamDefKind::Const { .. } => {
let bound_var = ty::BoundVariableKind::Const;
bound_vars.push(bound_var);
ty::Const::new_bound(
tcx,
ty::INNERMOST,
ty::BoundConst::new(ty::BoundVar::from_usize(bound_vars.len() - 1)),
)
.into()
}
});
let normalize_impl_ty =
tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args).skip_norm_wip();
let rebased_args =
normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
match normalize_impl_ty.kind() {
&ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
if def_id == trait_ty.def_id && args == rebased_args =>
{
}
_ => clauses.push(
ty::Binder::bind_with_vars(
ty::ProjectionClause {
projection_term: ty::AliasTerm::new_from_def_id(
tcx,
trait_ty.def_id,
rebased_args,
),
term: normalize_impl_ty.into(),
},
bound_vars,
)
.upcast(tcx),
),
};
}
ty::ParamEnv::new(tcx, clauses)
}
fn try_report_async_mismatch<'tcx>(
tcx: TyCtxt<'tcx>,
infcx: &InferCtxt<'tcx>,
errors: &[FulfillmentError<'tcx>],
trait_m: ty::AssocItem,
impl_m: ty::AssocItem,
impl_sig: ty::FnSig<'tcx>,
) -> Result<(), ErrorGuaranteed> {
if !tcx.asyncness(trait_m.def_id).is_async() {
return Ok(());
}
let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id: async_future_def_id }, .. }) =
*tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
else {
bug!("expected `async fn` to return an RPITIT");
};
for error in errors {
if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
&& def_id == async_future_def_id
&& let Some(proj) = error.root_obligation.predicate.as_projection_clause()
&& let Some(proj) = proj.no_bound_vars()
&& infcx.can_eq(
error.root_obligation.param_env,
proj.term.expect_type(),
impl_sig.output(),
)
{
return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
span: tcx.def_span(impl_m.def_id),
method_name: tcx.item_ident(impl_m.def_id),
trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
}));
}
}
Ok(())
}