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::errors::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture};
33
34pub(super) mod refine;
35
36pub(super) fn compare_impl_item(
38 tcx: TyCtxt<'_>,
39 impl_item_def_id: LocalDefId,
40) -> Result<(), ErrorGuaranteed> {
41 let impl_item = tcx.associated_item(impl_item_def_id);
42 let trait_item = tcx.associated_item(impl_item.expect_trait_impl()?);
43 let impl_trait_ref =
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 }
1208 if let Some(impl_node) = tcx.hir_get_if_local(impl_def_id.into())
1209 && let Some(impl_generics) = impl_node.generics()
1210 {
1211 let mut impl_bounds = 0;
1212 for p in impl_generics.predicates {
1213 match p.kind {
1214 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1215 bounds,
1216 ..
1217 })
1218 | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1219 bounds,
1220 ..
1221 }) => {
1222 for b in *bounds {
1223 if let hir::GenericBound::Outlives(_) = b {
1224 impl_bounds += 1;
1225 }
1226 }
1227 }
1228 _ => {}
1229 }
1230 }
1231 if impl_bounds == bounds_span.len() {
1232 bounds_span = ::alloc::vec::Vec::new()vec![];
1233 } else if impl_generics.has_where_clause_predicates {
1234 where_span = Some(impl_generics.where_clause_span);
1235 }
1236 }
1237 }
1238
1239 Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span })
1240}
1241
1242#[allow(unused)]
1243enum LateEarlyMismatch<'tcx> {
1244 EarlyInImpl(DefId, DefId, ty::Region<'tcx>),
1245 LateInImpl(DefId, DefId, ty::Region<'tcx>),
1246}
1247
1248fn check_region_late_boundedness<'tcx>(
1249 tcx: TyCtxt<'tcx>,
1250 impl_m: ty::AssocItem,
1251 trait_m: ty::AssocItem,
1252) -> Option<ErrorGuaranteed> {
1253 if !impl_m.is_fn() {
1254 return None;
1255 }
1256
1257 let (infcx, param_env) = tcx
1258 .infer_ctxt()
1259 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, impl_m.def_id));
1260
1261 let impl_m_args = infcx.fresh_args_for_item(DUMMY_SP, impl_m.def_id);
1262 let impl_m_sig = tcx.fn_sig(impl_m.def_id).instantiate(tcx, impl_m_args).skip_norm_wip();
1263 let impl_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, impl_m_sig);
1264
1265 let trait_m_args = infcx.fresh_args_for_item(DUMMY_SP, trait_m.def_id);
1266 let trait_m_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_args).skip_norm_wip();
1267 let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_m_sig);
1268
1269 let ocx = ObligationCtxt::new(&infcx);
1270
1271 let Ok(()) = ocx.eq(
1276 &ObligationCause::dummy(),
1277 param_env,
1278 ty::Binder::dummy(trait_m_sig),
1279 ty::Binder::dummy(impl_m_sig),
1280 ) else {
1281 return None;
1282 };
1283
1284 let errors = ocx.try_evaluate_obligations();
1285 if !errors.is_empty() {
1286 return None;
1287 }
1288
1289 let mut mismatched = ::alloc::vec::Vec::new()vec![];
1290
1291 let impl_generics = tcx.generics_of(impl_m.def_id);
1292 for (id_arg, arg) in
1293 std::iter::zip(ty::GenericArgs::identity_for_item(tcx, impl_m.def_id), impl_m_args)
1294 {
1295 if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1296 && let ty::ReVar(vid) = r.kind()
1297 && let r = infcx
1298 .inner
1299 .borrow_mut()
1300 .unwrap_region_constraints()
1301 .opportunistic_resolve_var(tcx, vid)
1302 && let ty::ReLateParam(ty::LateParamRegion {
1303 kind: ty::LateParamRegionKind::Named(trait_param_def_id),
1304 ..
1305 }) = r.kind()
1306 && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1307 {
1308 mismatched.push(LateEarlyMismatch::EarlyInImpl(
1309 impl_generics.region_param(ebr, tcx).def_id,
1310 trait_param_def_id,
1311 id_arg.expect_region(),
1312 ));
1313 }
1314 }
1315
1316 let trait_generics = tcx.generics_of(trait_m.def_id);
1317 for (id_arg, arg) in
1318 std::iter::zip(ty::GenericArgs::identity_for_item(tcx, trait_m.def_id), trait_m_args)
1319 {
1320 if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1321 && let ty::ReVar(vid) = r.kind()
1322 && let r = infcx
1323 .inner
1324 .borrow_mut()
1325 .unwrap_region_constraints()
1326 .opportunistic_resolve_var(tcx, vid)
1327 && let ty::ReLateParam(ty::LateParamRegion {
1328 kind: ty::LateParamRegionKind::Named(impl_param_def_id),
1329 ..
1330 }) = r.kind()
1331 && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1332 {
1333 mismatched.push(LateEarlyMismatch::LateInImpl(
1334 impl_param_def_id,
1335 trait_generics.region_param(ebr, tcx).def_id,
1336 id_arg.expect_region(),
1337 ));
1338 }
1339 }
1340
1341 if mismatched.is_empty() {
1342 return None;
1343 }
1344
1345 let spans: Vec<_> = mismatched
1346 .iter()
1347 .map(|param| {
1348 let (LateEarlyMismatch::EarlyInImpl(impl_param_def_id, ..)
1349 | LateEarlyMismatch::LateInImpl(impl_param_def_id, ..)) = *param;
1350 tcx.def_span(impl_param_def_id)
1351 })
1352 .collect();
1353
1354 let mut diag = tcx
1355 .dcx()
1356 .struct_span_err(spans, "lifetime parameters do not match the trait definition")
1357 .with_note("lifetime parameters differ in whether they are early- or late-bound")
1358 .with_code(E0195);
1359 for mismatch in mismatched {
1360 match mismatch {
1361 LateEarlyMismatch::EarlyInImpl(
1362 impl_param_def_id,
1363 trait_param_def_id,
1364 early_bound_region,
1365 ) => {
1366 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![
1367 tcx.def_span(impl_param_def_id),
1368 tcx.def_span(trait_param_def_id),
1369 ]);
1370 multispan
1371 .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1372 multispan
1373 .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1374 multispan.push_span_label(
1375 tcx.def_span(impl_param_def_id),
1376 ::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)),
1377 );
1378 multispan.push_span_label(
1379 tcx.def_span(trait_param_def_id),
1380 ::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)),
1381 );
1382 if let Some(span) =
1383 find_region_in_predicates(tcx, impl_m.def_id, early_bound_region)
1384 {
1385 multispan.push_span_label(
1386 span,
1387 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
tcx.item_name(impl_param_def_id)))
})format!(
1388 "this lifetime bound makes `{}` early-bound",
1389 tcx.item_name(impl_param_def_id)
1390 ),
1391 );
1392 }
1393 diag.span_note(
1394 multispan,
1395 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
tcx.item_name(impl_param_def_id)))
})format!(
1396 "`{}` differs between the trait and impl",
1397 tcx.item_name(impl_param_def_id)
1398 ),
1399 );
1400 }
1401 LateEarlyMismatch::LateInImpl(
1402 impl_param_def_id,
1403 trait_param_def_id,
1404 early_bound_region,
1405 ) => {
1406 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![
1407 tcx.def_span(impl_param_def_id),
1408 tcx.def_span(trait_param_def_id),
1409 ]);
1410 multispan
1411 .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1412 multispan
1413 .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1414 multispan.push_span_label(
1415 tcx.def_span(impl_param_def_id),
1416 ::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)),
1417 );
1418 multispan.push_span_label(
1419 tcx.def_span(trait_param_def_id),
1420 ::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)),
1421 );
1422 if let Some(span) =
1423 find_region_in_predicates(tcx, trait_m.def_id, early_bound_region)
1424 {
1425 multispan.push_span_label(
1426 span,
1427 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
tcx.item_name(trait_param_def_id)))
})format!(
1428 "this lifetime bound makes `{}` early-bound",
1429 tcx.item_name(trait_param_def_id)
1430 ),
1431 );
1432 }
1433 diag.span_note(
1434 multispan,
1435 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
tcx.item_name(impl_param_def_id)))
})format!(
1436 "`{}` differs between the trait and impl",
1437 tcx.item_name(impl_param_def_id)
1438 ),
1439 );
1440 }
1441 }
1442 }
1443
1444 Some(diag.emit())
1445}
1446
1447fn find_region_in_predicates<'tcx>(
1448 tcx: TyCtxt<'tcx>,
1449 def_id: DefId,
1450 early_bound_region: ty::Region<'tcx>,
1451) -> Option<Span> {
1452 for (pred, span) in tcx.explicit_predicates_of(def_id).instantiate_identity(tcx) {
1453 if pred.skip_norm_wip().visit_with(&mut FindRegion(early_bound_region)).is_break() {
1454 return Some(span);
1455 }
1456 }
1457
1458 struct FindRegion<'tcx>(ty::Region<'tcx>);
1459 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindRegion<'tcx> {
1460 type Result = ControlFlow<()>;
1461 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
1462 if r == self.0 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
1463 }
1464 }
1465
1466 None
1467}
1468
1469#[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(1469u32),
::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))]
1470fn extract_spans_for_error_reporting<'tcx>(
1471 infcx: &infer::InferCtxt<'tcx>,
1472 terr: TypeError<'_>,
1473 cause: &ObligationCause<'tcx>,
1474 impl_m: ty::AssocItem,
1475 trait_m: ty::AssocItem,
1476) -> (Span, Option<Span>) {
1477 let tcx = infcx.tcx;
1478 let mut impl_args = {
1479 let (sig, _) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1480 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1481 };
1482
1483 let trait_args = trait_m.def_id.as_local().map(|def_id| {
1484 let (sig, _) = tcx.hir_expect_trait_item(def_id).expect_fn();
1485 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1486 });
1487
1488 match terr {
1489 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1490 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1491 }
1492 _ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
1493 }
1494}
1495
1496fn compare_self_type<'tcx>(
1497 tcx: TyCtxt<'tcx>,
1498 impl_m: ty::AssocItem,
1499 trait_m: ty::AssocItem,
1500 impl_trait_ref: ty::TraitRef<'tcx>,
1501 delay: bool,
1502) -> Result<(), ErrorGuaranteed> {
1503 let self_string = |method: ty::AssocItem| {
1512 let untransformed_self_ty = match method.container {
1513 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1514 impl_trait_ref.self_ty()
1515 }
1516 ty::AssocContainer::Trait => tcx.types.self_param,
1517 };
1518 let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip().input(0);
1519 let (infcx, param_env) = tcx
1520 .infer_ctxt()
1521 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, method.def_id));
1522 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1523 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
1524 get_self_string(self_arg_ty, can_eq_self)
1525 };
1526
1527 match (trait_m.is_method(), impl_m.is_method()) {
1528 (false, false) | (true, true) => {}
1529
1530 (false, true) => {
1531 let self_descr = self_string(impl_m);
1532 let impl_m_span = tcx.def_span(impl_m.def_id);
1533 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!(
1534 tcx.dcx(),
1535 impl_m_span,
1536 E0185,
1537 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1538 trait_m.name(),
1539 self_descr
1540 );
1541 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"));
1542 if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1543 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}`"));
1544 } else {
1545 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1546 }
1547 return Err(err.emit_unless_delay(delay));
1548 }
1549
1550 (true, false) => {
1551 let self_descr = self_string(trait_m);
1552 let impl_m_span = tcx.def_span(impl_m.def_id);
1553 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!(
1554 tcx.dcx(),
1555 impl_m_span,
1556 E0186,
1557 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1558 trait_m.name(),
1559 self_descr
1560 );
1561 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"));
1562 if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1563 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"));
1564 } else {
1565 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1566 }
1567
1568 return Err(err.emit_unless_delay(delay));
1569 }
1570 }
1571
1572 Ok(())
1573}
1574
1575fn compare_number_of_generics<'tcx>(
1597 tcx: TyCtxt<'tcx>,
1598 impl_: ty::AssocItem,
1599 trait_: ty::AssocItem,
1600 delay: bool,
1601) -> Result<(), ErrorGuaranteed> {
1602 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1603 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1604
1605 if (trait_own_counts.types + trait_own_counts.consts)
1609 == (impl_own_counts.types + impl_own_counts.consts)
1610 {
1611 return Ok(());
1612 }
1613
1614 if trait_.is_impl_trait_in_trait() {
1619 tcx.dcx()
1622 .bug("errors comparing numbers of generics of trait/impl functions were not emitted");
1623 }
1624
1625 let matchings = [
1626 ("type", trait_own_counts.types, impl_own_counts.types),
1627 ("const", trait_own_counts.consts, impl_own_counts.consts),
1628 ];
1629
1630 let item_kind = impl_.descr();
1631
1632 let mut err_occurred = None;
1633 for (kind, trait_count, impl_count) in matchings {
1634 if impl_count != trait_count {
1635 let arg_spans = |item: &ty::AssocItem, generics: &hir::Generics<'_>| {
1636 let mut spans = generics
1637 .params
1638 .iter()
1639 .filter(|p| match p.kind {
1640 hir::GenericParamKind::Lifetime {
1641 kind: hir::LifetimeParamKind::Elided(_),
1642 } => {
1643 !item.is_fn()
1646 }
1647 _ => true,
1648 })
1649 .map(|p| p.span)
1650 .collect::<Vec<Span>>();
1651 if spans.is_empty() {
1652 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]
1653 }
1654 spans
1655 };
1656 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1657 let trait_item = tcx.hir_expect_trait_item(def_id);
1658 let arg_spans: Vec<Span> = arg_spans(&trait_, trait_item.generics);
1659 let impl_trait_spans: Vec<Span> = trait_item
1660 .generics
1661 .params
1662 .iter()
1663 .filter_map(|p| match p.kind {
1664 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1665 _ => None,
1666 })
1667 .collect();
1668 (Some(arg_spans), impl_trait_spans)
1669 } else {
1670 let trait_span = tcx.hir_span_if_local(trait_.def_id);
1671 (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![])
1672 };
1673
1674 let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
1675 let impl_item_impl_trait_spans: Vec<Span> = impl_item
1676 .generics
1677 .params
1678 .iter()
1679 .filter_map(|p| match p.kind {
1680 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1681 _ => None,
1682 })
1683 .collect();
1684 let spans = arg_spans(&impl_, impl_item.generics);
1685 let span = spans.first().copied();
1686
1687 let mut err = tcx.dcx().struct_span_err(
1688 spans,
1689 ::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!(
1690 "{} `{}` has {} {kind} parameter{} but its trait \
1691 declaration has {} {kind} parameter{}",
1692 item_kind,
1693 trait_.name(),
1694 impl_count,
1695 pluralize!(impl_count),
1696 trait_count,
1697 pluralize!(trait_count),
1698 kind = kind,
1699 ),
1700 );
1701 err.code(E0049);
1702
1703 let msg =
1704 ::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),);
1705 if let Some(spans) = trait_spans {
1706 let mut spans = spans.iter();
1707 if let Some(span) = spans.next() {
1708 err.span_label(*span, msg);
1709 }
1710 for span in spans {
1711 err.span_label(*span, "");
1712 }
1713 } else {
1714 err.span_label(tcx.def_span(trait_.def_id), msg);
1715 }
1716
1717 if let Some(span) = span {
1718 err.span_label(
1719 span,
1720 ::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),),
1721 );
1722 }
1723
1724 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1725 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1726 }
1727
1728 let reported = err.emit_unless_delay(delay);
1729 err_occurred = Some(reported);
1730 }
1731 }
1732
1733 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1734}
1735
1736fn compare_number_of_method_arguments<'tcx>(
1737 tcx: TyCtxt<'tcx>,
1738 impl_m: ty::AssocItem,
1739 trait_m: ty::AssocItem,
1740 delay: bool,
1741) -> Result<(), ErrorGuaranteed> {
1742 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1743 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1744 let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
1745 let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1746
1747 if trait_number_args != impl_number_args {
1748 let trait_span = trait_m
1749 .def_id
1750 .as_local()
1751 .and_then(|def_id| {
1752 let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
1753 let pos = trait_number_args.saturating_sub(1);
1754 trait_m_sig.decl.inputs.get(pos).map(|arg| {
1755 if pos == 0 {
1756 arg.span
1757 } else {
1758 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1759 }
1760 })
1761 })
1762 .or_else(|| tcx.hir_span_if_local(trait_m.def_id));
1763
1764 let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1765 let pos = impl_number_args.saturating_sub(1);
1766 let impl_span = impl_m_sig
1767 .decl
1768 .inputs
1769 .get(pos)
1770 .map(|arg| {
1771 if pos == 0 {
1772 arg.span
1773 } else {
1774 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1775 }
1776 })
1777 .unwrap_or_else(|| tcx.def_span(impl_m.def_id));
1778
1779 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!(
1780 tcx.dcx(),
1781 impl_span,
1782 E0050,
1783 "method `{}` has {} but the declaration in trait `{}` has {}",
1784 trait_m.name(),
1785 potentially_plural_count(impl_number_args, "parameter"),
1786 tcx.def_path_str(trait_m.def_id),
1787 trait_number_args
1788 );
1789
1790 if let Some(trait_span) = trait_span {
1791 err.span_label(
1792 trait_span,
1793 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait requires {0}",
potentially_plural_count(trait_number_args, "parameter")))
})format!(
1794 "trait requires {}",
1795 potentially_plural_count(trait_number_args, "parameter")
1796 ),
1797 );
1798 } else {
1799 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1800 }
1801
1802 err.span_label(
1803 impl_span,
1804 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}, found {1}",
potentially_plural_count(trait_number_args, "parameter"),
impl_number_args))
})format!(
1805 "expected {}, found {}",
1806 potentially_plural_count(trait_number_args, "parameter"),
1807 impl_number_args
1808 ),
1809 );
1810
1811 if !trait_m.def_id.is_local() {
1813 let trait_sig = tcx.fn_sig(trait_m.def_id);
1814 let trait_arg_idents = tcx.fn_arg_idents(trait_m.def_id);
1815 let sm = tcx.sess.source_map();
1816 let impl_inputs_span = if let (Some(first), Some(last)) =
1820 (impl_m_sig.decl.inputs.first(), impl_m_sig.decl.inputs.last())
1821 {
1822 let arg_idents = tcx.fn_arg_idents(impl_m.def_id);
1826 let first_lo = arg_idents
1827 .get(0)
1828 .and_then(|id| id.map(|id| id.span.lo()))
1829 .unwrap_or(first.span.lo());
1830 Some(impl_m_sig.span.with_lo(first_lo).with_hi(last.span.hi()))
1831 } else {
1832 sm.span_to_snippet(impl_m_sig.span).ok().and_then(|s| {
1837 let right_paren = s.as_bytes().iter().rposition(|&b| b == b')')?;
1838 let pos = impl_m_sig.span.lo() + BytePos(right_paren as u32);
1839 Some(impl_m_sig.span.with_lo(pos).with_hi(pos))
1840 })
1841 };
1842 let suggestion = match trait_number_args.cmp(&impl_number_args) {
1843 Ordering::Greater => {
1844 let trait_inputs = trait_sig.skip_binder().inputs().skip_binder();
1848 let missing = trait_inputs
1849 .iter()
1850 .enumerate()
1851 .skip(impl_number_args)
1852 .map(|(idx, ty)| {
1853 let name = trait_arg_idents
1854 .get(idx)
1855 .and_then(|ident| *ident)
1856 .map(|ident| ident.to_string())
1857 .unwrap_or_else(|| "_".to_string());
1858 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", name, ty))
})format!("{name}: {ty}")
1859 })
1860 .collect::<Vec<_>>();
1861
1862 if missing.is_empty() {
1863 None
1864 } else {
1865 impl_inputs_span.map(|s| {
1866 let span = s.shrink_to_hi();
1867 let prefix = if impl_number_args == 0 { "" } else { ", " };
1868 let replacement = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}", missing.join(", "),
prefix))
})format!("{prefix}{}", missing.join(", "));
1869 (
1870 span,
1871 ::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!(
1872 "add the missing parameter{} from the trait",
1873 pluralize!(trait_number_args - impl_number_args)
1874 ),
1875 replacement,
1876 )
1877 })
1878 }
1879 }
1880 Ordering::Less => impl_inputs_span.and_then(|full| {
1881 let lo = if trait_number_args == 0 {
1885 full.lo()
1886 } else {
1887 impl_m_sig
1888 .decl
1889 .inputs
1890 .get(trait_number_args - 1)
1891 .map(|arg| arg.span.hi())?
1892 };
1893 let span = full.with_lo(lo);
1894 Some((
1895 span,
1896 ::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!(
1897 "remove the extra parameter{} to match the trait",
1898 pluralize!(impl_number_args - trait_number_args)
1899 ),
1900 String::new(),
1901 ))
1902 }),
1903 Ordering::Equal => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1904 };
1905 if let Some((span, msg, replacement)) = suggestion {
1906 err.span_suggestion_verbose(span, msg, replacement, Applicability::MaybeIncorrect);
1907 }
1908 }
1909
1910 return Err(err.emit_unless_delay(delay));
1911 }
1912
1913 Ok(())
1914}
1915
1916fn compare_synthetic_generics<'tcx>(
1917 tcx: TyCtxt<'tcx>,
1918 impl_m: ty::AssocItem,
1919 trait_m: ty::AssocItem,
1920 delay: bool,
1921) -> Result<(), ErrorGuaranteed> {
1922 let mut error_found = None;
1928 let impl_m_generics = tcx.generics_of(impl_m.def_id);
1929 let trait_m_generics = tcx.generics_of(trait_m.def_id);
1930 let impl_m_type_params =
1931 impl_m_generics.own_params.iter().filter_map(|param| match param.kind {
1932 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1933 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1934 });
1935 let trait_m_type_params =
1936 trait_m_generics.own_params.iter().filter_map(|param| match param.kind {
1937 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1938 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1939 });
1940 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1941 iter::zip(impl_m_type_params, trait_m_type_params)
1942 {
1943 if impl_synthetic != trait_synthetic {
1944 let impl_def_id = impl_def_id.expect_local();
1945 let impl_span = tcx.def_span(impl_def_id);
1946 let trait_span = tcx.def_span(trait_def_id);
1947 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!(
1948 tcx.dcx(),
1949 impl_span,
1950 E0643,
1951 "method `{}` has incompatible signature for trait",
1952 trait_m.name()
1953 );
1954 err.span_label(trait_span, "declaration in trait here");
1955 if impl_synthetic {
1956 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1959 try {
1960 let new_name = tcx.opt_item_name(trait_def_id)?;
1964 let trait_m = trait_m.def_id.as_local()?;
1965 let trait_m = tcx.hir_expect_trait_item(trait_m);
1966
1967 let impl_m = impl_m.def_id.as_local()?;
1968 let impl_m = tcx.hir_expect_impl_item(impl_m);
1969
1970 let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1973 let generics_span = impl_m.generics.span.substitute_dummy(new_generics_span);
1975 let new_generics =
1977 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1978
1979 err.multipart_suggestion(
1980 "try changing the `impl Trait` argument to a generic parameter",
1981 ::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![
1982 (impl_span, new_name.to_string()),
1984 (generics_span, new_generics),
1988 ],
1989 Applicability::MaybeIncorrect,
1990 );
1991 };
1992 } else {
1993 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1996 try {
1997 let impl_m = impl_m.def_id.as_local()?;
1998 let impl_m = tcx.hir_expect_impl_item(impl_m);
1999 let (sig, _) = impl_m.expect_fn();
2000 let input_tys = sig.decl.inputs;
2001
2002 struct Visitor(hir::def_id::LocalDefId);
2003 impl<'v> intravisit::Visitor<'v> for Visitor {
2004 type Result = ControlFlow<Span>;
2005 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) -> Self::Result {
2006 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
2007 && let Res::Def(DefKind::TyParam, def_id) = path.res
2008 && def_id == self.0.to_def_id()
2009 {
2010 ControlFlow::Break(ty.span)
2011 } else {
2012 intravisit::walk_ty(self, ty)
2013 }
2014 }
2015 }
2016
2017 let span = input_tys
2018 .iter()
2019 .find_map(|ty| Visitor(impl_def_id).visit_ty_unambig(ty).break_value())?;
2020
2021 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
2022 let bounds = bounds.first()?.span().to(bounds.last()?.span());
2023 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
2024
2025 err.multipart_suggestion(
2026 "try removing the generic parameter and using `impl Trait` instead",
2027 ::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![
2028 (impl_m.generics.span, String::new()),
2030 (span, format!("impl {bounds}")),
2032 ],
2033 Applicability::MaybeIncorrect,
2034 );
2035 };
2036 }
2037 error_found = Some(err.emit_unless_delay(delay));
2038 }
2039 }
2040 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
2041}
2042
2043fn compare_generic_param_kinds<'tcx>(
2069 tcx: TyCtxt<'tcx>,
2070 impl_item: ty::AssocItem,
2071 trait_item: ty::AssocItem,
2072 delay: bool,
2073) -> Result<(), ErrorGuaranteed> {
2074 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());
2075
2076 let ty_const_params_of = |def_id| {
2077 tcx.generics_of(def_id).own_params.iter().filter(|param| {
2078 #[allow(non_exhaustive_omitted_patterns)] match param.kind {
GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. } =>
true,
_ => false,
}matches!(
2079 param.kind,
2080 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
2081 )
2082 })
2083 };
2084
2085 for (param_impl, param_trait) in
2086 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
2087 {
2088 use GenericParamDefKind::*;
2089 if match (¶m_impl.kind, ¶m_trait.kind) {
2090 (Const { .. }, Const { .. })
2091 if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
2092 {
2093 true
2094 }
2095 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
2096 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
2099 (Lifetime { .. }, _) | (_, Lifetime { .. }) => {
2100 ::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`")
2101 }
2102 } {
2103 let param_impl_span = tcx.def_span(param_impl.def_id);
2104 let param_trait_span = tcx.def_span(param_trait.def_id);
2105
2106 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!(
2107 tcx.dcx(),
2108 param_impl_span,
2109 E0053,
2110 "{} `{}` has an incompatible generic parameter for trait `{}`",
2111 impl_item.descr(),
2112 trait_item.name(),
2113 &tcx.def_path_str(tcx.parent(trait_item.def_id))
2114 );
2115
2116 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
2117 Const { .. } => {
2118 ::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!(
2119 "{} const parameter of type `{}`",
2120 prefix,
2121 tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip()
2122 )
2123 }
2124 Type { .. } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} type parameter", prefix))
})format!("{prefix} type parameter"),
2125 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!(
2126 tcx.def_span(param.def_id),
2127 "lifetime params are expected to be filtered by `ty_const_params_of`"
2128 ),
2129 };
2130
2131 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
2132 err.span_label(trait_header_span, "");
2133 err.span_label(param_trait_span, make_param_message("expected", param_trait));
2134
2135 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
2136 err.span_label(impl_header_span, "");
2137 err.span_label(param_impl_span, make_param_message("found", param_impl));
2138
2139 let reported = err.emit_unless_delay(delay);
2140 return Err(reported);
2141 }
2142 }
2143
2144 Ok(())
2145}
2146
2147fn compare_impl_const<'tcx>(
2148 tcx: TyCtxt<'tcx>,
2149 impl_const_item: ty::AssocItem,
2150 trait_const_item: ty::AssocItem,
2151 impl_trait_ref: ty::TraitRef<'tcx>,
2152) -> Result<(), ErrorGuaranteed> {
2153 compare_type_const(tcx, impl_const_item, trait_const_item)?;
2154 compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
2155 compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
2156 check_region_bounds_on_impl_item(tcx, impl_const_item, trait_const_item, false)?;
2157 compare_const_predicate_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
2158}
2159
2160fn compare_type_const<'tcx>(
2161 tcx: TyCtxt<'tcx>,
2162 impl_const_item: ty::AssocItem,
2163 trait_const_item: ty::AssocItem,
2164) -> Result<(), ErrorGuaranteed> {
2165 let impl_is_type_const = tcx.is_type_const(impl_const_item.def_id);
2166 let trait_type_const_span = tcx.type_const_span(trait_const_item.def_id);
2167
2168 if let Some(trait_type_const_span) = trait_type_const_span
2169 && !impl_is_type_const
2170 {
2171 return Err(tcx
2172 .dcx()
2173 .struct_span_err(
2174 tcx.def_span(impl_const_item.def_id),
2175 "implementation of a `type const` must also be marked as `type const`",
2176 )
2177 .with_span_note(
2178 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![
2179 tcx.def_span(trait_const_item.def_id),
2180 trait_type_const_span,
2181 ]),
2182 "trait declaration of const is marked as `type const`",
2183 )
2184 .emit());
2185 }
2186 Ok(())
2187}
2188
2189#[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(2192u32),
::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:2260",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2260u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&["impl_ty"],
::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:2263",
"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(2263u32),
::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:2268",
"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(2268u32),
::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))]
2193fn compare_const_predicate_entailment<'tcx>(
2194 tcx: TyCtxt<'tcx>,
2195 impl_ct: ty::AssocItem,
2196 trait_ct: ty::AssocItem,
2197 impl_trait_ref: ty::TraitRef<'tcx>,
2198) -> Result<(), ErrorGuaranteed> {
2199 let impl_ct_def_id = impl_ct.def_id.expect_local();
2200 let impl_ct_span = tcx.def_span(impl_ct_def_id);
2201
2202 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id).rebase_onto(
2208 tcx,
2209 impl_ct.container_id(tcx),
2210 impl_trait_ref.args,
2211 );
2212
2213 let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
2216
2217 let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
2218 let code = ObligationCauseCode::CompareImplItem {
2219 impl_item_def_id: impl_ct_def_id,
2220 trait_item_def_id: trait_ct.def_id,
2221 kind: impl_ct.kind,
2222 };
2223 let mut cause = ObligationCause::new(impl_ct_span, impl_ct_def_id, code.clone());
2224
2225 let impl_ct_predicates = tcx.predicates_of(impl_ct.def_id);
2226 let trait_ct_predicates = tcx.predicates_of(trait_ct.def_id);
2227
2228 let impl_predicates = tcx.predicates_of(impl_ct_predicates.parent.unwrap());
2231 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2232 hybrid_preds.extend(
2233 trait_ct_predicates
2234 .instantiate_own(tcx, trait_to_impl_args)
2235 .map(|(predicate, _)| predicate),
2236 );
2237 let hybrid_preds = hybrid_preds.into_iter().map(Unnormalized::skip_norm_wip);
2238
2239 let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
2240 let param_env = traits::normalize_param_env_or_error(
2241 tcx,
2242 param_env,
2243 ObligationCause::misc(impl_ct_span, impl_ct_def_id),
2244 );
2245
2246 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2247 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2248
2249 let impl_ct_own_bounds = impl_ct_predicates.instantiate_own_identity();
2250 for (predicate, span) in impl_ct_own_bounds {
2251 let cause = ObligationCause::misc(span, impl_ct_def_id);
2252 let predicate = ocx.normalize(&cause, param_env, predicate);
2253
2254 let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
2255 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2256 }
2257
2258 let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
2260 debug!(?impl_ty);
2261
2262 let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
2263 debug!(?trait_ty);
2264
2265 let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
2266
2267 if let Err(terr) = err {
2268 debug!(?impl_ty, ?trait_ty);
2269
2270 let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
2272 cause.span = ty.span;
2273
2274 let mut diag = struct_span_code_err!(
2275 tcx.dcx(),
2276 cause.span,
2277 E0326,
2278 "implemented const `{}` has an incompatible type for trait",
2279 trait_ct.name()
2280 );
2281
2282 let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
2283 let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
2285 ty.span
2286 });
2287
2288 infcx.err_ctxt().note_type_err(
2289 &mut diag,
2290 &cause,
2291 trait_c_span.map(|span| (span, Cow::from("type in trait"), false)),
2292 Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2293 expected: trait_ty.into(),
2294 found: impl_ty.into(),
2295 }))),
2296 terr,
2297 false,
2298 None,
2299 );
2300 return Err(diag.emit());
2301 };
2302
2303 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2306 if !errors.is_empty() {
2307 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2308 }
2309
2310 ocx.resolve_regions_and_report_errors(impl_ct_def_id, param_env, [])
2311}
2312
2313#[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(2313u32),
::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))]
2314fn compare_impl_ty<'tcx>(
2315 tcx: TyCtxt<'tcx>,
2316 impl_ty: ty::AssocItem,
2317 trait_ty: ty::AssocItem,
2318 impl_trait_ref: ty::TraitRef<'tcx>,
2319) -> Result<(), ErrorGuaranteed> {
2320 compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
2321 compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
2322 check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
2323 compare_type_predicate_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
2324 check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
2325}
2326
2327#[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(2329u32),
::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:2357",
"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(2357u32),
::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:2368",
"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(2368u32),
::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:2393",
"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(2393u32),
::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))]
2330fn compare_type_predicate_entailment<'tcx>(
2331 tcx: TyCtxt<'tcx>,
2332 impl_ty: ty::AssocItem,
2333 trait_ty: ty::AssocItem,
2334 impl_trait_ref: ty::TraitRef<'tcx>,
2335) -> Result<(), ErrorGuaranteed> {
2336 let impl_def_id = impl_ty.container_id(tcx);
2337 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
2338 tcx,
2339 impl_def_id,
2340 impl_trait_ref.args,
2341 );
2342
2343 let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
2344 let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);
2345
2346 let impl_ty_own_bounds = impl_ty_predicates.instantiate_own_identity();
2347 if impl_ty_own_bounds.len() == 0 {
2349 return Ok(());
2351 }
2352
2353 let impl_ty_def_id = impl_ty.def_id.expect_local();
2357 debug!(?trait_to_impl_args);
2358
2359 let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
2362 let mut hybrid_preds = impl_predicates.instantiate_identity(tcx).predicates;
2363 hybrid_preds.extend(
2364 trait_ty_predicates
2365 .instantiate_own(tcx, trait_to_impl_args)
2366 .map(|(predicate, _)| predicate),
2367 );
2368 debug!(?hybrid_preds);
2369
2370 let impl_ty_span = tcx.def_span(impl_ty_def_id);
2371 let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
2372
2373 let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
2374 if is_conditionally_const {
2375 hybrid_preds.extend(
2378 tcx.const_conditions(impl_ty_predicates.parent.unwrap())
2379 .instantiate_identity(tcx)
2380 .into_iter()
2381 .chain(
2382 tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
2383 )
2384 .map(|(trait_ref, _)| {
2385 trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
2386 }),
2387 );
2388 }
2389
2390 let hybrid_preds = hybrid_preds.into_iter().map(Unnormalized::skip_norm_wip);
2391 let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
2392 let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
2393 debug!(caller_bounds=?param_env.caller_bounds());
2394
2395 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2396 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2397
2398 for (predicate, span) in impl_ty_own_bounds {
2399 let cause = ObligationCause::misc(span, impl_ty_def_id);
2400 let predicate = ocx.normalize(&cause, param_env, predicate);
2401
2402 let cause = ObligationCause::new(
2403 span,
2404 impl_ty_def_id,
2405 ObligationCauseCode::CompareImplItem {
2406 impl_item_def_id: impl_ty.def_id.expect_local(),
2407 trait_item_def_id: trait_ty.def_id,
2408 kind: impl_ty.kind,
2409 },
2410 );
2411 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2412 }
2413
2414 if is_conditionally_const {
2415 let impl_ty_own_const_conditions =
2417 tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2418 for (const_condition, span) in impl_ty_own_const_conditions {
2419 let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2420 let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2421
2422 let cause = ObligationCause::new(
2423 span,
2424 impl_ty_def_id,
2425 ObligationCauseCode::CompareImplItem {
2426 impl_item_def_id: impl_ty_def_id,
2427 trait_item_def_id: trait_ty.def_id,
2428 kind: impl_ty.kind,
2429 },
2430 );
2431 ocx.register_obligation(traits::Obligation::new(
2432 tcx,
2433 cause,
2434 param_env,
2435 const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2436 ));
2437 }
2438 }
2439
2440 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2443 if !errors.is_empty() {
2444 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2445 return Err(reported);
2446 }
2447
2448 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2451}
2452
2453#[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(2466u32),
::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:2478",
"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(2478u32),
::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:2527",
"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(2527u32),
::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:2550",
"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(2550u32),
::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))]
2467pub(super) fn check_type_bounds<'tcx>(
2468 tcx: TyCtxt<'tcx>,
2469 trait_ty: ty::AssocItem,
2470 impl_ty: ty::AssocItem,
2471 impl_trait_ref: ty::TraitRef<'tcx>,
2472) -> Result<(), ErrorGuaranteed> {
2473 tcx.ensure_result().coherent_trait(impl_trait_ref.def_id)?;
2476
2477 let param_env = tcx.param_env(impl_ty.def_id);
2478 debug!(?param_env);
2479
2480 let container_id = impl_ty.container_id(tcx);
2481 let impl_ty_def_id = impl_ty.def_id.expect_local();
2482 let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2483 let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2484
2485 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2486 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2487
2488 let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2492 tcx.def_span(impl_ty_def_id)
2493 } else {
2494 match tcx.hir_node_by_def_id(impl_ty_def_id) {
2495 hir::Node::TraitItem(hir::TraitItem {
2496 kind: hir::TraitItemKind::Type(_, Some(ty)),
2497 ..
2498 }) => ty.span,
2499 hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2500 item => span_bug!(
2501 tcx.def_span(impl_ty_def_id),
2502 "cannot call `check_type_bounds` on item: {item:?}",
2503 ),
2504 }
2505 };
2506 let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2507
2508 let normalize_cause = ObligationCause::new(
2509 impl_ty_span,
2510 impl_ty_def_id,
2511 ObligationCauseCode::CheckAssociatedTypeBounds {
2512 impl_item_def_id: impl_ty.def_id.expect_local(),
2513 trait_item_def_id: trait_ty.def_id,
2514 },
2515 );
2516 let mk_cause = |span: Span| {
2517 let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2518 ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2519 };
2520
2521 let mut obligations: Vec<_> = util::elaborate(
2522 tcx,
2523 tcx.explicit_item_bounds(trait_ty.def_id)
2524 .iter_instantiated_copied(tcx, rebased_args)
2525 .map(Unnormalized::skip_norm_wip)
2526 .map(|(concrete_ty_bound, span)| {
2527 debug!(?concrete_ty_bound);
2528 traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2529 }),
2530 )
2531 .collect();
2532
2533 if tcx.is_conditionally_const(impl_ty_def_id) {
2535 obligations.extend(util::elaborate(
2536 tcx,
2537 tcx.explicit_implied_const_bounds(trait_ty.def_id)
2538 .iter_instantiated_copied(tcx, rebased_args)
2539 .map(Unnormalized::skip_norm_wip)
2540 .map(|(c, span)| {
2541 traits::Obligation::new(
2542 tcx,
2543 mk_cause(span),
2544 param_env,
2545 c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2546 )
2547 }),
2548 ));
2549 }
2550 debug!(item_bounds=?obligations);
2551
2552 let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2557 for obligation in &mut obligations {
2558 match ocx.deeply_normalize(
2559 &normalize_cause,
2560 normalize_param_env,
2561 Unnormalized::new_wip(obligation.predicate),
2562 ) {
2563 Ok(pred) => obligation.predicate = pred,
2564 Err(e) => {
2565 return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2566 }
2567 }
2568 }
2569
2570 ocx.register_obligations(obligations);
2573 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2574 if !errors.is_empty() {
2575 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2576 return Err(reported);
2577 }
2578
2579 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2582}
2583
2584fn param_env_with_gat_bounds<'tcx>(
2632 tcx: TyCtxt<'tcx>,
2633 impl_ty: ty::AssocItem,
2634 impl_trait_ref: ty::TraitRef<'tcx>,
2635) -> ty::ParamEnv<'tcx> {
2636 let param_env = tcx.param_env(impl_ty.def_id);
2637 let container_id = impl_ty.container_id(tcx);
2638 let mut predicates = param_env.caller_bounds().to_vec();
2639
2640 let impl_tys_to_install = match impl_ty.kind {
2645 ty::AssocKind::Type {
2646 data:
2647 ty::AssocTypeData::Rpitit(
2648 ty::ImplTraitInTraitData::Impl { fn_def_id }
2649 | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2650 ),
2651 } => tcx
2652 .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2653 .iter()
2654 .map(|def_id| tcx.associated_item(*def_id))
2655 .collect(),
2656 _ => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[impl_ty]))vec![impl_ty],
2657 };
2658
2659 for impl_ty in impl_tys_to_install {
2660 let trait_ty = match impl_ty.container {
2661 ty::AssocContainer::InherentImpl => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
2662 ty::AssocContainer::Trait => impl_ty,
2663 ty::AssocContainer::TraitImpl(Err(_)) => continue,
2664 ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
2665 tcx.associated_item(trait_item_def_id)
2666 }
2667 };
2668
2669 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind<'tcx>; 8]> =
2670 smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2671 let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2673 .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2674 GenericParamDefKind::Type { .. } => {
2675 let kind = ty::BoundTyKind::Param(param.def_id);
2676 let bound_var = ty::BoundVariableKind::Ty(kind);
2677 bound_vars.push(bound_var);
2678 Ty::new_bound(
2679 tcx,
2680 ty::INNERMOST,
2681 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2682 )
2683 .into()
2684 }
2685 GenericParamDefKind::Lifetime => {
2686 let kind = ty::BoundRegionKind::Named(param.def_id);
2687 let bound_var = ty::BoundVariableKind::Region(kind);
2688 bound_vars.push(bound_var);
2689 ty::Region::new_bound(
2690 tcx,
2691 ty::INNERMOST,
2692 ty::BoundRegion {
2693 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2694 kind,
2695 },
2696 )
2697 .into()
2698 }
2699 GenericParamDefKind::Const { .. } => {
2700 let bound_var = ty::BoundVariableKind::Const;
2701 bound_vars.push(bound_var);
2702 ty::Const::new_bound(
2703 tcx,
2704 ty::INNERMOST,
2705 ty::BoundConst::new(ty::BoundVar::from_usize(bound_vars.len() - 1)),
2706 )
2707 .into()
2708 }
2709 });
2710 let normalize_impl_ty =
2720 tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args).skip_norm_wip();
2721 let rebased_args =
2722 normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2723 let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2724
2725 match normalize_impl_ty.kind() {
2726 &ty::Alias(ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
2727 if def_id == trait_ty.def_id && args == rebased_args =>
2728 {
2729 }
2735 _ => predicates.push(
2736 ty::Binder::bind_with_vars(
2737 ty::ProjectionPredicate {
2738 projection_term: ty::AliasTerm::new_from_def_id(
2739 tcx,
2740 trait_ty.def_id,
2741 rebased_args,
2742 ),
2743 term: normalize_impl_ty.into(),
2744 },
2745 bound_vars,
2746 )
2747 .upcast(tcx),
2748 ),
2749 };
2750 }
2751
2752 ty::ParamEnv::new(tcx.mk_clauses(&predicates))
2753}
2754
2755fn try_report_async_mismatch<'tcx>(
2758 tcx: TyCtxt<'tcx>,
2759 infcx: &InferCtxt<'tcx>,
2760 errors: &[FulfillmentError<'tcx>],
2761 trait_m: ty::AssocItem,
2762 impl_m: ty::AssocItem,
2763 impl_sig: ty::FnSig<'tcx>,
2764) -> Result<(), ErrorGuaranteed> {
2765 if !tcx.asyncness(trait_m.def_id).is_async() {
2766 return Ok(());
2767 }
2768
2769 let ty::Alias(ty::AliasTy { kind: ty::Projection { def_id: async_future_def_id }, .. }) =
2770 *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2771 else {
2772 ::rustc_middle::util::bug::bug_fmt(format_args!("expected `async fn` to return an RPITIT"));bug!("expected `async fn` to return an RPITIT");
2773 };
2774
2775 for error in errors {
2776 if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2777 && def_id == async_future_def_id
2778 && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2779 && let Some(proj) = proj.no_bound_vars()
2780 && infcx.can_eq(
2781 error.root_obligation.param_env,
2782 proj.term.expect_type(),
2783 impl_sig.output(),
2784 )
2785 {
2786 return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2789 span: tcx.def_span(impl_m.def_id),
2790 method_name: tcx.item_ident(impl_m.def_id),
2791 trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
2792 }));
2793 }
2794 }
2795
2796 Ok(())
2797}