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