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(ty::Projection, proj) = ty.kind()
824 && self.cx().is_impl_trait_in_trait(proj.def_id)
825 {
826 if let Some((ty, _)) = self.types.get(&proj.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(proj.def_id, (infer_ty, proj.args));
836 for (pred, pred_span) in self
838 .cx()
839 .explicit_item_bounds(proj.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(proj.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::Opaque, opaque_ty) = self.ty.kind() {
926 self.tcx.def_span(opaque_ty.def_id)
927 } else {
928 self.return_span
929 };
930 self.tcx
931 .dcx()
932 .struct_span_err(
933 return_span,
934 "return type captures more lifetimes than trait definition",
935 )
936 .with_span_label(self.tcx.def_span(def_id), "this lifetime was captured")
937 .with_span_note(
938 self.tcx.def_span(self.def_id),
939 "hidden type must only reference lifetimes captured by this impl trait",
940 )
941 .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))
942 .emit()
943 }
944 None => {
945 self.tcx.dcx().bug("should've been able to remap region");
950 }
951 };
952 return Err(guar);
953 };
954
955 Ok(ty::Region::new_early_param(
956 self.tcx,
957 ty::EarlyParamRegion {
958 name: e.name,
959 index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32,
960 },
961 ))
962 }
963}
964
965fn get_self_string<'tcx, P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> String
968where
969 P: Fn(Ty<'tcx>) -> bool,
970{
971 if is_self_ty(self_arg_ty) {
972 "self".to_owned()
973 } else if let ty::Ref(_, ty, mutbl) = self_arg_ty.kind()
974 && is_self_ty(*ty)
975 {
976 match mutbl {
977 hir::Mutability::Not => "&self".to_owned(),
978 hir::Mutability::Mut => "&mut self".to_owned(),
979 }
980 } else {
981 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("self: {0}", self_arg_ty))
})format!("self: {self_arg_ty}")
982 }
983}
984
985fn report_trait_method_mismatch<'tcx>(
986 infcx: &InferCtxt<'tcx>,
987 mut cause: ObligationCause<'tcx>,
988 param_env: ty::ParamEnv<'tcx>,
989 terr: TypeError<'tcx>,
990 (trait_m, trait_sig): (ty::AssocItem, ty::FnSig<'tcx>),
991 (impl_m, impl_sig): (ty::AssocItem, ty::FnSig<'tcx>),
992 impl_trait_ref: ty::TraitRef<'tcx>,
993) -> ErrorGuaranteed {
994 let tcx = infcx.tcx;
995 let (impl_err_span, trait_err_span) =
996 extract_spans_for_error_reporting(infcx, terr, &cause, impl_m, trait_m);
997
998 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!(
999 tcx.dcx(),
1000 impl_err_span,
1001 E0053,
1002 "method `{}` has an incompatible type for trait",
1003 trait_m.name()
1004 );
1005 match &terr {
1006 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
1007 if trait_m.is_method() =>
1008 {
1009 let ty = trait_sig.inputs()[0];
1010 let sugg = get_self_string(ty, |ty| ty == impl_trait_ref.self_ty());
1011
1012 let (sig, body) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1016 let span = tcx
1017 .hir_body_param_idents(body)
1018 .zip(sig.decl.inputs.iter())
1019 .map(|(param_ident, ty)| {
1020 if let Some(param_ident) = param_ident {
1021 param_ident.span.to(ty.span)
1022 } else {
1023 ty.span
1024 }
1025 })
1026 .next()
1027 .unwrap_or(impl_err_span);
1028
1029 diag.span_suggestion_verbose(
1030 span,
1031 "change the self-receiver type to match the trait",
1032 sugg,
1033 Applicability::MachineApplicable,
1034 );
1035 }
1036 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
1037 if trait_sig.inputs().len() == *i {
1038 if let ImplItemKind::Fn(sig, _) =
1041 &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).kind
1042 && !sig.header.asyncness.is_async()
1043 {
1044 let msg = "change the output type to match the trait";
1045 let ap = Applicability::MachineApplicable;
1046 match sig.decl.output {
1047 hir::FnRetTy::DefaultReturn(sp) => {
1048 let sugg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" -> {0}", trait_sig.output()))
})format!(" -> {}", trait_sig.output());
1049 diag.span_suggestion_verbose(sp, msg, sugg, ap);
1050 }
1051 hir::FnRetTy::Return(hir_ty) => {
1052 let sugg = trait_sig.output();
1053 diag.span_suggestion_verbose(hir_ty.span, msg, sugg, ap);
1054 }
1055 };
1056 };
1057 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
1058 diag.span_suggestion_verbose(
1059 impl_err_span,
1060 "change the parameter type to match the trait",
1061 trait_ty,
1062 Applicability::MachineApplicable,
1063 );
1064 }
1065 }
1066 _ => {}
1067 }
1068
1069 cause.span = impl_err_span;
1070 infcx.err_ctxt().note_type_err(
1071 &mut diag,
1072 &cause,
1073 trait_err_span.map(|sp| (sp, Cow::from("type in trait"), false)),
1074 Some(param_env.and(infer::ValuePairs::PolySigs(ExpectedFound {
1075 expected: ty::Binder::dummy(trait_sig),
1076 found: ty::Binder::dummy(impl_sig),
1077 }))),
1078 terr,
1079 false,
1080 None,
1081 );
1082
1083 diag.emit()
1084}
1085
1086fn check_region_bounds_on_impl_item<'tcx>(
1087 tcx: TyCtxt<'tcx>,
1088 impl_m: ty::AssocItem,
1089 trait_m: ty::AssocItem,
1090 delay: bool,
1091) -> Result<(), ErrorGuaranteed> {
1092 let impl_generics = tcx.generics_of(impl_m.def_id);
1093 let impl_params = impl_generics.own_counts().lifetimes;
1094
1095 let trait_generics = tcx.generics_of(trait_m.def_id);
1096 let trait_params = trait_generics.own_counts().lifetimes;
1097
1098 let Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span }) =
1099 check_number_of_early_bound_regions(
1100 tcx,
1101 impl_m.def_id.expect_local(),
1102 trait_m.def_id,
1103 impl_generics,
1104 impl_params,
1105 trait_generics,
1106 trait_params,
1107 )
1108 else {
1109 return Ok(());
1110 };
1111
1112 if !delay && let Some(guar) = check_region_late_boundedness(tcx, impl_m, trait_m) {
1113 return Err(guar);
1114 }
1115
1116 let reported = tcx
1117 .dcx()
1118 .create_err(LifetimesOrBoundsMismatchOnTrait {
1119 span,
1120 item_kind: impl_m.descr(),
1121 ident: impl_m.ident(tcx),
1122 generics_span,
1123 bounds_span,
1124 where_span,
1125 })
1126 .emit_unless_delay(delay);
1127
1128 Err(reported)
1129}
1130
1131pub(super) struct CheckNumberOfEarlyBoundRegionsError {
1132 pub(super) span: Span,
1133 pub(super) generics_span: Span,
1134 pub(super) bounds_span: Vec<Span>,
1135 pub(super) where_span: Option<Span>,
1136}
1137
1138pub(super) fn check_number_of_early_bound_regions<'tcx>(
1139 tcx: TyCtxt<'tcx>,
1140 impl_def_id: LocalDefId,
1141 trait_def_id: DefId,
1142 impl_generics: &Generics,
1143 impl_params: usize,
1144 trait_generics: &Generics,
1145 trait_params: usize,
1146) -> Result<(), CheckNumberOfEarlyBoundRegionsError> {
1147 {
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:1147",
"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(1147u32),
::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);
1148
1149 if trait_params == impl_params {
1159 return Ok(());
1160 }
1161
1162 let span = tcx
1163 .hir_get_generics(impl_def_id)
1164 .expect("expected impl item to have generics or else we can't compare them")
1165 .span;
1166
1167 let mut generics_span = tcx.def_span(trait_def_id);
1168 let mut bounds_span = ::alloc::vec::Vec::new()vec![];
1169 let mut where_span = None;
1170
1171 if let Some(trait_node) = tcx.hir_get_if_local(trait_def_id)
1172 && let Some(trait_generics) = trait_node.generics()
1173 {
1174 generics_span = trait_generics.span;
1175 for p in trait_generics.predicates {
1178 match p.kind {
1179 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1180 bounds,
1181 ..
1182 })
1183 | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1184 bounds,
1185 ..
1186 }) => {
1187 for b in *bounds {
1188 if let hir::GenericBound::Outlives(lt) = b {
1189 bounds_span.push(lt.ident.span);
1190 }
1191 }
1192 }
1193 _ => {}
1194 }
1195 }
1196 if let Some(impl_node) = tcx.hir_get_if_local(impl_def_id.into())
1197 && let Some(impl_generics) = impl_node.generics()
1198 {
1199 let mut impl_bounds = 0;
1200 for p in impl_generics.predicates {
1201 match p.kind {
1202 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1203 bounds,
1204 ..
1205 })
1206 | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1207 bounds,
1208 ..
1209 }) => {
1210 for b in *bounds {
1211 if let hir::GenericBound::Outlives(_) = b {
1212 impl_bounds += 1;
1213 }
1214 }
1215 }
1216 _ => {}
1217 }
1218 }
1219 if impl_bounds == bounds_span.len() {
1220 bounds_span = ::alloc::vec::Vec::new()vec![];
1221 } else if impl_generics.has_where_clause_predicates {
1222 where_span = Some(impl_generics.where_clause_span);
1223 }
1224 }
1225 }
1226
1227 Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span })
1228}
1229
1230#[allow(unused)]
1231enum LateEarlyMismatch<'tcx> {
1232 EarlyInImpl(DefId, DefId, ty::Region<'tcx>),
1233 LateInImpl(DefId, DefId, ty::Region<'tcx>),
1234}
1235
1236fn check_region_late_boundedness<'tcx>(
1237 tcx: TyCtxt<'tcx>,
1238 impl_m: ty::AssocItem,
1239 trait_m: ty::AssocItem,
1240) -> Option<ErrorGuaranteed> {
1241 if !impl_m.is_fn() {
1242 return None;
1243 }
1244
1245 let (infcx, param_env) = tcx
1246 .infer_ctxt()
1247 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, impl_m.def_id));
1248
1249 let impl_m_args = infcx.fresh_args_for_item(DUMMY_SP, impl_m.def_id);
1250 let impl_m_sig = tcx.fn_sig(impl_m.def_id).instantiate(tcx, impl_m_args);
1251 let impl_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, impl_m_sig);
1252
1253 let trait_m_args = infcx.fresh_args_for_item(DUMMY_SP, trait_m.def_id);
1254 let trait_m_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_args);
1255 let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_m_sig);
1256
1257 let ocx = ObligationCtxt::new(&infcx);
1258
1259 let Ok(()) = ocx.eq(
1264 &ObligationCause::dummy(),
1265 param_env,
1266 ty::Binder::dummy(trait_m_sig),
1267 ty::Binder::dummy(impl_m_sig),
1268 ) else {
1269 return None;
1270 };
1271
1272 let errors = ocx.try_evaluate_obligations();
1273 if !errors.is_empty() {
1274 return None;
1275 }
1276
1277 let mut mismatched = ::alloc::vec::Vec::new()vec![];
1278
1279 let impl_generics = tcx.generics_of(impl_m.def_id);
1280 for (id_arg, arg) in
1281 std::iter::zip(ty::GenericArgs::identity_for_item(tcx, impl_m.def_id), impl_m_args)
1282 {
1283 if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1284 && let ty::ReVar(vid) = r.kind()
1285 && let r = infcx
1286 .inner
1287 .borrow_mut()
1288 .unwrap_region_constraints()
1289 .opportunistic_resolve_var(tcx, vid)
1290 && let ty::ReLateParam(ty::LateParamRegion {
1291 kind: ty::LateParamRegionKind::Named(trait_param_def_id),
1292 ..
1293 }) = r.kind()
1294 && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1295 {
1296 mismatched.push(LateEarlyMismatch::EarlyInImpl(
1297 impl_generics.region_param(ebr, tcx).def_id,
1298 trait_param_def_id,
1299 id_arg.expect_region(),
1300 ));
1301 }
1302 }
1303
1304 let trait_generics = tcx.generics_of(trait_m.def_id);
1305 for (id_arg, arg) in
1306 std::iter::zip(ty::GenericArgs::identity_for_item(tcx, trait_m.def_id), trait_m_args)
1307 {
1308 if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1309 && let ty::ReVar(vid) = r.kind()
1310 && let r = infcx
1311 .inner
1312 .borrow_mut()
1313 .unwrap_region_constraints()
1314 .opportunistic_resolve_var(tcx, vid)
1315 && let ty::ReLateParam(ty::LateParamRegion {
1316 kind: ty::LateParamRegionKind::Named(impl_param_def_id),
1317 ..
1318 }) = r.kind()
1319 && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1320 {
1321 mismatched.push(LateEarlyMismatch::LateInImpl(
1322 impl_param_def_id,
1323 trait_generics.region_param(ebr, tcx).def_id,
1324 id_arg.expect_region(),
1325 ));
1326 }
1327 }
1328
1329 if mismatched.is_empty() {
1330 return None;
1331 }
1332
1333 let spans: Vec<_> = mismatched
1334 .iter()
1335 .map(|param| {
1336 let (LateEarlyMismatch::EarlyInImpl(impl_param_def_id, ..)
1337 | LateEarlyMismatch::LateInImpl(impl_param_def_id, ..)) = *param;
1338 tcx.def_span(impl_param_def_id)
1339 })
1340 .collect();
1341
1342 let mut diag = tcx
1343 .dcx()
1344 .struct_span_err(spans, "lifetime parameters do not match the trait definition")
1345 .with_note("lifetime parameters differ in whether they are early- or late-bound")
1346 .with_code(E0195);
1347 for mismatch in mismatched {
1348 match mismatch {
1349 LateEarlyMismatch::EarlyInImpl(
1350 impl_param_def_id,
1351 trait_param_def_id,
1352 early_bound_region,
1353 ) => {
1354 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![
1355 tcx.def_span(impl_param_def_id),
1356 tcx.def_span(trait_param_def_id),
1357 ]);
1358 multispan
1359 .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1360 multispan
1361 .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1362 multispan.push_span_label(
1363 tcx.def_span(impl_param_def_id),
1364 ::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)),
1365 );
1366 multispan.push_span_label(
1367 tcx.def_span(trait_param_def_id),
1368 ::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)),
1369 );
1370 if let Some(span) =
1371 find_region_in_predicates(tcx, impl_m.def_id, early_bound_region)
1372 {
1373 multispan.push_span_label(
1374 span,
1375 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
tcx.item_name(impl_param_def_id)))
})format!(
1376 "this lifetime bound makes `{}` early-bound",
1377 tcx.item_name(impl_param_def_id)
1378 ),
1379 );
1380 }
1381 diag.span_note(
1382 multispan,
1383 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
tcx.item_name(impl_param_def_id)))
})format!(
1384 "`{}` differs between the trait and impl",
1385 tcx.item_name(impl_param_def_id)
1386 ),
1387 );
1388 }
1389 LateEarlyMismatch::LateInImpl(
1390 impl_param_def_id,
1391 trait_param_def_id,
1392 early_bound_region,
1393 ) => {
1394 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![
1395 tcx.def_span(impl_param_def_id),
1396 tcx.def_span(trait_param_def_id),
1397 ]);
1398 multispan
1399 .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1400 multispan
1401 .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1402 multispan.push_span_label(
1403 tcx.def_span(impl_param_def_id),
1404 ::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)),
1405 );
1406 multispan.push_span_label(
1407 tcx.def_span(trait_param_def_id),
1408 ::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)),
1409 );
1410 if let Some(span) =
1411 find_region_in_predicates(tcx, trait_m.def_id, early_bound_region)
1412 {
1413 multispan.push_span_label(
1414 span,
1415 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
tcx.item_name(trait_param_def_id)))
})format!(
1416 "this lifetime bound makes `{}` early-bound",
1417 tcx.item_name(trait_param_def_id)
1418 ),
1419 );
1420 }
1421 diag.span_note(
1422 multispan,
1423 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
tcx.item_name(impl_param_def_id)))
})format!(
1424 "`{}` differs between the trait and impl",
1425 tcx.item_name(impl_param_def_id)
1426 ),
1427 );
1428 }
1429 }
1430 }
1431
1432 Some(diag.emit())
1433}
1434
1435fn find_region_in_predicates<'tcx>(
1436 tcx: TyCtxt<'tcx>,
1437 def_id: DefId,
1438 early_bound_region: ty::Region<'tcx>,
1439) -> Option<Span> {
1440 for (pred, span) in tcx.explicit_predicates_of(def_id).instantiate_identity(tcx) {
1441 if pred.visit_with(&mut FindRegion(early_bound_region)).is_break() {
1442 return Some(span);
1443 }
1444 }
1445
1446 struct FindRegion<'tcx>(ty::Region<'tcx>);
1447 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindRegion<'tcx> {
1448 type Result = ControlFlow<()>;
1449 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
1450 if r == self.0 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
1451 }
1452 }
1453
1454 None
1455}
1456
1457#[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(1457u32),
::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))]
1458fn extract_spans_for_error_reporting<'tcx>(
1459 infcx: &infer::InferCtxt<'tcx>,
1460 terr: TypeError<'_>,
1461 cause: &ObligationCause<'tcx>,
1462 impl_m: ty::AssocItem,
1463 trait_m: ty::AssocItem,
1464) -> (Span, Option<Span>) {
1465 let tcx = infcx.tcx;
1466 let mut impl_args = {
1467 let (sig, _) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1468 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1469 };
1470
1471 let trait_args = trait_m.def_id.as_local().map(|def_id| {
1472 let (sig, _) = tcx.hir_expect_trait_item(def_id).expect_fn();
1473 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1474 });
1475
1476 match terr {
1477 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1478 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1479 }
1480 _ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
1481 }
1482}
1483
1484fn compare_self_type<'tcx>(
1485 tcx: TyCtxt<'tcx>,
1486 impl_m: ty::AssocItem,
1487 trait_m: ty::AssocItem,
1488 impl_trait_ref: ty::TraitRef<'tcx>,
1489 delay: bool,
1490) -> Result<(), ErrorGuaranteed> {
1491 let self_string = |method: ty::AssocItem| {
1500 let untransformed_self_ty = match method.container {
1501 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1502 impl_trait_ref.self_ty()
1503 }
1504 ty::AssocContainer::Trait => tcx.types.self_param,
1505 };
1506 let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().input(0);
1507 let (infcx, param_env) = tcx
1508 .infer_ctxt()
1509 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, method.def_id));
1510 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1511 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
1512 get_self_string(self_arg_ty, can_eq_self)
1513 };
1514
1515 match (trait_m.is_method(), impl_m.is_method()) {
1516 (false, false) | (true, true) => {}
1517
1518 (false, true) => {
1519 let self_descr = self_string(impl_m);
1520 let impl_m_span = tcx.def_span(impl_m.def_id);
1521 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!(
1522 tcx.dcx(),
1523 impl_m_span,
1524 E0185,
1525 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1526 trait_m.name(),
1527 self_descr
1528 );
1529 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"));
1530 if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1531 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}`"));
1532 } else {
1533 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1534 }
1535 return Err(err.emit_unless_delay(delay));
1536 }
1537
1538 (true, false) => {
1539 let self_descr = self_string(trait_m);
1540 let impl_m_span = tcx.def_span(impl_m.def_id);
1541 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!(
1542 tcx.dcx(),
1543 impl_m_span,
1544 E0186,
1545 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1546 trait_m.name(),
1547 self_descr
1548 );
1549 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"));
1550 if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1551 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"));
1552 } else {
1553 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1554 }
1555
1556 return Err(err.emit_unless_delay(delay));
1557 }
1558 }
1559
1560 Ok(())
1561}
1562
1563fn compare_number_of_generics<'tcx>(
1585 tcx: TyCtxt<'tcx>,
1586 impl_: ty::AssocItem,
1587 trait_: ty::AssocItem,
1588 delay: bool,
1589) -> Result<(), ErrorGuaranteed> {
1590 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1591 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1592
1593 if (trait_own_counts.types + trait_own_counts.consts)
1597 == (impl_own_counts.types + impl_own_counts.consts)
1598 {
1599 return Ok(());
1600 }
1601
1602 if trait_.is_impl_trait_in_trait() {
1607 tcx.dcx()
1610 .bug("errors comparing numbers of generics of trait/impl functions were not emitted");
1611 }
1612
1613 let matchings = [
1614 ("type", trait_own_counts.types, impl_own_counts.types),
1615 ("const", trait_own_counts.consts, impl_own_counts.consts),
1616 ];
1617
1618 let item_kind = impl_.descr();
1619
1620 let mut err_occurred = None;
1621 for (kind, trait_count, impl_count) in matchings {
1622 if impl_count != trait_count {
1623 let arg_spans = |item: &ty::AssocItem, generics: &hir::Generics<'_>| {
1624 let mut spans = generics
1625 .params
1626 .iter()
1627 .filter(|p| match p.kind {
1628 hir::GenericParamKind::Lifetime {
1629 kind: hir::LifetimeParamKind::Elided(_),
1630 } => {
1631 !item.is_fn()
1634 }
1635 _ => true,
1636 })
1637 .map(|p| p.span)
1638 .collect::<Vec<Span>>();
1639 if spans.is_empty() {
1640 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]
1641 }
1642 spans
1643 };
1644 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1645 let trait_item = tcx.hir_expect_trait_item(def_id);
1646 let arg_spans: Vec<Span> = arg_spans(&trait_, trait_item.generics);
1647 let impl_trait_spans: Vec<Span> = trait_item
1648 .generics
1649 .params
1650 .iter()
1651 .filter_map(|p| match p.kind {
1652 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1653 _ => None,
1654 })
1655 .collect();
1656 (Some(arg_spans), impl_trait_spans)
1657 } else {
1658 let trait_span = tcx.hir_span_if_local(trait_.def_id);
1659 (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![])
1660 };
1661
1662 let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
1663 let impl_item_impl_trait_spans: Vec<Span> = impl_item
1664 .generics
1665 .params
1666 .iter()
1667 .filter_map(|p| match p.kind {
1668 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1669 _ => None,
1670 })
1671 .collect();
1672 let spans = arg_spans(&impl_, impl_item.generics);
1673 let span = spans.first().copied();
1674
1675 let mut err = tcx.dcx().struct_span_err(
1676 spans,
1677 ::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!(
1678 "{} `{}` has {} {kind} parameter{} but its trait \
1679 declaration has {} {kind} parameter{}",
1680 item_kind,
1681 trait_.name(),
1682 impl_count,
1683 pluralize!(impl_count),
1684 trait_count,
1685 pluralize!(trait_count),
1686 kind = kind,
1687 ),
1688 );
1689 err.code(E0049);
1690
1691 let msg =
1692 ::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),);
1693 if let Some(spans) = trait_spans {
1694 let mut spans = spans.iter();
1695 if let Some(span) = spans.next() {
1696 err.span_label(*span, msg);
1697 }
1698 for span in spans {
1699 err.span_label(*span, "");
1700 }
1701 } else {
1702 err.span_label(tcx.def_span(trait_.def_id), msg);
1703 }
1704
1705 if let Some(span) = span {
1706 err.span_label(
1707 span,
1708 ::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),),
1709 );
1710 }
1711
1712 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1713 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1714 }
1715
1716 let reported = err.emit_unless_delay(delay);
1717 err_occurred = Some(reported);
1718 }
1719 }
1720
1721 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1722}
1723
1724fn compare_number_of_method_arguments<'tcx>(
1725 tcx: TyCtxt<'tcx>,
1726 impl_m: ty::AssocItem,
1727 trait_m: ty::AssocItem,
1728 delay: bool,
1729) -> Result<(), ErrorGuaranteed> {
1730 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1731 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1732 let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
1733 let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1734
1735 if trait_number_args != impl_number_args {
1736 let trait_span = trait_m
1737 .def_id
1738 .as_local()
1739 .and_then(|def_id| {
1740 let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
1741 let pos = trait_number_args.saturating_sub(1);
1742 trait_m_sig.decl.inputs.get(pos).map(|arg| {
1743 if pos == 0 {
1744 arg.span
1745 } else {
1746 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1747 }
1748 })
1749 })
1750 .or_else(|| tcx.hir_span_if_local(trait_m.def_id));
1751
1752 let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1753 let pos = impl_number_args.saturating_sub(1);
1754 let impl_span = impl_m_sig
1755 .decl
1756 .inputs
1757 .get(pos)
1758 .map(|arg| {
1759 if pos == 0 {
1760 arg.span
1761 } else {
1762 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1763 }
1764 })
1765 .unwrap_or_else(|| tcx.def_span(impl_m.def_id));
1766
1767 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!(
1768 tcx.dcx(),
1769 impl_span,
1770 E0050,
1771 "method `{}` has {} but the declaration in trait `{}` has {}",
1772 trait_m.name(),
1773 potentially_plural_count(impl_number_args, "parameter"),
1774 tcx.def_path_str(trait_m.def_id),
1775 trait_number_args
1776 );
1777
1778 if let Some(trait_span) = trait_span {
1779 err.span_label(
1780 trait_span,
1781 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait requires {0}",
potentially_plural_count(trait_number_args, "parameter")))
})format!(
1782 "trait requires {}",
1783 potentially_plural_count(trait_number_args, "parameter")
1784 ),
1785 );
1786 } else {
1787 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1788 }
1789
1790 err.span_label(
1791 impl_span,
1792 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}, found {1}",
potentially_plural_count(trait_number_args, "parameter"),
impl_number_args))
})format!(
1793 "expected {}, found {}",
1794 potentially_plural_count(trait_number_args, "parameter"),
1795 impl_number_args
1796 ),
1797 );
1798
1799 if !trait_m.def_id.is_local() {
1801 let trait_sig = tcx.fn_sig(trait_m.def_id);
1802 let trait_arg_idents = tcx.fn_arg_idents(trait_m.def_id);
1803 let sm = tcx.sess.source_map();
1804 let impl_inputs_span = if let (Some(first), Some(last)) =
1808 (impl_m_sig.decl.inputs.first(), impl_m_sig.decl.inputs.last())
1809 {
1810 let arg_idents = tcx.fn_arg_idents(impl_m.def_id);
1814 let first_lo = arg_idents
1815 .get(0)
1816 .and_then(|id| id.map(|id| id.span.lo()))
1817 .unwrap_or(first.span.lo());
1818 Some(impl_m_sig.span.with_lo(first_lo).with_hi(last.span.hi()))
1819 } else {
1820 sm.span_to_snippet(impl_m_sig.span).ok().and_then(|s| {
1825 let right_paren = s.as_bytes().iter().rposition(|&b| b == b')')?;
1826 let pos = impl_m_sig.span.lo() + BytePos(right_paren as u32);
1827 Some(impl_m_sig.span.with_lo(pos).with_hi(pos))
1828 })
1829 };
1830 let suggestion = match trait_number_args.cmp(&impl_number_args) {
1831 Ordering::Greater => {
1832 let trait_inputs = trait_sig.skip_binder().inputs().skip_binder();
1836 let missing = trait_inputs
1837 .iter()
1838 .enumerate()
1839 .skip(impl_number_args)
1840 .map(|(idx, ty)| {
1841 let name = trait_arg_idents
1842 .get(idx)
1843 .and_then(|ident| *ident)
1844 .map(|ident| ident.to_string())
1845 .unwrap_or_else(|| "_".to_string());
1846 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", name, ty))
})format!("{name}: {ty}")
1847 })
1848 .collect::<Vec<_>>();
1849
1850 if missing.is_empty() {
1851 None
1852 } else {
1853 impl_inputs_span.map(|s| {
1854 let span = s.shrink_to_hi();
1855 let prefix = if impl_number_args == 0 { "" } else { ", " };
1856 let replacement = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}", missing.join(", "),
prefix))
})format!("{prefix}{}", missing.join(", "));
1857 (
1858 span,
1859 ::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!(
1860 "add the missing parameter{} from the trait",
1861 pluralize!(trait_number_args - impl_number_args)
1862 ),
1863 replacement,
1864 )
1865 })
1866 }
1867 }
1868 Ordering::Less => impl_inputs_span.and_then(|full| {
1869 let lo = if trait_number_args == 0 {
1873 full.lo()
1874 } else {
1875 impl_m_sig
1876 .decl
1877 .inputs
1878 .get(trait_number_args - 1)
1879 .map(|arg| arg.span.hi())?
1880 };
1881 let span = full.with_lo(lo);
1882 Some((
1883 span,
1884 ::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!(
1885 "remove the extra parameter{} to match the trait",
1886 pluralize!(impl_number_args - trait_number_args)
1887 ),
1888 String::new(),
1889 ))
1890 }),
1891 Ordering::Equal => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1892 };
1893 if let Some((span, msg, replacement)) = suggestion {
1894 err.span_suggestion_verbose(span, msg, replacement, Applicability::MaybeIncorrect);
1895 }
1896 }
1897
1898 return Err(err.emit_unless_delay(delay));
1899 }
1900
1901 Ok(())
1902}
1903
1904fn compare_synthetic_generics<'tcx>(
1905 tcx: TyCtxt<'tcx>,
1906 impl_m: ty::AssocItem,
1907 trait_m: ty::AssocItem,
1908 delay: bool,
1909) -> Result<(), ErrorGuaranteed> {
1910 let mut error_found = None;
1916 let impl_m_generics = tcx.generics_of(impl_m.def_id);
1917 let trait_m_generics = tcx.generics_of(trait_m.def_id);
1918 let impl_m_type_params =
1919 impl_m_generics.own_params.iter().filter_map(|param| match param.kind {
1920 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1921 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1922 });
1923 let trait_m_type_params =
1924 trait_m_generics.own_params.iter().filter_map(|param| match param.kind {
1925 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1926 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1927 });
1928 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1929 iter::zip(impl_m_type_params, trait_m_type_params)
1930 {
1931 if impl_synthetic != trait_synthetic {
1932 let impl_def_id = impl_def_id.expect_local();
1933 let impl_span = tcx.def_span(impl_def_id);
1934 let trait_span = tcx.def_span(trait_def_id);
1935 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!(
1936 tcx.dcx(),
1937 impl_span,
1938 E0643,
1939 "method `{}` has incompatible signature for trait",
1940 trait_m.name()
1941 );
1942 err.span_label(trait_span, "declaration in trait here");
1943 if impl_synthetic {
1944 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1947 try {
1948 let new_name = tcx.opt_item_name(trait_def_id)?;
1952 let trait_m = trait_m.def_id.as_local()?;
1953 let trait_m = tcx.hir_expect_trait_item(trait_m);
1954
1955 let impl_m = impl_m.def_id.as_local()?;
1956 let impl_m = tcx.hir_expect_impl_item(impl_m);
1957
1958 let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1961 let generics_span = impl_m.generics.span.substitute_dummy(new_generics_span);
1963 let new_generics =
1965 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1966
1967 err.multipart_suggestion(
1968 "try changing the `impl Trait` argument to a generic parameter",
1969 ::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![
1970 (impl_span, new_name.to_string()),
1972 (generics_span, new_generics),
1976 ],
1977 Applicability::MaybeIncorrect,
1978 );
1979 };
1980 } else {
1981 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1984 try {
1985 let impl_m = impl_m.def_id.as_local()?;
1986 let impl_m = tcx.hir_expect_impl_item(impl_m);
1987 let (sig, _) = impl_m.expect_fn();
1988 let input_tys = sig.decl.inputs;
1989
1990 struct Visitor(hir::def_id::LocalDefId);
1991 impl<'v> intravisit::Visitor<'v> for Visitor {
1992 type Result = ControlFlow<Span>;
1993 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) -> Self::Result {
1994 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
1995 && let Res::Def(DefKind::TyParam, def_id) = path.res
1996 && def_id == self.0.to_def_id()
1997 {
1998 ControlFlow::Break(ty.span)
1999 } else {
2000 intravisit::walk_ty(self, ty)
2001 }
2002 }
2003 }
2004
2005 let span = input_tys
2006 .iter()
2007 .find_map(|ty| Visitor(impl_def_id).visit_ty_unambig(ty).break_value())?;
2008
2009 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
2010 let bounds = bounds.first()?.span().to(bounds.last()?.span());
2011 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
2012
2013 err.multipart_suggestion(
2014 "try removing the generic parameter and using `impl Trait` instead",
2015 ::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![
2016 (impl_m.generics.span, String::new()),
2018 (span, format!("impl {bounds}")),
2020 ],
2021 Applicability::MaybeIncorrect,
2022 );
2023 };
2024 }
2025 error_found = Some(err.emit_unless_delay(delay));
2026 }
2027 }
2028 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
2029}
2030
2031fn compare_generic_param_kinds<'tcx>(
2057 tcx: TyCtxt<'tcx>,
2058 impl_item: ty::AssocItem,
2059 trait_item: ty::AssocItem,
2060 delay: bool,
2061) -> Result<(), ErrorGuaranteed> {
2062 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());
2063
2064 let ty_const_params_of = |def_id| {
2065 tcx.generics_of(def_id).own_params.iter().filter(|param| {
2066 #[allow(non_exhaustive_omitted_patterns)] match param.kind {
GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. } =>
true,
_ => false,
}matches!(
2067 param.kind,
2068 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
2069 )
2070 })
2071 };
2072
2073 for (param_impl, param_trait) in
2074 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
2075 {
2076 use GenericParamDefKind::*;
2077 if match (¶m_impl.kind, ¶m_trait.kind) {
2078 (Const { .. }, Const { .. })
2079 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
2080 {
2081 true
2082 }
2083 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
2084 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
2087 (Lifetime { .. }, _) | (_, Lifetime { .. }) => {
2088 ::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`")
2089 }
2090 } {
2091 let param_impl_span = tcx.def_span(param_impl.def_id);
2092 let param_trait_span = tcx.def_span(param_trait.def_id);
2093
2094 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!(
2095 tcx.dcx(),
2096 param_impl_span,
2097 E0053,
2098 "{} `{}` has an incompatible generic parameter for trait `{}`",
2099 impl_item.descr(),
2100 trait_item.name(),
2101 &tcx.def_path_str(tcx.parent(trait_item.def_id))
2102 );
2103
2104 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
2105 Const { .. } => {
2106 ::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!(
2107 "{} const parameter of type `{}`",
2108 prefix,
2109 tcx.type_of(param.def_id).instantiate_identity()
2110 )
2111 }
2112 Type { .. } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} type parameter", prefix))
})format!("{prefix} type parameter"),
2113 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!(
2114 tcx.def_span(param.def_id),
2115 "lifetime params are expected to be filtered by `ty_const_params_of`"
2116 ),
2117 };
2118
2119 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
2120 err.span_label(trait_header_span, "");
2121 err.span_label(param_trait_span, make_param_message("expected", param_trait));
2122
2123 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
2124 err.span_label(impl_header_span, "");
2125 err.span_label(param_impl_span, make_param_message("found", param_impl));
2126
2127 let reported = err.emit_unless_delay(delay);
2128 return Err(reported);
2129 }
2130 }
2131
2132 Ok(())
2133}
2134
2135fn compare_impl_const<'tcx>(
2136 tcx: TyCtxt<'tcx>,
2137 impl_const_item: ty::AssocItem,
2138 trait_const_item: ty::AssocItem,
2139 impl_trait_ref: ty::TraitRef<'tcx>,
2140) -> Result<(), ErrorGuaranteed> {
2141 compare_type_const(tcx, impl_const_item, trait_const_item)?;
2142 compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
2143 compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
2144 check_region_bounds_on_impl_item(tcx, impl_const_item, trait_const_item, false)?;
2145 compare_const_predicate_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
2146}
2147
2148fn compare_type_const<'tcx>(
2149 tcx: TyCtxt<'tcx>,
2150 impl_const_item: ty::AssocItem,
2151 trait_const_item: ty::AssocItem,
2152) -> Result<(), ErrorGuaranteed> {
2153 let impl_is_type_const = tcx.is_type_const(impl_const_item.def_id);
2154 let trait_type_const_span = tcx.type_const_span(trait_const_item.def_id);
2155
2156 if let Some(trait_type_const_span) = trait_type_const_span
2157 && !impl_is_type_const
2158 {
2159 return Err(tcx
2160 .dcx()
2161 .struct_span_err(
2162 tcx.def_span(impl_const_item.def_id),
2163 "implementation of a `type const` must also be marked as `type const`",
2164 )
2165 .with_span_note(
2166 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![
2167 tcx.def_span(trait_const_item.def_id),
2168 trait_type_const_span,
2169 ]),
2170 "trait declaration of const is marked as `type const`",
2171 )
2172 .emit());
2173 }
2174 Ok(())
2175}
2176
2177#[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(2180u32),
::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:2247",
"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(2247u32),
::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:2250",
"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(2250u32),
::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:2255",
"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(2255u32),
::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))]
2181fn compare_const_predicate_entailment<'tcx>(
2182 tcx: TyCtxt<'tcx>,
2183 impl_ct: ty::AssocItem,
2184 trait_ct: ty::AssocItem,
2185 impl_trait_ref: ty::TraitRef<'tcx>,
2186) -> Result<(), ErrorGuaranteed> {
2187 let impl_ct_def_id = impl_ct.def_id.expect_local();
2188 let impl_ct_span = tcx.def_span(impl_ct_def_id);
2189
2190 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id).rebase_onto(
2196 tcx,
2197 impl_ct.container_id(tcx),
2198 impl_trait_ref.args,
2199 );
2200
2201 let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
2204
2205 let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
2206 let code = ObligationCauseCode::CompareImplItem {
2207 impl_item_def_id: impl_ct_def_id,
2208 trait_item_def_id: trait_ct.def_id,
2209 kind: impl_ct.kind,
2210 };
2211 let mut cause = ObligationCause::new(impl_ct_span, impl_ct_def_id, code.clone());
2212
2213 let impl_ct_predicates = tcx.predicates_of(impl_ct.def_id);
2214 let trait_ct_predicates = tcx.predicates_of(trait_ct.def_id);
2215
2216 let impl_predicates = tcx.predicates_of(impl_ct_predicates.parent.unwrap());
2219 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2220 hybrid_preds.extend(
2221 trait_ct_predicates
2222 .instantiate_own(tcx, trait_to_impl_args)
2223 .map(|(predicate, _)| predicate),
2224 );
2225
2226 let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
2227 let param_env = traits::normalize_param_env_or_error(
2228 tcx,
2229 param_env,
2230 ObligationCause::misc(impl_ct_span, impl_ct_def_id),
2231 );
2232
2233 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2234 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2235
2236 let impl_ct_own_bounds = impl_ct_predicates.instantiate_own_identity();
2237 for (predicate, span) in impl_ct_own_bounds {
2238 let cause = ObligationCause::misc(span, impl_ct_def_id);
2239 let predicate = ocx.normalize(&cause, param_env, predicate);
2240
2241 let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
2242 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2243 }
2244
2245 let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
2247 debug!(?impl_ty);
2248
2249 let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
2250 debug!(?trait_ty);
2251
2252 let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
2253
2254 if let Err(terr) = err {
2255 debug!(?impl_ty, ?trait_ty);
2256
2257 let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
2259 cause.span = ty.span;
2260
2261 let mut diag = struct_span_code_err!(
2262 tcx.dcx(),
2263 cause.span,
2264 E0326,
2265 "implemented const `{}` has an incompatible type for trait",
2266 trait_ct.name()
2267 );
2268
2269 let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
2270 let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
2272 ty.span
2273 });
2274
2275 infcx.err_ctxt().note_type_err(
2276 &mut diag,
2277 &cause,
2278 trait_c_span.map(|span| (span, Cow::from("type in trait"), false)),
2279 Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2280 expected: trait_ty.into(),
2281 found: impl_ty.into(),
2282 }))),
2283 terr,
2284 false,
2285 None,
2286 );
2287 return Err(diag.emit());
2288 };
2289
2290 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2293 if !errors.is_empty() {
2294 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2295 }
2296
2297 ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env, [])
2298}
2299
2300#[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(2300u32),
::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))]
2301fn compare_impl_ty<'tcx>(
2302 tcx: TyCtxt<'tcx>,
2303 impl_ty: ty::AssocItem,
2304 trait_ty: ty::AssocItem,
2305 impl_trait_ref: ty::TraitRef<'tcx>,
2306) -> Result<(), ErrorGuaranteed> {
2307 compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
2308 compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
2309 check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
2310 compare_type_predicate_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
2311 check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
2312}
2313
2314#[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(2316u32),
::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:2344",
"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(2344u32),
::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:2355",
"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(2355u32),
::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:2379",
"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(2379u32),
::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))]
2317fn compare_type_predicate_entailment<'tcx>(
2318 tcx: TyCtxt<'tcx>,
2319 impl_ty: ty::AssocItem,
2320 trait_ty: ty::AssocItem,
2321 impl_trait_ref: ty::TraitRef<'tcx>,
2322) -> Result<(), ErrorGuaranteed> {
2323 let impl_def_id = impl_ty.container_id(tcx);
2324 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
2325 tcx,
2326 impl_def_id,
2327 impl_trait_ref.args,
2328 );
2329
2330 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
2331 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
2332
2333 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own_identity();
2334 if impl_ty_own_bounds.len() == 0 {
2336 return Ok(());
2338 }
2339
2340 let impl_ty_def_id = impl_ty.def_id.expect_local();
2344 debug!(?trait_to_impl_args);
2345
2346 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
2349 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2350 hybrid_preds.extend(
2351 trait_ty_predicates
2352 .instantiate_own(tcx, trait_to_impl_args)
2353 .map(|(predicate, _)| predicate),
2354 );
2355 debug!(?hybrid_preds);
2356
2357 let impl_ty_span = tcx.def_span(impl_ty_def_id);
2358 let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
2359
2360 let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
2361 if is_conditionally_const {
2362 hybrid_preds.extend(
2365 tcx.const_conditions(impl_ty_predicates.parent.unwrap())
2366 .instantiate_identity(tcx)
2367 .into_iter()
2368 .chain(
2369 tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
2370 )
2371 .map(|(trait_ref, _)| {
2372 trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
2373 }),
2374 );
2375 }
2376
2377 let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds));
2378 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
2379 debug!(caller_bounds=?param_env.caller_bounds());
2380
2381 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2382 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2383
2384 for (predicate, span) in impl_ty_own_bounds {
2385 let cause = ObligationCause::misc(span, impl_ty_def_id);
2386 let predicate = ocx.normalize(&cause, param_env, predicate);
2387
2388 let cause = ObligationCause::new(
2389 span,
2390 impl_ty_def_id,
2391 ObligationCauseCode::CompareImplItem {
2392 impl_item_def_id: impl_ty.def_id.expect_local(),
2393 trait_item_def_id: trait_ty.def_id,
2394 kind: impl_ty.kind,
2395 },
2396 );
2397 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2398 }
2399
2400 if is_conditionally_const {
2401 let impl_ty_own_const_conditions =
2403 tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2404 for (const_condition, span) in impl_ty_own_const_conditions {
2405 let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2406 let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2407
2408 let cause = ObligationCause::new(
2409 span,
2410 impl_ty_def_id,
2411 ObligationCauseCode::CompareImplItem {
2412 impl_item_def_id: impl_ty_def_id,
2413 trait_item_def_id: trait_ty.def_id,
2414 kind: impl_ty.kind,
2415 },
2416 );
2417 ocx.register_obligation(traits::Obligation::new(
2418 tcx,
2419 cause,
2420 param_env,
2421 const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2422 ));
2423 }
2424 }
2425
2426 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2429 if !errors.is_empty() {
2430 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2431 return Err(reported);
2432 }
2433
2434 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2437}
2438
2439#[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(2452u32),
::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:2464",
"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(2464u32),
::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:2511",
"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(2511u32),
::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:2534",
"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(2534u32),
::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))]
2453pub(super) fn check_type_bounds<'tcx>(
2454 tcx: TyCtxt<'tcx>,
2455 trait_ty: ty::AssocItem,
2456 impl_ty: ty::AssocItem,
2457 impl_trait_ref: ty::TraitRef<'tcx>,
2458) -> Result<(), ErrorGuaranteed> {
2459 tcx.ensure_result().coherent_trait(impl_trait_ref.def_id)?;
2462
2463 let param_env = tcx.param_env(impl_ty.def_id);
2464 debug!(?param_env);
2465
2466 let container_id = impl_ty.container_id(tcx);
2467 let impl_ty_def_id = impl_ty.def_id.expect_local();
2468 let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2469 let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2470
2471 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2472 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2473
2474 let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2478 tcx.def_span(impl_ty_def_id)
2479 } else {
2480 match tcx.hir_node_by_def_id(impl_ty_def_id) {
2481 hir::Node::TraitItem(hir::TraitItem {
2482 kind: hir::TraitItemKind::Type(_, Some(ty)),
2483 ..
2484 }) => ty.span,
2485 hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2486 item => span_bug!(
2487 tcx.def_span(impl_ty_def_id),
2488 "cannot call `check_type_bounds` on item: {item:?}",
2489 ),
2490 }
2491 };
2492 let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2493
2494 let normalize_cause = ObligationCause::new(
2495 impl_ty_span,
2496 impl_ty_def_id,
2497 ObligationCauseCode::CheckAssociatedTypeBounds {
2498 impl_item_def_id: impl_ty.def_id.expect_local(),
2499 trait_item_def_id: trait_ty.def_id,
2500 },
2501 );
2502 let mk_cause = |span: Span| {
2503 let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2504 ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2505 };
2506
2507 let mut obligations: Vec<_> = util::elaborate(
2508 tcx,
2509 tcx.explicit_item_bounds(trait_ty.def_id).iter_instantiated_copied(tcx, rebased_args).map(
2510 |(concrete_ty_bound, span)| {
2511 debug!(?concrete_ty_bound);
2512 traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2513 },
2514 ),
2515 )
2516 .collect();
2517
2518 if tcx.is_conditionally_const(impl_ty_def_id) {
2520 obligations.extend(util::elaborate(
2521 tcx,
2522 tcx.explicit_implied_const_bounds(trait_ty.def_id)
2523 .iter_instantiated_copied(tcx, rebased_args)
2524 .map(|(c, span)| {
2525 traits::Obligation::new(
2526 tcx,
2527 mk_cause(span),
2528 param_env,
2529 c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2530 )
2531 }),
2532 ));
2533 }
2534 debug!(item_bounds=?obligations);
2535
2536 let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2541 for obligation in &mut obligations {
2542 match ocx.deeply_normalize(&normalize_cause, normalize_param_env, obligation.predicate) {
2543 Ok(pred) => obligation.predicate = pred,
2544 Err(e) => {
2545 return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2546 }
2547 }
2548 }
2549
2550 ocx.register_obligations(obligations);
2553 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2554 if !errors.is_empty() {
2555 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2556 return Err(reported);
2557 }
2558
2559 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2562}
2563
2564fn param_env_with_gat_bounds<'tcx>(
2612 tcx: TyCtxt<'tcx>,
2613 impl_ty: ty::AssocItem,
2614 impl_trait_ref: ty::TraitRef<'tcx>,
2615) -> ty::ParamEnv<'tcx> {
2616 let param_env = tcx.param_env(impl_ty.def_id);
2617 let container_id = impl_ty.container_id(tcx);
2618 let mut predicates = param_env.caller_bounds().to_vec();
2619
2620 let impl_tys_to_install = match impl_ty.kind {
2625 ty::AssocKind::Type {
2626 data:
2627 ty::AssocTypeData::Rpitit(
2628 ty::ImplTraitInTraitData::Impl { fn_def_id }
2629 | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2630 ),
2631 } => tcx
2632 .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2633 .iter()
2634 .map(|def_id| tcx.associated_item(*def_id))
2635 .collect(),
2636 _ => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[impl_ty]))vec![impl_ty],
2637 };
2638
2639 for impl_ty in impl_tys_to_install {
2640 let trait_ty = match impl_ty.container {
2641 ty::AssocContainer::InherentImpl => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
2642 ty::AssocContainer::Trait => impl_ty,
2643 ty::AssocContainer::TraitImpl(Err(_)) => continue,
2644 ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
2645 tcx.associated_item(trait_item_def_id)
2646 }
2647 };
2648
2649 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind<'tcx>; 8]> =
2650 smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2651 let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2653 .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2654 GenericParamDefKind::Type { .. } => {
2655 let kind = ty::BoundTyKind::Param(param.def_id);
2656 let bound_var = ty::BoundVariableKind::Ty(kind);
2657 bound_vars.push(bound_var);
2658 Ty::new_bound(
2659 tcx,
2660 ty::INNERMOST,
2661 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2662 )
2663 .into()
2664 }
2665 GenericParamDefKind::Lifetime => {
2666 let kind = ty::BoundRegionKind::Named(param.def_id);
2667 let bound_var = ty::BoundVariableKind::Region(kind);
2668 bound_vars.push(bound_var);
2669 ty::Region::new_bound(
2670 tcx,
2671 ty::INNERMOST,
2672 ty::BoundRegion {
2673 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2674 kind,
2675 },
2676 )
2677 .into()
2678 }
2679 GenericParamDefKind::Const { .. } => {
2680 let bound_var = ty::BoundVariableKind::Const;
2681 bound_vars.push(bound_var);
2682 ty::Const::new_bound(
2683 tcx,
2684 ty::INNERMOST,
2685 ty::BoundConst::new(ty::BoundVar::from_usize(bound_vars.len() - 1)),
2686 )
2687 .into()
2688 }
2689 });
2690 let normalize_impl_ty =
2700 tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args);
2701 let rebased_args =
2702 normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2703 let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2704
2705 match normalize_impl_ty.kind() {
2706 ty::Alias(ty::Projection, proj)
2707 if proj.def_id == trait_ty.def_id && proj.args == rebased_args =>
2708 {
2709 }
2715 _ => predicates.push(
2716 ty::Binder::bind_with_vars(
2717 ty::ProjectionPredicate {
2718 projection_term: ty::AliasTerm::new_from_args(
2719 tcx,
2720 trait_ty.def_id,
2721 rebased_args,
2722 ),
2723 term: normalize_impl_ty.into(),
2724 },
2725 bound_vars,
2726 )
2727 .upcast(tcx),
2728 ),
2729 };
2730 }
2731
2732 ty::ParamEnv::new(tcx.mk_clauses(&predicates))
2733}
2734
2735fn try_report_async_mismatch<'tcx>(
2738 tcx: TyCtxt<'tcx>,
2739 infcx: &InferCtxt<'tcx>,
2740 errors: &[FulfillmentError<'tcx>],
2741 trait_m: ty::AssocItem,
2742 impl_m: ty::AssocItem,
2743 impl_sig: ty::FnSig<'tcx>,
2744) -> Result<(), ErrorGuaranteed> {
2745 if !tcx.asyncness(trait_m.def_id).is_async() {
2746 return Ok(());
2747 }
2748
2749 let ty::Alias(ty::Projection, ty::AliasTy { def_id: async_future_def_id, .. }) =
2750 *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2751 else {
2752 ::rustc_middle::util::bug::bug_fmt(format_args!("expected `async fn` to return an RPITIT"));bug!("expected `async fn` to return an RPITIT");
2753 };
2754
2755 for error in errors {
2756 if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2757 && def_id == async_future_def_id
2758 && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2759 && let Some(proj) = proj.no_bound_vars()
2760 && infcx.can_eq(
2761 error.root_obligation.param_env,
2762 proj.term.expect_type(),
2763 impl_sig.output(),
2764 )
2765 {
2766 return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2769 span: tcx.def_span(impl_m.def_id),
2770 method_name: tcx.item_ident(impl_m.def_id),
2771 trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
2772 }));
2773 }
2774 }
2775
2776 Ok(())
2777}