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