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