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::{TraitErrors, util};
15use rustc_middle::ty::error::{ExpectedFound, TypeError};
16use rustc_middle::ty::{
17 self, BottomUpFolder, GenericArgs, GenericParamDefKind, Generics, RegionExt, Ty, TyCtxt,
18 TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypeVisitor,
19 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::solve::NextSolverError;
27use rustc_trait_selection::traits::{
28 self, FromSolverError, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
29};
30use tracing::{debug, instrument};
31
32use super::potentially_plural_count;
33use crate::diagnostics::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture};
34
35pub(super) mod refine;
36
37pub(super) fn compare_impl_item(
39 tcx: TyCtxt<'_>,
40 impl_item_def_id: LocalDefId,
41) -> Result<(), ErrorGuaranteed> {
42 let impl_item = tcx.associated_item(impl_item_def_id);
43 let trait_item = tcx.associated_item(impl_item.expect_trait_impl()?);
44 let impl_trait_ref =
45 tcx.impl_trait_ref(impl_item.container_id(tcx)).instantiate_identity().skip_norm_wip();
46 {
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:46",
"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(46u32),
::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);
47
48 match impl_item.kind {
49 ty::AssocKind::Fn { .. } => compare_impl_method(tcx, impl_item, trait_item, impl_trait_ref),
50 ty::AssocKind::Type { .. } => compare_impl_ty(tcx, impl_item, trait_item, impl_trait_ref),
51 ty::AssocKind::Const { .. } => {
52 compare_impl_const(tcx, impl_item, trait_item, impl_trait_ref)
53 }
54 }
55}
56
57#[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(65u32),
::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_clause_entailment(tcx, impl_m, trait_m,
impl_trait_ref)?;
Ok(())
}
}
}#[instrument(level = "debug", skip(tcx))]
66fn compare_impl_method<'tcx>(
67 tcx: TyCtxt<'tcx>,
68 impl_m: ty::AssocItem,
69 trait_m: ty::AssocItem,
70 impl_trait_ref: ty::TraitRef<'tcx>,
71) -> Result<(), ErrorGuaranteed> {
72 check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, false)?;
73 compare_method_clause_entailment(tcx, impl_m, trait_m, impl_trait_ref)?;
74 Ok(())
75}
76
77fn check_method_is_structurally_compatible<'tcx>(
81 tcx: TyCtxt<'tcx>,
82 impl_m: ty::AssocItem,
83 trait_m: ty::AssocItem,
84 impl_trait_ref: ty::TraitRef<'tcx>,
85 delay: bool,
86) -> Result<(), ErrorGuaranteed> {
87 compare_self_type(tcx, impl_m, trait_m, impl_trait_ref, delay)?;
88 compare_number_of_generics(tcx, impl_m, trait_m, delay)?;
89 compare_generic_param_kinds(tcx, impl_m, trait_m, delay)?;
90 compare_number_of_method_arguments(tcx, impl_m, trait_m, delay)?;
91 compare_synthetic_generics(tcx, impl_m, trait_m, delay)?;
92 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, delay)?;
93 Ok(())
94}
95
96#[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_clause_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(174u32),
::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:205",
"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(205u32),
::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_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.mk_clauses_from_iter(hybrid_clauses));
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_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));
{
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 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(())
}
}
}#[instrument(level = "debug", skip(tcx, impl_trait_ref))]
175fn compare_method_clause_entailment<'tcx>(
176 tcx: TyCtxt<'tcx>,
177 impl_m: ty::AssocItem,
178 trait_m: ty::AssocItem,
179 impl_trait_ref: ty::TraitRef<'tcx>,
180) -> Result<(), ErrorGuaranteed> {
181 let impl_m_def_id = impl_m.def_id.expect_local();
187 let impl_m_span = tcx.def_span(impl_m_def_id);
188 let cause = ObligationCause::new(
189 impl_m_span,
190 impl_m_def_id,
191 ObligationCauseCode::CompareImplItem {
192 impl_item_def_id: impl_m_def_id,
193 trait_item_def_id: trait_m.def_id,
194 kind: impl_m.kind,
195 },
196 );
197
198 let impl_def_id = impl_m.container_id(tcx);
200 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
201 tcx,
202 impl_m.container_id(tcx),
203 impl_trait_ref.args,
204 );
205 debug!(?trait_to_impl_args);
206
207 let impl_m_clauses = tcx.clauses_of(impl_m.def_id);
208 let trait_m_clauses = tcx.clauses_of(trait_m.def_id);
209
210 let impl_clauses = tcx.clauses_of(impl_m_clauses.parent.unwrap());
218 let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
219 hybrid_clauses
220 .extend(trait_m_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(clause, _)| clause));
221
222 let is_conditionally_const = tcx.is_conditionally_const(impl_m.def_id);
223 if is_conditionally_const {
224 hybrid_clauses.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_clauses = hybrid_clauses.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_clauses));
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_clauses.instantiate_own_identity();
267 for (clause, span) in impl_m_own_bounds {
268 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
269 let clause = ocx.normalize(&normalize_cause, param_env, clause);
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, clause));
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 let TraitErrors::HasErrors(errors) = errors {
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_clauses = tcx
492 .clauses_of(impl_m.container_id(tcx))
493 .instantiate_identity(tcx)
494 .into_iter()
495 .chain(tcx.clauses_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_clauses));
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.clauses_of(impl_m_def_id).instantiate_own_identity();
514 for (clause, span) in impl_m_own_bounds {
515 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
516 let clause = ocx.normalize(&normalize_cause, param_env, clause);
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, clause));
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 let TraitErrors::HasErrors(errors) = errors {
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: FromSolverError<'tcx, NextSolverError<'tcx>>
807 + FromSolverError<'tcx, traits::OldSolverError<'tcx>>,
808{
809 fn new(
810 ocx: &'a ObligationCtxt<'a, 'tcx, E>,
811 span: Span,
812 param_env: ty::ParamEnv<'tcx>,
813 impl_m_id: LocalDefId,
814 ) -> Self {
815 ImplTraitInTraitCollector { ocx, types: FxIndexMap::default(), span, param_env, impl_m_id }
816 }
817}
818
819impl<'tcx, E> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx, E>
820where
821 E: FromSolverError<'tcx, NextSolverError<'tcx>>
822 + FromSolverError<'tcx, traits::OldSolverError<'tcx>>,
823{
824 fn cx(&self) -> TyCtxt<'tcx> {
825 self.ocx.infcx.tcx
826 }
827
828 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
829 if let &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args: proj_args, .. }) =
830 ty.kind()
831 && self.cx().is_impl_trait_in_trait(def_id)
832 {
833 if let Some((ty, _)) = self.types.get(&def_id) {
834 return *ty;
835 }
836 if proj_args.has_escaping_bound_vars() {
838 ::rustc_middle::util::bug::bug_fmt(format_args!("FIXME(RPITIT): error here"));bug!("FIXME(RPITIT): error here");
839 }
840 let infer_ty = self.ocx.infcx.next_ty_var(self.span);
842 self.types.insert(def_id, (infer_ty, proj_args));
843 for (pred, pred_span) in self
845 .cx()
846 .explicit_item_bounds(def_id)
847 .iter_instantiated_copied(self.cx(), proj_args)
848 .map(Unnormalized::skip_norm_wip)
849 {
850 let pred = pred.fold_with(self);
851 let pred = self.ocx.normalize(
852 &ObligationCause::misc(self.span, self.impl_m_id),
853 self.param_env,
854 Unnormalized::new_wip(pred),
855 );
856
857 self.ocx.register_obligation(traits::Obligation::new(
858 self.cx(),
859 ObligationCause::new(
860 self.span,
861 self.impl_m_id,
862 ObligationCauseCode::WhereClause(def_id, pred_span),
863 ),
864 self.param_env,
865 pred,
866 ));
867 }
868 infer_ty
869 } else {
870 ty.super_fold_with(self)
871 }
872 }
873}
874
875struct RemapHiddenTyRegions<'tcx> {
876 tcx: TyCtxt<'tcx>,
877 map: FxIndexMap<ty::Region<'tcx>, ty::Region<'tcx>>,
880 num_trait_args: usize,
881 num_impl_args: usize,
882 def_id: DefId,
884 impl_m_def_id: DefId,
886 ty: Ty<'tcx>,
888 return_span: Span,
890}
891
892impl<'tcx> ty::FallibleTypeFolder<TyCtxt<'tcx>> for RemapHiddenTyRegions<'tcx> {
893 type Error = ErrorGuaranteed;
894
895 fn cx(&self) -> TyCtxt<'tcx> {
896 self.tcx
897 }
898
899 fn try_fold_region(
900 &mut self,
901 region: ty::Region<'tcx>,
902 ) -> Result<ty::Region<'tcx>, Self::Error> {
903 match region.kind() {
904 ty::ReBound(..) | ty::ReStatic | ty::ReError(_) => return Ok(region),
906 ty::ReLateParam(_) => {}
908 ty::ReEarlyParam(ebr) => {
911 if ebr.index as usize >= self.num_impl_args {
912 } else {
914 return Ok(region);
915 }
916 }
917 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!(
918 "should not have leaked vars or placeholders into hidden type of RPITIT"
919 ),
920 }
921
922 let e = if let Some(id_region) = self.map.get(®ion) {
923 if let ty::ReEarlyParam(e) = id_region.kind() {
924 e
925 } else {
926 ::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!(
927 "expected to map region {region} to early-bound identity region, but got {id_region}"
928 );
929 }
930 } else {
931 let guar = match region.opt_param_def_id(self.tcx, self.impl_m_def_id) {
932 Some(def_id) => {
933 let return_span = if let &ty::Alias(
934 _,
935 ty::AliasTy { kind: ty::Opaque { def_id: opaque_ty_def_id }, .. },
936 ) = self.ty.kind()
937 {
938 self.tcx.def_span(opaque_ty_def_id)
939 } else {
940 self.return_span
941 };
942 self.tcx
943 .dcx()
944 .struct_span_err(
945 return_span,
946 "return type captures more lifetimes than trait definition",
947 )
948 .with_span_label(self.tcx.def_span(def_id), "this lifetime was captured")
949 .with_span_note(
950 self.tcx.def_span(self.def_id),
951 "hidden type must only reference lifetimes captured by this impl trait",
952 )
953 .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))
954 .emit()
955 }
956 None => {
957 self.tcx.dcx().bug("should've been able to remap region");
962 }
963 };
964 return Err(guar);
965 };
966
967 Ok(ty::Region::new_early_param(
968 self.tcx,
969 ty::EarlyParamRegion {
970 name: e.name,
971 index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32,
972 },
973 ))
974 }
975}
976
977fn get_self_string<'tcx, P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> String
980where
981 P: Fn(Ty<'tcx>) -> bool,
982{
983 if is_self_ty(self_arg_ty) {
984 "self".to_owned()
985 } else if let ty::Ref(_, ty, mutbl) = self_arg_ty.kind()
986 && is_self_ty(*ty)
987 {
988 match mutbl {
989 hir::Mutability::Not => "&self".to_owned(),
990 hir::Mutability::Mut => "&mut self".to_owned(),
991 }
992 } else {
993 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("self: {0}", self_arg_ty))
})format!("self: {self_arg_ty}")
994 }
995}
996
997fn report_trait_method_mismatch<'tcx>(
998 infcx: &InferCtxt<'tcx>,
999 mut cause: ObligationCause<'tcx>,
1000 param_env: ty::ParamEnv<'tcx>,
1001 terr: TypeError<'tcx>,
1002 (trait_m, trait_sig): (ty::AssocItem, ty::FnSig<'tcx>),
1003 (impl_m, impl_sig): (ty::AssocItem, ty::FnSig<'tcx>),
1004 impl_trait_ref: ty::TraitRef<'tcx>,
1005) -> ErrorGuaranteed {
1006 let tcx = infcx.tcx;
1007 let (impl_err_span, trait_err_span) =
1008 extract_spans_for_error_reporting(infcx, terr, &cause, impl_m, trait_m);
1009
1010 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!(
1011 tcx.dcx(),
1012 impl_err_span,
1013 E0053,
1014 "method `{}` has an incompatible type for trait",
1015 trait_m.name()
1016 );
1017 match &terr {
1018 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
1019 if trait_m.is_method() =>
1020 {
1021 let ty = trait_sig.inputs()[0];
1022 let sugg = get_self_string(ty, |ty| ty == impl_trait_ref.self_ty());
1023
1024 let (sig, body) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1028 let span = tcx
1029 .hir_body_param_idents(body)
1030 .zip(sig.decl.inputs.iter())
1031 .map(|(param_ident, ty)| {
1032 if let Some(param_ident) = param_ident {
1033 param_ident.span.to(ty.span)
1034 } else {
1035 ty.span
1036 }
1037 })
1038 .next()
1039 .unwrap_or(impl_err_span);
1040
1041 diag.span_suggestion_verbose(
1042 span,
1043 "change the self-receiver type to match the trait",
1044 sugg,
1045 Applicability::MachineApplicable,
1046 );
1047 }
1048 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
1049 if trait_sig.inputs().len() == *i {
1050 if let ImplItemKind::Fn(sig, _) =
1053 &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).kind
1054 && !sig.header.asyncness.is_async()
1055 {
1056 let msg = "change the output type to match the trait";
1057 let ap = Applicability::MachineApplicable;
1058 match sig.decl.output {
1059 hir::FnRetTy::DefaultReturn(sp) => {
1060 let sugg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" -> {0}", trait_sig.output()))
})format!(" -> {}", trait_sig.output());
1061 diag.span_suggestion_verbose(sp, msg, sugg, ap);
1062 }
1063 hir::FnRetTy::Return(hir_ty) => {
1064 let sugg = trait_sig.output();
1065 diag.span_suggestion_verbose(hir_ty.span, msg, sugg, ap);
1066 }
1067 };
1068 };
1069 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
1070 diag.span_suggestion_verbose(
1071 impl_err_span,
1072 "change the parameter type to match the trait",
1073 trait_ty,
1074 Applicability::MachineApplicable,
1075 );
1076 }
1077 }
1078 _ => {}
1079 }
1080
1081 cause.span = impl_err_span;
1082 infcx.err_ctxt().note_type_err(
1083 &mut diag,
1084 &cause,
1085 trait_err_span.map(|sp| (sp, Cow::from("type in trait"), false)),
1086 Some(param_env.and(infer::ValuePairs::PolySigs(ExpectedFound {
1087 expected: ty::Binder::dummy(trait_sig),
1088 found: ty::Binder::dummy(impl_sig),
1089 }))),
1090 terr,
1091 false,
1092 None,
1093 );
1094
1095 diag.emit()
1096}
1097
1098fn check_region_bounds_on_impl_item<'tcx>(
1099 tcx: TyCtxt<'tcx>,
1100 impl_m: ty::AssocItem,
1101 trait_m: ty::AssocItem,
1102 delay: bool,
1103) -> Result<(), ErrorGuaranteed> {
1104 let impl_generics = tcx.generics_of(impl_m.def_id);
1105 let impl_params = impl_generics.own_counts().lifetimes;
1106
1107 let trait_generics = tcx.generics_of(trait_m.def_id);
1108 let trait_params = trait_generics.own_counts().lifetimes;
1109
1110 let Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span }) =
1111 check_number_of_early_bound_regions(
1112 tcx,
1113 impl_m.def_id.expect_local(),
1114 trait_m.def_id,
1115 impl_generics,
1116 impl_params,
1117 trait_generics,
1118 trait_params,
1119 )
1120 else {
1121 return Ok(());
1122 };
1123
1124 if !delay && let Some(guar) = check_region_late_boundedness(tcx, impl_m, trait_m) {
1125 return Err(guar);
1126 }
1127
1128 let reported = tcx
1129 .dcx()
1130 .create_err(LifetimesOrBoundsMismatchOnTrait {
1131 span,
1132 item_kind: impl_m.descr(),
1133 ident: impl_m.ident(tcx),
1134 generics_span,
1135 bounds_span,
1136 where_span,
1137 })
1138 .emit_unless_delay(delay);
1139
1140 Err(reported)
1141}
1142
1143pub(super) struct CheckNumberOfEarlyBoundRegionsError {
1144 pub(super) span: Span,
1145 pub(super) generics_span: Span,
1146 pub(super) bounds_span: Vec<Span>,
1147 pub(super) where_span: Option<Span>,
1148}
1149
1150pub(super) fn check_number_of_early_bound_regions<'tcx>(
1151 tcx: TyCtxt<'tcx>,
1152 impl_def_id: LocalDefId,
1153 trait_def_id: DefId,
1154 impl_generics: &Generics,
1155 impl_params: usize,
1156 trait_generics: &Generics,
1157 trait_params: usize,
1158) -> Result<(), CheckNumberOfEarlyBoundRegionsError> {
1159 {
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:1159",
"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(1159u32),
::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);
1160
1161 if trait_params == impl_params {
1171 return Ok(());
1172 }
1173
1174 let span = tcx
1175 .hir_get_generics(impl_def_id)
1176 .expect("expected impl item to have generics or else we can't compare them")
1177 .span;
1178
1179 let mut generics_span = tcx.def_span(trait_def_id);
1180 let mut bounds_span = ::alloc::vec::Vec::new()vec![];
1181 let mut where_span = None;
1182
1183 if let Some(trait_node) = tcx.hir_get_if_local(trait_def_id)
1184 && let Some(trait_generics) = trait_node.generics()
1185 {
1186 generics_span = trait_generics.span;
1187 for p in trait_generics.predicates {
1190 match p.kind {
1191 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1192 bounds,
1193 ..
1194 })
1195 | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1196 bounds,
1197 ..
1198 }) => {
1199 for b in *bounds {
1200 if let hir::GenericBound::Outlives(lt) = b {
1201 bounds_span.push(lt.ident.span);
1202 }
1203 }
1204 }
1205 }
1206 }
1207 if let Some(impl_node) = tcx.hir_get_if_local(impl_def_id.into())
1208 && let Some(impl_generics) = impl_node.generics()
1209 {
1210 let mut impl_bounds = 0;
1211 for p in impl_generics.predicates {
1212 match p.kind {
1213 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1214 bounds,
1215 ..
1216 })
1217 | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1218 bounds,
1219 ..
1220 }) => {
1221 for b in *bounds {
1222 if let hir::GenericBound::Outlives(_) = b {
1223 impl_bounds += 1;
1224 }
1225 }
1226 }
1227 }
1228 }
1229 if impl_bounds == bounds_span.len() {
1230 bounds_span = ::alloc::vec::Vec::new()vec![];
1231 } else if impl_generics.has_where_clause_predicates {
1232 where_span = Some(impl_generics.where_clause_span);
1233 }
1234 }
1235 }
1236
1237 Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span })
1238}
1239
1240#[allow(unused)]
1241enum LateEarlyMismatch<'tcx> {
1242 EarlyInImpl(DefId, DefId, ty::Region<'tcx>),
1243 LateInImpl(DefId, DefId, ty::Region<'tcx>),
1244}
1245
1246fn check_region_late_boundedness<'tcx>(
1247 tcx: TyCtxt<'tcx>,
1248 impl_m: ty::AssocItem,
1249 trait_m: ty::AssocItem,
1250) -> Option<ErrorGuaranteed> {
1251 if !impl_m.is_fn() {
1252 return None;
1253 }
1254
1255 let (infcx, param_env) = tcx
1256 .infer_ctxt()
1257 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, impl_m.def_id));
1258
1259 let impl_m_args = infcx.fresh_args_for_item(DUMMY_SP, impl_m.def_id);
1260 let impl_m_sig = tcx.fn_sig(impl_m.def_id).instantiate(tcx, impl_m_args).skip_norm_wip();
1261 let impl_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, impl_m_sig);
1262
1263 let trait_m_args = infcx.fresh_args_for_item(DUMMY_SP, trait_m.def_id);
1264 let trait_m_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_args).skip_norm_wip();
1265 let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_m_sig);
1266
1267 let ocx = ObligationCtxt::new(&infcx);
1268
1269 let Ok(()) = ocx.eq(
1274 &ObligationCause::dummy(),
1275 param_env,
1276 ty::Binder::dummy(trait_m_sig),
1277 ty::Binder::dummy(impl_m_sig),
1278 ) else {
1279 return None;
1280 };
1281
1282 let errors = ocx.try_evaluate_obligations();
1283 if !errors.no_errors() {
1284 return None;
1285 }
1286
1287 let mut mismatched = ::alloc::vec::Vec::new()vec![];
1288
1289 let impl_generics = tcx.generics_of(impl_m.def_id);
1290 for (id_arg, arg) in
1291 std::iter::zip(ty::GenericArgs::identity_for_item(tcx, impl_m.def_id), impl_m_args)
1292 {
1293 if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1294 && let ty::ReVar(vid) = r.kind()
1295 && let r = infcx
1296 .inner
1297 .borrow_mut()
1298 .unwrap_region_constraints()
1299 .opportunistic_resolve_var(tcx, vid)
1300 && let ty::ReLateParam(ty::LateParamRegion {
1301 kind: ty::LateParamRegionKind::Named(trait_param_def_id),
1302 ..
1303 }) = r.kind()
1304 && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1305 {
1306 mismatched.push(LateEarlyMismatch::EarlyInImpl(
1307 impl_generics.region_param(ebr, tcx).def_id,
1308 trait_param_def_id,
1309 id_arg.expect_region(),
1310 ));
1311 }
1312 }
1313
1314 let trait_generics = tcx.generics_of(trait_m.def_id);
1315 for (id_arg, arg) in
1316 std::iter::zip(ty::GenericArgs::identity_for_item(tcx, trait_m.def_id), trait_m_args)
1317 {
1318 if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1319 && let ty::ReVar(vid) = r.kind()
1320 && let r = infcx
1321 .inner
1322 .borrow_mut()
1323 .unwrap_region_constraints()
1324 .opportunistic_resolve_var(tcx, vid)
1325 && let ty::ReLateParam(ty::LateParamRegion {
1326 kind: ty::LateParamRegionKind::Named(impl_param_def_id),
1327 ..
1328 }) = r.kind()
1329 && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1330 {
1331 mismatched.push(LateEarlyMismatch::LateInImpl(
1332 impl_param_def_id,
1333 trait_generics.region_param(ebr, tcx).def_id,
1334 id_arg.expect_region(),
1335 ));
1336 }
1337 }
1338
1339 if mismatched.is_empty() {
1340 return None;
1341 }
1342
1343 let spans: Vec<_> = mismatched
1344 .iter()
1345 .map(|param| {
1346 let (LateEarlyMismatch::EarlyInImpl(impl_param_def_id, ..)
1347 | LateEarlyMismatch::LateInImpl(impl_param_def_id, ..)) = *param;
1348 tcx.def_span(impl_param_def_id)
1349 })
1350 .collect();
1351
1352 let mut diag = tcx
1353 .dcx()
1354 .struct_span_err(spans, "lifetime parameters do not match the trait definition")
1355 .with_note("lifetime parameters differ in whether they are early- or late-bound")
1356 .with_code(E0195);
1357 for mismatch in mismatched {
1358 match mismatch {
1359 LateEarlyMismatch::EarlyInImpl(
1360 impl_param_def_id,
1361 trait_param_def_id,
1362 early_bound_region,
1363 ) => {
1364 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![
1365 tcx.def_span(impl_param_def_id),
1366 tcx.def_span(trait_param_def_id),
1367 ]);
1368 multispan
1369 .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1370 multispan
1371 .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1372 multispan.push_span_label(
1373 tcx.def_span(impl_param_def_id),
1374 ::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)),
1375 );
1376 multispan.push_span_label(
1377 tcx.def_span(trait_param_def_id),
1378 ::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)),
1379 );
1380 if let Some(span) = find_region_in_clauses(tcx, impl_m.def_id, early_bound_region) {
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) = find_region_in_clauses(tcx, trait_m.def_id, early_bound_region)
1419 {
1420 multispan.push_span_label(
1421 span,
1422 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
tcx.item_name(trait_param_def_id)))
})format!(
1423 "this lifetime bound makes `{}` early-bound",
1424 tcx.item_name(trait_param_def_id)
1425 ),
1426 );
1427 }
1428 diag.span_note(
1429 multispan,
1430 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
tcx.item_name(impl_param_def_id)))
})format!(
1431 "`{}` differs between the trait and impl",
1432 tcx.item_name(impl_param_def_id)
1433 ),
1434 );
1435 }
1436 }
1437 }
1438
1439 Some(diag.emit())
1440}
1441
1442fn find_region_in_clauses<'tcx>(
1443 tcx: TyCtxt<'tcx>,
1444 def_id: DefId,
1445 early_bound_region: ty::Region<'tcx>,
1446) -> Option<Span> {
1447 for (clause, span) in tcx.explicit_clauses_of(def_id).instantiate_identity(tcx) {
1448 if clause.skip_norm_wip().visit_with(&mut FindRegion(early_bound_region)).is_break() {
1449 return Some(span);
1450 }
1451 }
1452
1453 struct FindRegion<'tcx>(ty::Region<'tcx>);
1454 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindRegion<'tcx> {
1455 type Result = ControlFlow<()>;
1456 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
1457 if r == self.0 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
1458 }
1459 }
1460
1461 None
1462}
1463
1464#[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(1464u32),
::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))]
1465fn extract_spans_for_error_reporting<'tcx>(
1466 infcx: &infer::InferCtxt<'tcx>,
1467 terr: TypeError<'_>,
1468 cause: &ObligationCause<'tcx>,
1469 impl_m: ty::AssocItem,
1470 trait_m: ty::AssocItem,
1471) -> (Span, Option<Span>) {
1472 let tcx = infcx.tcx;
1473 let mut impl_args = {
1474 let (sig, _) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1475 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1476 };
1477
1478 let trait_args = trait_m.def_id.as_local().map(|def_id| {
1479 let (sig, _) = tcx.hir_expect_trait_item(def_id).expect_fn();
1480 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1481 });
1482
1483 match terr {
1484 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1485 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1486 }
1487 _ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
1488 }
1489}
1490
1491fn compare_self_type<'tcx>(
1492 tcx: TyCtxt<'tcx>,
1493 impl_m: ty::AssocItem,
1494 trait_m: ty::AssocItem,
1495 impl_trait_ref: ty::TraitRef<'tcx>,
1496 delay: bool,
1497) -> Result<(), ErrorGuaranteed> {
1498 let self_string = |method: ty::AssocItem| {
1507 let untransformed_self_ty = match method.container {
1508 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1509 impl_trait_ref.self_ty()
1510 }
1511 ty::AssocContainer::Trait => tcx.types.self_param,
1512 };
1513 let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip().input(0);
1514 let (infcx, param_env) = tcx
1515 .infer_ctxt()
1516 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, method.def_id));
1517 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1518 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
1519 get_self_string(self_arg_ty, can_eq_self)
1520 };
1521
1522 match (trait_m.is_method(), impl_m.is_method()) {
1523 (false, false) | (true, true) => {}
1524
1525 (false, true) => {
1526 let self_descr = self_string(impl_m);
1527 let impl_m_span = tcx.def_span(impl_m.def_id);
1528 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!(
1529 tcx.dcx(),
1530 impl_m_span,
1531 E0185,
1532 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1533 trait_m.name(),
1534 self_descr
1535 );
1536 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"));
1537 if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1538 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}`"));
1539 } else {
1540 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1541 }
1542 return Err(err.emit_unless_delay(delay));
1543 }
1544
1545 (true, false) => {
1546 let self_descr = self_string(trait_m);
1547 let impl_m_span = tcx.def_span(impl_m.def_id);
1548 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!(
1549 tcx.dcx(),
1550 impl_m_span,
1551 E0186,
1552 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1553 trait_m.name(),
1554 self_descr
1555 );
1556 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"));
1557 if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1558 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"));
1559 } else {
1560 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1561 }
1562
1563 return Err(err.emit_unless_delay(delay));
1564 }
1565 }
1566
1567 Ok(())
1568}
1569
1570fn compare_number_of_generics<'tcx>(
1592 tcx: TyCtxt<'tcx>,
1593 impl_: ty::AssocItem,
1594 trait_: ty::AssocItem,
1595 delay: bool,
1596) -> Result<(), ErrorGuaranteed> {
1597 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1598 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1599
1600 if (trait_own_counts.types + trait_own_counts.consts)
1604 == (impl_own_counts.types + impl_own_counts.consts)
1605 {
1606 return Ok(());
1607 }
1608
1609 if trait_.is_impl_trait_in_trait() {
1614 tcx.dcx()
1617 .bug("errors comparing numbers of generics of trait/impl functions were not emitted");
1618 }
1619
1620 let matchings = [
1621 ("type", trait_own_counts.types, impl_own_counts.types),
1622 ("const", trait_own_counts.consts, impl_own_counts.consts),
1623 ];
1624
1625 let item_kind = impl_.descr();
1626
1627 let mut err_occurred = None;
1628 for (kind, trait_count, impl_count) in matchings {
1629 if impl_count != trait_count {
1630 let arg_spans = |item: &ty::AssocItem, generics: &hir::Generics<'_>| {
1631 let mut spans = generics
1632 .params
1633 .iter()
1634 .filter(|p| match p.kind {
1635 hir::GenericParamKind::Lifetime {
1636 kind: hir::LifetimeParamKind::Elided(_),
1637 } => {
1638 !item.is_fn()
1641 }
1642 _ => true,
1643 })
1644 .map(|p| p.span)
1645 .collect::<Vec<Span>>();
1646 if spans.is_empty() {
1647 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]
1648 }
1649 spans
1650 };
1651 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1652 let trait_item = tcx.hir_expect_trait_item(def_id);
1653 let arg_spans: Vec<Span> = arg_spans(&trait_, trait_item.generics);
1654 let impl_trait_spans: Vec<Span> = trait_item
1655 .generics
1656 .params
1657 .iter()
1658 .filter_map(|p| match p.kind {
1659 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1660 _ => None,
1661 })
1662 .collect();
1663 (Some(arg_spans), impl_trait_spans)
1664 } else {
1665 let trait_span = tcx.hir_span_if_local(trait_.def_id);
1666 (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![])
1667 };
1668
1669 let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
1670 let impl_item_impl_trait_spans: Vec<Span> = impl_item
1671 .generics
1672 .params
1673 .iter()
1674 .filter_map(|p| match p.kind {
1675 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1676 _ => None,
1677 })
1678 .collect();
1679 let spans = arg_spans(&impl_, impl_item.generics);
1680 let span = spans.first().copied();
1681
1682 let mut err = tcx.dcx().struct_span_err(
1683 spans,
1684 ::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!(
1685 "{} `{}` has {} {kind} parameter{} but its trait \
1686 declaration has {} {kind} parameter{}",
1687 item_kind,
1688 trait_.name(),
1689 impl_count,
1690 pluralize!(impl_count),
1691 trait_count,
1692 pluralize!(trait_count),
1693 kind = kind,
1694 ),
1695 );
1696 err.code(E0049);
1697
1698 let msg =
1699 ::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),);
1700 if let Some(spans) = trait_spans {
1701 let mut spans = spans.iter();
1702 if let Some(span) = spans.next() {
1703 err.span_label(*span, msg);
1704 }
1705 for span in spans {
1706 err.span_label(*span, "");
1707 }
1708 } else {
1709 err.span_label(tcx.def_span(trait_.def_id), msg);
1710 }
1711
1712 if let Some(span) = span {
1713 err.span_label(
1714 span,
1715 ::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),),
1716 );
1717 }
1718
1719 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1720 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1721 }
1722
1723 let reported = err.emit_unless_delay(delay);
1724 err_occurred = Some(reported);
1725 }
1726 }
1727
1728 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1729}
1730
1731fn compare_number_of_method_arguments<'tcx>(
1732 tcx: TyCtxt<'tcx>,
1733 impl_m: ty::AssocItem,
1734 trait_m: ty::AssocItem,
1735 delay: bool,
1736) -> Result<(), ErrorGuaranteed> {
1737 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1738 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1739 let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
1740 let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1741
1742 if trait_number_args != impl_number_args {
1743 let trait_span = trait_m
1744 .def_id
1745 .as_local()
1746 .and_then(|def_id| {
1747 let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
1748 let pos = trait_number_args.saturating_sub(1);
1749 trait_m_sig.decl.inputs.get(pos).map(|arg| {
1750 if pos == 0 {
1751 arg.span
1752 } else {
1753 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1754 }
1755 })
1756 })
1757 .or_else(|| tcx.hir_span_if_local(trait_m.def_id));
1758
1759 let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1760 let pos = impl_number_args.saturating_sub(1);
1761 let impl_span = impl_m_sig
1762 .decl
1763 .inputs
1764 .get(pos)
1765 .map(|arg| {
1766 if pos == 0 {
1767 arg.span
1768 } else {
1769 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1770 }
1771 })
1772 .unwrap_or_else(|| tcx.def_span(impl_m.def_id));
1773
1774 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!(
1775 tcx.dcx(),
1776 impl_span,
1777 E0050,
1778 "method `{}` has {} but the declaration in trait `{}` has {}",
1779 trait_m.name(),
1780 potentially_plural_count(impl_number_args, "parameter"),
1781 tcx.def_path_str(trait_m.def_id),
1782 trait_number_args
1783 );
1784
1785 if let Some(trait_span) = trait_span {
1786 err.span_label(
1787 trait_span,
1788 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait requires {0}",
potentially_plural_count(trait_number_args, "parameter")))
})format!(
1789 "trait requires {}",
1790 potentially_plural_count(trait_number_args, "parameter")
1791 ),
1792 );
1793 } else {
1794 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1795 }
1796
1797 err.span_label(
1798 impl_span,
1799 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}, found {1}",
potentially_plural_count(trait_number_args, "parameter"),
impl_number_args))
})format!(
1800 "expected {}, found {}",
1801 potentially_plural_count(trait_number_args, "parameter"),
1802 impl_number_args
1803 ),
1804 );
1805
1806 if !trait_m.def_id.is_local() {
1808 let trait_sig = tcx.fn_sig(trait_m.def_id);
1809 let trait_arg_idents = tcx.fn_arg_idents(trait_m.def_id);
1810 let sm = tcx.sess.source_map();
1811 let impl_inputs_span = if let (Some(first), Some(last)) =
1815 (impl_m_sig.decl.inputs.first(), impl_m_sig.decl.inputs.last())
1816 {
1817 let arg_idents = tcx.fn_arg_idents(impl_m.def_id);
1821 let first_lo = arg_idents
1822 .get(0)
1823 .and_then(|id| id.map(|id| id.span.lo()))
1824 .unwrap_or(first.span.lo());
1825 Some(impl_m_sig.span.with_lo(first_lo).with_hi(last.span.hi()))
1826 } else {
1827 sm.span_to_snippet(impl_m_sig.span).ok().and_then(|s| {
1832 let right_paren = s.as_bytes().iter().rposition(|&b| b == b')')?;
1833 let pos = impl_m_sig.span.lo() + BytePos(right_paren as u32);
1834 Some(impl_m_sig.span.with_lo(pos).with_hi(pos))
1835 })
1836 };
1837 let suggestion = match trait_number_args.cmp(&impl_number_args) {
1838 Ordering::Greater => {
1839 let trait_inputs = trait_sig.skip_binder().inputs().skip_binder();
1843 let missing = trait_inputs
1844 .iter()
1845 .enumerate()
1846 .skip(impl_number_args)
1847 .map(|(idx, ty)| {
1848 let name = trait_arg_idents
1849 .get(idx)
1850 .and_then(|ident| *ident)
1851 .map(|ident| ident.to_string())
1852 .unwrap_or_else(|| "_".to_string());
1853 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", name, ty))
})format!("{name}: {ty}")
1854 })
1855 .collect::<Vec<_>>();
1856
1857 if missing.is_empty() {
1858 None
1859 } else {
1860 impl_inputs_span.map(|s| {
1861 let span = s.shrink_to_hi();
1862 let prefix = if impl_number_args == 0 { "" } else { ", " };
1863 let replacement = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}", missing.join(", "),
prefix))
})format!("{prefix}{}", missing.join(", "));
1864 (
1865 span,
1866 ::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!(
1867 "add the missing parameter{} from the trait",
1868 pluralize!(trait_number_args - impl_number_args)
1869 ),
1870 replacement,
1871 )
1872 })
1873 }
1874 }
1875 Ordering::Less => impl_inputs_span.and_then(|full| {
1876 let lo = if trait_number_args == 0 {
1880 full.lo()
1881 } else {
1882 impl_m_sig
1883 .decl
1884 .inputs
1885 .get(trait_number_args - 1)
1886 .map(|arg| arg.span.hi())?
1887 };
1888 let span = full.with_lo(lo);
1889 Some((
1890 span,
1891 ::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!(
1892 "remove the extra parameter{} to match the trait",
1893 pluralize!(impl_number_args - trait_number_args)
1894 ),
1895 String::new(),
1896 ))
1897 }),
1898 Ordering::Equal => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1899 };
1900 if let Some((span, msg, replacement)) = suggestion {
1901 err.span_suggestion_verbose(span, msg, replacement, Applicability::MaybeIncorrect);
1902 }
1903 }
1904
1905 return Err(err.emit_unless_delay(delay));
1906 }
1907
1908 Ok(())
1909}
1910
1911fn compare_synthetic_generics<'tcx>(
1912 tcx: TyCtxt<'tcx>,
1913 impl_m: ty::AssocItem,
1914 trait_m: ty::AssocItem,
1915 delay: bool,
1916) -> Result<(), ErrorGuaranteed> {
1917 let mut error_found = None;
1923 let impl_m_generics = tcx.generics_of(impl_m.def_id);
1924 let trait_m_generics = tcx.generics_of(trait_m.def_id);
1925 let impl_m_type_params =
1926 impl_m_generics.own_params.iter().filter_map(|param| match param.kind {
1927 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1928 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1929 });
1930 let trait_m_type_params =
1931 trait_m_generics.own_params.iter().filter_map(|param| match param.kind {
1932 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1933 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1934 });
1935 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1936 iter::zip(impl_m_type_params, trait_m_type_params)
1937 {
1938 if impl_synthetic != trait_synthetic {
1939 let impl_def_id = impl_def_id.expect_local();
1940 let impl_span = tcx.def_span(impl_def_id);
1941 let trait_span = tcx.def_span(trait_def_id);
1942 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!(
1943 tcx.dcx(),
1944 impl_span,
1945 E0643,
1946 "method `{}` has incompatible signature for trait",
1947 trait_m.name()
1948 );
1949 err.span_label(trait_span, "declaration in trait here");
1950 if impl_synthetic {
1951 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1954 try {
1955 let new_name = tcx.opt_item_name(trait_def_id)?;
1959 let trait_m = trait_m.def_id.as_local()?;
1960 let trait_m = tcx.hir_expect_trait_item(trait_m);
1961
1962 let impl_m = impl_m.def_id.as_local()?;
1963 let impl_m = tcx.hir_expect_impl_item(impl_m);
1964
1965 let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1968 let generics_span = impl_m.generics.span.substitute_dummy(new_generics_span);
1970 let new_generics =
1972 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1973
1974 err.multipart_suggestion(
1975 "try changing the `impl Trait` argument to a generic parameter",
1976 ::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![
1977 (impl_span, new_name.to_string()),
1979 (generics_span, new_generics),
1983 ],
1984 Applicability::MaybeIncorrect,
1985 );
1986 };
1987 } else {
1988 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1991 try {
1992 let impl_m = impl_m.def_id.as_local()?;
1993 let impl_m = tcx.hir_expect_impl_item(impl_m);
1994 let (sig, _) = impl_m.expect_fn();
1995 let input_tys = sig.decl.inputs;
1996
1997 struct Visitor(hir::def_id::LocalDefId);
1998 impl<'v> intravisit::Visitor<'v> for Visitor {
1999 type Result = ControlFlow<Span>;
2000 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) -> Self::Result {
2001 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
2002 && let Res::Def(DefKind::TyParam, def_id) = path.res
2003 && def_id == self.0.to_def_id()
2004 {
2005 ControlFlow::Break(ty.span)
2006 } else {
2007 intravisit::walk_ty(self, ty)
2008 }
2009 }
2010 }
2011
2012 let span = input_tys
2013 .iter()
2014 .find_map(|ty| Visitor(impl_def_id).visit_ty_unambig(ty).break_value())?;
2015
2016 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
2017 let bounds = bounds.first()?.span().to(bounds.last()?.span());
2018 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
2019
2020 err.multipart_suggestion(
2021 "try removing the generic parameter and using `impl Trait` instead",
2022 ::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![
2023 (impl_m.generics.span, String::new()),
2025 (span, format!("impl {bounds}")),
2027 ],
2028 Applicability::MaybeIncorrect,
2029 );
2030 };
2031 }
2032 error_found = Some(err.emit_unless_delay(delay));
2033 }
2034 }
2035 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
2036}
2037
2038fn compare_generic_param_kinds<'tcx>(
2064 tcx: TyCtxt<'tcx>,
2065 impl_item: ty::AssocItem,
2066 trait_item: ty::AssocItem,
2067 delay: bool,
2068) -> Result<(), ErrorGuaranteed> {
2069 {
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());
2070
2071 let ty_const_params_of = |def_id| {
2072 tcx.generics_of(def_id).own_params.iter().filter(|param| {
2073 #[allow(non_exhaustive_omitted_patterns)] match param.kind {
GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. } =>
true,
_ => false,
}matches!(
2074 param.kind,
2075 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
2076 )
2077 })
2078 };
2079
2080 for (param_impl, param_trait) in
2081 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
2082 {
2083 use GenericParamDefKind::*;
2084 if match (¶m_impl.kind, ¶m_trait.kind) {
2085 (Const { .. }, Const { .. })
2086 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
2087 {
2088 true
2089 }
2090 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
2091 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
2094 (Lifetime { .. }, _) | (_, Lifetime { .. }) => {
2095 ::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`")
2096 }
2097 } {
2098 let param_impl_span = tcx.def_span(param_impl.def_id);
2099 let param_trait_span = tcx.def_span(param_trait.def_id);
2100
2101 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!(
2102 tcx.dcx(),
2103 param_impl_span,
2104 E0053,
2105 "{} `{}` has an incompatible generic parameter for trait `{}`",
2106 impl_item.descr(),
2107 trait_item.name(),
2108 &tcx.def_path_str(tcx.parent(trait_item.def_id))
2109 );
2110
2111 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
2112 Const { .. } => {
2113 ::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!(
2114 "{} const parameter of type `{}`",
2115 prefix,
2116 tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip()
2117 )
2118 }
2119 Type { .. } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} type parameter", prefix))
})format!("{prefix} type parameter"),
2120 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!(
2121 tcx.def_span(param.def_id),
2122 "lifetime params are expected to be filtered by `ty_const_params_of`"
2123 ),
2124 };
2125
2126 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
2127 err.span_label(trait_header_span, "");
2128 err.span_label(param_trait_span, make_param_message("expected", param_trait));
2129
2130 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
2131 err.span_label(impl_header_span, "");
2132 err.span_label(param_impl_span, make_param_message("found", param_impl));
2133
2134 let reported = err.emit_unless_delay(delay);
2135 return Err(reported);
2136 }
2137 }
2138
2139 Ok(())
2140}
2141
2142fn compare_impl_const<'tcx>(
2143 tcx: TyCtxt<'tcx>,
2144 impl_const_item: ty::AssocItem,
2145 trait_const_item: ty::AssocItem,
2146 impl_trait_ref: ty::TraitRef<'tcx>,
2147) -> Result<(), ErrorGuaranteed> {
2148 compare_type_const(tcx, impl_const_item, trait_const_item)?;
2149 compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
2150 compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
2151 check_region_bounds_on_impl_item(tcx, impl_const_item, trait_const_item, false)?;
2152 compare_const_clause_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
2153}
2154
2155fn compare_type_const<'tcx>(
2156 tcx: TyCtxt<'tcx>,
2157 impl_const_item: ty::AssocItem,
2158 trait_const_item: ty::AssocItem,
2159) -> Result<(), ErrorGuaranteed> {
2160 let impl_is_type_const = tcx.is_type_const(impl_const_item.def_id);
2161 let trait_type_const_span = tcx.type_const_span(trait_const_item.def_id);
2162
2163 if let Some(trait_type_const_span) = trait_type_const_span
2164 && !impl_is_type_const
2165 {
2166 return Err(tcx
2167 .dcx()
2168 .struct_span_err(
2169 tcx.def_span(impl_const_item.def_id),
2170 "implementation of a `type const` must also be marked as `type const`",
2171 )
2172 .with_span_note(
2173 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![
2174 tcx.def_span(trait_const_item.def_id),
2175 trait_type_const_span,
2176 ]),
2177 "trait declaration of const is marked as `type const`",
2178 )
2179 .emit());
2180 }
2181 Ok(())
2182}
2183
2184#[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_clause_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_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.mk_clauses_from_iter(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);
{
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:2254",
"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(2254u32),
::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:2257",
"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(2257u32),
::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:2262",
"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(2262u32),
::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 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))]
2189fn compare_const_clause_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_clauses = tcx.clauses_of(impl_ct.def_id);
2222 let trait_ct_clauses = tcx.clauses_of(trait_ct.def_id);
2223
2224 let impl_clauses = tcx.clauses_of(impl_ct_clauses.parent.unwrap());
2227 let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
2228 hybrid_clauses.extend(
2229 trait_ct_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(clause, _)| clause),
2230 );
2231 let hybrid_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
2232
2233 let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_clauses));
2234 let param_env = traits::normalize_param_env_or_error(
2235 tcx,
2236 param_env,
2237 ObligationCause::misc(impl_ct_span, impl_ct_def_id),
2238 );
2239
2240 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2241 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2242
2243 let impl_ct_own_bounds = impl_ct_clauses.instantiate_own_identity();
2244 for (clause, span) in impl_ct_own_bounds {
2245 let cause = ObligationCause::misc(span, impl_ct_def_id);
2246 let clause = ocx.normalize(&cause, param_env, clause);
2247
2248 let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
2249 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
2250 }
2251
2252 let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
2254 debug!(?impl_ty);
2255
2256 let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
2257 debug!(?trait_ty);
2258
2259 let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
2260
2261 if let Err(terr) = err {
2262 debug!(?impl_ty, ?trait_ty);
2263
2264 let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
2266 cause.span = ty.span;
2267
2268 let mut diag = struct_span_code_err!(
2269 tcx.dcx(),
2270 cause.span,
2271 E0326,
2272 "implemented const `{}` has an incompatible type for trait",
2273 trait_ct.name()
2274 );
2275
2276 let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
2277 let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
2279 ty.span
2280 });
2281
2282 infcx.err_ctxt().note_type_err(
2283 &mut diag,
2284 &cause,
2285 trait_c_span.map(|span| (span, Cow::from("type in trait"), false)),
2286 Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2287 expected: trait_ty.into(),
2288 found: impl_ty.into(),
2289 }))),
2290 terr,
2291 false,
2292 None,
2293 );
2294 return Err(diag.emit());
2295 };
2296
2297 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2300 if let TraitErrors::HasErrors(errors) = errors {
2301 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2302 }
2303
2304 ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env, [])
2305}
2306
2307#[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(2307u32),
::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_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))]
2308fn compare_impl_ty<'tcx>(
2309 tcx: TyCtxt<'tcx>,
2310 impl_ty: ty::AssocItem,
2311 trait_ty: ty::AssocItem,
2312 impl_trait_ref: ty::TraitRef<'tcx>,
2313) -> Result<(), ErrorGuaranteed> {
2314 compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
2315 compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
2316 check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
2317 compare_type_clause_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
2318 check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
2319}
2320
2321#[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_clause_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(2323u32),
::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_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();
{
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:2351",
"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(2351u32),
::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_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));
{
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:2360",
"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(2360u32),
::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_clauses")
}> =
::tracing::__macro_support::FieldName::new("hybrid_clauses");
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_clauses)
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_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.mk_clauses_from_iter(hybrid_clauses));
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:2385",
"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(2385u32),
::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 (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))]
2324fn compare_type_clause_entailment<'tcx>(
2325 tcx: TyCtxt<'tcx>,
2326 impl_ty: ty::AssocItem,
2327 trait_ty: ty::AssocItem,
2328 impl_trait_ref: ty::TraitRef<'tcx>,
2329) -> Result<(), ErrorGuaranteed> {
2330 let impl_def_id = impl_ty.container_id(tcx);
2331 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
2332 tcx,
2333 impl_def_id,
2334 impl_trait_ref.args,
2335 );
2336
2337 let impl_ty_clauses = tcx.clauses_of(impl_ty.def_id);
2338 let trait_ty_clauses = tcx.clauses_of(trait_ty.def_id);
2339
2340 let impl_ty_own_bounds = impl_ty_clauses.instantiate_own_identity();
2341 if impl_ty_own_bounds.len() == 0 {
2343 return Ok(());
2345 }
2346
2347 let impl_ty_def_id = impl_ty.def_id.expect_local();
2351 debug!(?trait_to_impl_args);
2352
2353 let impl_clauses = tcx.clauses_of(impl_ty_clauses.parent.unwrap());
2356 let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
2357 hybrid_clauses.extend(
2358 trait_ty_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(predicate, _)| predicate),
2359 );
2360 debug!(?hybrid_clauses);
2361
2362 let impl_ty_span = tcx.def_span(impl_ty_def_id);
2363 let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
2364
2365 let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
2366 if is_conditionally_const {
2367 hybrid_clauses.extend(
2370 tcx.const_conditions(impl_ty_clauses.parent.unwrap())
2371 .instantiate_identity(tcx)
2372 .into_iter()
2373 .chain(
2374 tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
2375 )
2376 .map(|(trait_ref, _)| {
2377 trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
2378 }),
2379 );
2380 }
2381
2382 let hybrid_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
2383 let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_clauses));
2384 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
2385 debug!(caller_bounds=?param_env.caller_bounds());
2386
2387 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2388 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2389
2390 for (clause, span) in impl_ty_own_bounds {
2391 let cause = ObligationCause::misc(span, impl_ty_def_id);
2392 let clause = ocx.normalize(&cause, param_env, clause);
2393
2394 let cause = ObligationCause::new(
2395 span,
2396 impl_ty_def_id,
2397 ObligationCauseCode::CompareImplItem {
2398 impl_item_def_id: impl_ty.def_id.expect_local(),
2399 trait_item_def_id: trait_ty.def_id,
2400 kind: impl_ty.kind,
2401 },
2402 );
2403 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
2404 }
2405
2406 if is_conditionally_const {
2407 let impl_ty_own_const_conditions =
2409 tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2410 for (const_condition, span) in impl_ty_own_const_conditions {
2411 let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2412 let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2413
2414 let cause = ObligationCause::new(
2415 span,
2416 impl_ty_def_id,
2417 ObligationCauseCode::CompareImplItem {
2418 impl_item_def_id: impl_ty_def_id,
2419 trait_item_def_id: trait_ty.def_id,
2420 kind: impl_ty.kind,
2421 },
2422 );
2423 ocx.register_obligation(traits::Obligation::new(
2424 tcx,
2425 cause,
2426 param_env,
2427 const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2428 ));
2429 }
2430 }
2431
2432 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2435 if let TraitErrors::HasErrors(errors) = errors {
2436 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2437 return Err(reported);
2438 }
2439
2440 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2443}
2444
2445#[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(2458u32),
::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:2470",
"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(2470u32),
::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:2519",
"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(2519u32),
::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:2542",
"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(2542u32),
::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 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)
}
}
}#[instrument(level = "debug", skip(tcx))]
2459pub(super) fn check_type_bounds<'tcx>(
2460 tcx: TyCtxt<'tcx>,
2461 trait_ty: ty::AssocItem,
2462 impl_ty: ty::AssocItem,
2463 impl_trait_ref: ty::TraitRef<'tcx>,
2464) -> Result<(), ErrorGuaranteed> {
2465 tcx.ensure_result().coherent_trait(impl_trait_ref.def_id)?;
2468
2469 let param_env = tcx.param_env(impl_ty.def_id);
2470 debug!(?param_env);
2471
2472 let container_id = impl_ty.container_id(tcx);
2473 let impl_ty_def_id = impl_ty.def_id.expect_local();
2474 let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2475 let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2476
2477 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2478 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2479
2480 let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2484 tcx.def_span(impl_ty_def_id)
2485 } else {
2486 match tcx.hir_node_by_def_id(impl_ty_def_id) {
2487 hir::Node::TraitItem(hir::TraitItem {
2488 kind: hir::TraitItemKind::Type(_, Some(ty)),
2489 ..
2490 }) => ty.span,
2491 hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2492 item => span_bug!(
2493 tcx.def_span(impl_ty_def_id),
2494 "cannot call `check_type_bounds` on item: {item:?}",
2495 ),
2496 }
2497 };
2498 let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2499
2500 let normalize_cause = ObligationCause::new(
2501 impl_ty_span,
2502 impl_ty_def_id,
2503 ObligationCauseCode::CheckAssociatedTypeBounds {
2504 impl_item_def_id: impl_ty.def_id.expect_local(),
2505 trait_item_def_id: trait_ty.def_id,
2506 },
2507 );
2508 let mk_cause = |span: Span| {
2509 let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2510 ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2511 };
2512
2513 let mut obligations: Vec<_> = util::elaborate(
2514 tcx,
2515 tcx.explicit_item_bounds(trait_ty.def_id)
2516 .iter_instantiated_copied(tcx, rebased_args)
2517 .map(Unnormalized::skip_norm_wip)
2518 .map(|(concrete_ty_bound, span)| {
2519 debug!(?concrete_ty_bound);
2520 traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2521 }),
2522 )
2523 .collect();
2524
2525 if tcx.is_conditionally_const(impl_ty_def_id) {
2527 obligations.extend(util::elaborate(
2528 tcx,
2529 tcx.explicit_implied_const_bounds(trait_ty.def_id)
2530 .iter_instantiated_copied(tcx, rebased_args)
2531 .map(Unnormalized::skip_norm_wip)
2532 .map(|(c, span)| {
2533 traits::Obligation::new(
2534 tcx,
2535 mk_cause(span),
2536 param_env,
2537 c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2538 )
2539 }),
2540 ));
2541 }
2542 debug!(item_bounds=?obligations);
2543
2544 let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2549 for obligation in &mut obligations {
2550 match ocx.deeply_normalize(
2551 &normalize_cause,
2552 normalize_param_env,
2553 Unnormalized::new_wip(obligation.predicate),
2554 ) {
2555 Ok(pred) => obligation.predicate = pred,
2556 Err(e) => {
2557 return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2558 }
2559 }
2560 }
2561
2562 ocx.register_obligations(obligations);
2565 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2566 if let TraitErrors::HasErrors(errors) = errors {
2567 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2568 return Err(reported);
2569 }
2570
2571 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2574}
2575
2576fn param_env_with_gat_bounds<'tcx>(
2624 tcx: TyCtxt<'tcx>,
2625 impl_ty: ty::AssocItem,
2626 impl_trait_ref: ty::TraitRef<'tcx>,
2627) -> ty::ParamEnv<'tcx> {
2628 let param_env = tcx.param_env(impl_ty.def_id);
2629 let container_id = impl_ty.container_id(tcx);
2630 let mut clauses = param_env.caller_bounds().to_vec();
2631
2632 let impl_tys_to_install = match impl_ty.kind {
2637 ty::AssocKind::Type {
2638 data:
2639 ty::AssocTypeData::Rpitit(
2640 ty::ImplTraitInTraitData::Impl { fn_def_id }
2641 | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2642 ),
2643 } => tcx
2644 .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2645 .iter()
2646 .map(|def_id| tcx.associated_item(*def_id))
2647 .collect(),
2648 _ => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[impl_ty]))vec![impl_ty],
2649 };
2650
2651 for impl_ty in impl_tys_to_install {
2652 let trait_ty = match impl_ty.container {
2653 ty::AssocContainer::InherentImpl => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
2654 ty::AssocContainer::Trait => impl_ty,
2655 ty::AssocContainer::TraitImpl(Err(_)) => continue,
2656 ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
2657 tcx.associated_item(trait_item_def_id)
2658 }
2659 };
2660
2661 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind<'tcx>; 8]> =
2662 smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2663 let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2665 .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2666 GenericParamDefKind::Type { .. } => {
2667 let kind = ty::BoundTyKind::Param(param.def_id);
2668 let bound_var = ty::BoundVariableKind::Ty(kind);
2669 bound_vars.push(bound_var);
2670 Ty::new_bound(
2671 tcx,
2672 ty::INNERMOST,
2673 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2674 )
2675 .into()
2676 }
2677 GenericParamDefKind::Lifetime => {
2678 let kind = ty::BoundRegionKind::Named(param.def_id);
2679 let bound_var = ty::BoundVariableKind::Region(kind);
2680 bound_vars.push(bound_var);
2681 ty::Region::new_bound(
2682 tcx,
2683 ty::INNERMOST,
2684 ty::BoundRegion {
2685 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2686 kind,
2687 },
2688 )
2689 .into()
2690 }
2691 GenericParamDefKind::Const { .. } => {
2692 let bound_var = ty::BoundVariableKind::Const;
2693 bound_vars.push(bound_var);
2694 ty::Const::new_bound(
2695 tcx,
2696 ty::INNERMOST,
2697 ty::BoundConst::new(ty::BoundVar::from_usize(bound_vars.len() - 1)),
2698 )
2699 .into()
2700 }
2701 });
2702 let normalize_impl_ty =
2712 tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args).skip_norm_wip();
2713 let rebased_args =
2714 normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2715 let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2716
2717 match normalize_impl_ty.kind() {
2718 &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
2719 if def_id == trait_ty.def_id && args == rebased_args =>
2720 {
2721 }
2727 _ => clauses.push(
2728 ty::Binder::bind_with_vars(
2729 ty::ProjectionPredicate {
2730 projection_term: ty::AliasTerm::new_from_def_id(
2731 tcx,
2732 trait_ty.def_id,
2733 rebased_args,
2734 ),
2735 term: normalize_impl_ty.into(),
2736 },
2737 bound_vars,
2738 )
2739 .upcast(tcx),
2740 ),
2741 };
2742 }
2743
2744 ty::ParamEnv::new(tcx.mk_clauses(&clauses))
2745}
2746
2747fn try_report_async_mismatch<'tcx>(
2750 tcx: TyCtxt<'tcx>,
2751 infcx: &InferCtxt<'tcx>,
2752 errors: &[FulfillmentError<'tcx>],
2753 trait_m: ty::AssocItem,
2754 impl_m: ty::AssocItem,
2755 impl_sig: ty::FnSig<'tcx>,
2756) -> Result<(), ErrorGuaranteed> {
2757 if !tcx.asyncness(trait_m.def_id).is_async() {
2758 return Ok(());
2759 }
2760
2761 let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id: async_future_def_id }, .. }) =
2762 *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2763 else {
2764 ::rustc_middle::util::bug::bug_fmt(format_args!("expected `async fn` to return an RPITIT"));bug!("expected `async fn` to return an RPITIT");
2765 };
2766
2767 for error in errors {
2768 if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2769 && def_id == async_future_def_id
2770 && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2771 && let Some(proj) = proj.no_bound_vars()
2772 && infcx.can_eq(
2773 error.root_obligation.param_env,
2774 proj.term.expect_type(),
2775 impl_sig.output(),
2776 )
2777 {
2778 return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2781 span: tcx.def_span(impl_m.def_id),
2782 method_name: tcx.item_ident(impl_m.def_id),
2783 trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
2784 }));
2785 }
2786 }
2787
2788 Ok(())
2789}