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