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::Visitor;
12use rustc_hir::{self as hir, AmbigArg, GenericParamKind, ImplItemKind, intravisit};
13use rustc_infer::infer::{self, BoundRegionConversionTime, InferCtxt, TyCtxtInferExt};
14use rustc_infer::traits::{TraitErrors, 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_span::{BytePos, DUMMY_SP, Span, bug, kw, span_bug};
22use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
23use rustc_trait_selection::infer::InferCtxtExt;
24use rustc_trait_selection::regions::InferCtxtRegionExt;
25use rustc_trait_selection::solve::NextSolverError;
26use rustc_trait_selection::traits::{
27 self, FromSolverError, 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 /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/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("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/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(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("impl_trait_ref");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
as &dyn ::tracing::field::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("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/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(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_m")
}> =
::tracing::__macro_support::FieldName::new("impl_m");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_m")
}> =
::tracing::__macro_support::FieldName::new("trait_m");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("impl_trait_ref");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_m)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_m)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
as &dyn ::tracing::field::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_clause_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_clause_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_const_generic_param_types(tcx, impl_m, trait_m, impl_trait_ref, delay)?;
90 compare_number_of_method_arguments(tcx, impl_m, trait_m, delay)?;
91 compare_synthetic_generics(tcx, impl_m, trait_m, delay)?;
92 check_region_bounds_on_impl_item(tcx, impl_m, trait_m, delay)?;
93 Ok(())
94}
95
96{}
#[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_clause_entailment",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(174u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_m")
}> =
::tracing::__macro_support::FieldName::new("impl_m");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_m")
}> =
::tracing::__macro_support::FieldName::new("trait_m");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_m)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_m)
as &dyn ::tracing::field::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 /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:205",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(205u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_to_impl_args")
}> =
::tracing::__macro_support::FieldName::new("trait_to_impl_args");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_to_impl_args)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let impl_m_clauses = tcx.clauses_of(impl_m.def_id);
let trait_m_clauses = tcx.clauses_of(trait_m.def_id);
let impl_clauses = tcx.clauses_of(impl_m_clauses.parent.unwrap());
let mut hybrid_clauses =
impl_clauses.instantiate_identity(tcx).clauses;
hybrid_clauses.extend(trait_m_clauses.instantiate_own(tcx,
trait_to_impl_args).map(|(clause, _)| clause));
let is_conditionally_const =
tcx.is_conditionally_const(impl_m.def_id);
if is_conditionally_const {
hybrid_clauses.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_clauses =
hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
let normalize_cause =
traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
let param_env =
traits::normalize_param_env_or_error(tcx,
hybrid_clauses.collect(), normalize_cause);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:257",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(257u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param_env")
}> =
::tracing::__macro_support::FieldName::new("param_env");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_env)
as &dyn ::tracing::field::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_clauses.instantiate_own_identity();
for (clause, span) in impl_m_own_bounds {
let normalize_cause =
traits::ObligationCause::misc(span, impl_m_def_id);
let clause =
ocx.normalize(&normalize_cause, param_env, clause);
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, clause));
}
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 /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:333",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(333u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_sig")
}> =
::tracing::__macro_support::FieldName::new("impl_sig");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_sig)
as &dyn ::tracing::field::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 /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:346",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(346u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_sig")
}> =
::tracing::__macro_support::FieldName::new("trait_sig");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_sig)
as &dyn ::tracing::field::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 /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:358",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(358u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_sig")
}> =
::tracing::__macro_support::FieldName::new("impl_sig");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_sig")
}> =
::tracing::__macro_support::FieldName::new("trait_sig");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("terr")
}> =
::tracing::__macro_support::FieldName::new("terr");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("sub_types failed")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_sig)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_sig)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&terr)
as &dyn ::tracing::field::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 let TraitErrors::HasErrors(errors) = errors {
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))]
175fn compare_method_clause_entailment<'tcx>(
176 tcx: TyCtxt<'tcx>,
177 impl_m: ty::AssocItem,
178 trait_m: ty::AssocItem,
179 impl_trait_ref: ty::TraitRef<'tcx>,
180) -> Result<(), ErrorGuaranteed> {
181 let impl_m_def_id = impl_m.def_id.expect_local();
187 let impl_m_span = tcx.def_span(impl_m_def_id);
188 let cause = ObligationCause::new(
189 impl_m_span,
190 impl_m_def_id,
191 ObligationCauseCode::CompareImplItem {
192 impl_item_def_id: impl_m_def_id,
193 trait_item_def_id: trait_m.def_id,
194 kind: impl_m.kind,
195 },
196 );
197
198 let impl_def_id = impl_m.container_id(tcx);
200 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
201 tcx,
202 impl_m.container_id(tcx),
203 impl_trait_ref.args,
204 );
205 debug!(?trait_to_impl_args);
206
207 let impl_m_clauses = tcx.clauses_of(impl_m.def_id);
208 let trait_m_clauses = tcx.clauses_of(trait_m.def_id);
209
210 let impl_clauses = tcx.clauses_of(impl_m_clauses.parent.unwrap());
218 let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
219 hybrid_clauses
220 .extend(trait_m_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(clause, _)| clause));
221
222 let is_conditionally_const = tcx.is_conditionally_const(impl_m.def_id);
223 if is_conditionally_const {
224 hybrid_clauses.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_clauses = hybrid_clauses.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 =
256 traits::normalize_param_env_or_error(tcx, hybrid_clauses.collect(), normalize_cause);
257 debug!(?param_env);
258
259 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
260 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
261
262 let impl_m_own_bounds = impl_m_clauses.instantiate_own_identity();
267 for (clause, span) in impl_m_own_bounds {
268 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
269 let clause = ocx.normalize(&normalize_cause, param_env, clause);
270
271 let cause = ObligationCause::new(
272 span,
273 impl_m_def_id,
274 ObligationCauseCode::CompareImplItem {
275 impl_item_def_id: impl_m_def_id,
276 trait_item_def_id: trait_m.def_id,
277 kind: impl_m.kind,
278 },
279 );
280 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
281 }
282
283 if is_conditionally_const {
290 for (const_condition, span) in
291 tcx.const_conditions(impl_m.def_id).instantiate_own_identity()
292 {
293 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
294 let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
295
296 let cause = ObligationCause::new(
297 span,
298 impl_m_def_id,
299 ObligationCauseCode::CompareImplItem {
300 impl_item_def_id: impl_m_def_id,
301 trait_item_def_id: trait_m.def_id,
302 kind: impl_m.kind,
303 },
304 );
305 ocx.register_obligation(traits::Obligation::new(
306 tcx,
307 cause,
308 param_env,
309 const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
310 ));
311 }
312 }
313
314 let mut wf_tys = FxIndexSet::default();
323
324 let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars(
325 impl_m_span,
326 BoundRegionConversionTime::HigherRankedType,
327 tcx.fn_sig(impl_m.def_id).instantiate_identity().skip_norm_wip(),
328 );
329
330 let norm_cause = ObligationCause::misc(impl_m_span, impl_m_def_id);
331 let impl_sig =
332 ocx.normalize(&norm_cause, param_env, Unnormalized::new_wip(unnormalized_impl_sig));
333 debug!(?impl_sig);
334
335 let trait_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args).skip_norm_wip();
336 let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);
337
338 wf_tys.extend(trait_sig.inputs_and_output.iter());
342 let trait_sig = ocx.normalize(&norm_cause, param_env, Unnormalized::new_wip(trait_sig));
343 wf_tys.extend(trait_sig.inputs_and_output.iter());
346 debug!(?trait_sig);
347
348 let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
356
357 if let Err(terr) = result {
358 debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
359
360 let emitted = report_trait_method_mismatch(
361 infcx,
362 cause,
363 param_env,
364 terr,
365 (trait_m, trait_sig),
366 (impl_m, impl_sig),
367 impl_trait_ref,
368 );
369 return Err(emitted);
370 }
371
372 if !(impl_sig, trait_sig).references_error() {
373 for ty in unnormalized_impl_sig.inputs_and_output {
374 ocx.register_obligation(traits::Obligation::new(
375 infcx.tcx,
376 cause.clone(),
377 param_env,
378 ty::ClauseKind::WellFormed(ty.into()),
379 ));
380 }
381 }
382
383 let errors = ocx.evaluate_obligations_error_on_ambiguity();
386 if let TraitErrors::HasErrors(errors) = errors {
387 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
388 return Err(reported);
389 }
390
391 let errors = infcx.resolve_regions(impl_m_def_id, param_env, wf_tys);
394 if !errors.is_empty() {
395 return Err(infcx
396 .tainted_by_errors()
397 .unwrap_or_else(|| infcx.err_ctxt().report_region_errors(impl_m_def_id, &errors)));
398 }
399
400 Ok(())
401}
402
403struct RemapLateParam<'tcx> {
404 tcx: TyCtxt<'tcx>,
405 mapping: FxIndexMap<ty::LateParamRegionKind, ty::LateParamRegionKind>,
406}
407
408impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateParam<'tcx> {
409 fn cx(&self) -> TyCtxt<'tcx> {
410 self.tcx
411 }
412
413 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
414 if let ty::ReLateParam(fr) = r.kind() {
415 ty::Region::new_late_param(
416 self.tcx,
417 fr.scope,
418 self.mapping.get(&fr.kind).copied().unwrap_or(fr.kind),
419 )
420 } else {
421 r
422 }
423 }
424}
425
426{}
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("collect_return_position_impl_trait_in_trait_tys",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(457u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_m_def_id")
}> =
::tracing::__macro_support::FieldName::new("impl_m_def_id");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_m_def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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<&'tcx DefIdMap<ty::EarlyBinder<'tcx, Ty<'tcx>>>,
ErrorGuaranteed> = loop {};
return __tracing_attr_fake_return;
}
{
let impl_m = tcx.associated_item(impl_m_def_id.to_def_id());
let trait_m =
tcx.associated_item(impl_m.expect_trait_impl()?);
let impl_trait_ref =
tcx.impl_trait_ref(tcx.parent(impl_m_def_id.to_def_id())).instantiate_identity().skip_norm_wip();
check_method_is_structurally_compatible(tcx, impl_m,
trait_m, impl_trait_ref, true)?;
let impl_m_hir_id =
tcx.local_def_id_to_hir_id(impl_m_def_id);
let return_span =
tcx.hir_fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
let cause =
ObligationCause::new(return_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 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);
let hybrid_clauses =
tcx.clauses_of(impl_m.container_id(tcx)).instantiate_identity(tcx).into_iter().chain(tcx.clauses_of(trait_m.def_id).instantiate_own(tcx,
trait_to_impl_args)).map(|(clause, _)|
clause.skip_norm_wip());
let param_env =
traits::normalize_param_env_or_error(tcx,
hybrid_clauses.collect(),
ObligationCause::misc(tcx.def_span(impl_m_def_id),
impl_m_def_id));
let infcx =
&tcx.infer_ctxt().build(TypingMode::non_body_analysis());
let ocx = ObligationCtxt::new_with_diagnostics(infcx);
let impl_m_own_bounds =
tcx.clauses_of(impl_m_def_id).instantiate_own_identity();
for (clause, span) in impl_m_own_bounds {
let normalize_cause =
traits::ObligationCause::misc(span, impl_m_def_id);
let clause =
ocx.normalize(&normalize_cause, param_env, clause);
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, clause));
}
let misc_cause =
ObligationCause::misc(return_span, impl_m_def_id);
let impl_sig =
ocx.normalize(&misc_cause, param_env,
Unnormalized::new_wip(infcx.instantiate_binder_with_fresh_vars(return_span,
BoundRegionConversionTime::HigherRankedType,
tcx.fn_sig(impl_m.def_id).instantiate_identity().skip_norm_wip())));
impl_sig.error_reported()?;
let impl_return_ty = impl_sig.output();
let mut collector =
ImplTraitInTraitCollector::new(&ocx, return_span, param_env,
impl_m_def_id);
let unnormalized_trait_sig =
tcx.liberate_late_bound_regions(impl_m.def_id,
tcx.fn_sig(trait_m.def_id).instantiate(tcx,
trait_to_impl_args).skip_norm_wip()).fold_with(&mut collector);
let trait_sig =
ocx.normalize(&misc_cause, param_env,
Unnormalized::new_wip(unnormalized_trait_sig));
trait_sig.error_reported()?;
let trait_return_ty = trait_sig.output();
let universe = infcx.create_next_universe();
let mut idx = ty::BoundVar::ZERO;
let mapping: FxIndexMap<_, _> =
collector.types.iter().map(|(_, &(ty, _))|
{
if !(infcx.deeply_resolve_ignoring_regions(ty) == ty &&
ty.is_ty_var()) {
{
::core::panicking::panic_fmt(format_args!("{0:?} should not have been constrained via normalization",
infcx.deeply_resolve_ignoring_regions(ty)));
}
};
idx += 1;
(ty,
Ty::new_placeholder(tcx,
ty::PlaceholderType::new(universe,
ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon })))
}).collect();
let mut type_mapper =
BottomUpFolder {
tcx,
ty_op: |ty| *mapping.get(&ty).unwrap_or(&ty),
lt_op: |lt| lt,
ct_op: |ct| ct,
};
let wf_tys =
FxIndexSet::from_iter(unnormalized_trait_sig.inputs_and_output.iter().chain(trait_sig.inputs_and_output.iter()).map(|ty|
ty.fold_with(&mut type_mapper)));
match ocx.eq(&cause, param_env, trait_return_ty,
impl_return_ty) {
Ok(()) => {}
Err(terr) => {
let mut diag =
{
tcx.dcx().struct_span_err(cause.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("method `{0}` has an incompatible return type for trait",
trait_m.name()))
})).with_code(E0053)
};
diag.span_context(tcx.def_span(impl_m.container_id(tcx)).shrink_to_lo());
infcx.err_ctxt().note_type_err(&mut diag, &cause,
tcx.hir_get_if_local(trait_m.def_id).and_then(|node|
node.fn_decl()).map(|decl|
{
let mut span: MultiSpan = decl.output.span().into();
span.push_span_context(tcx.def_span(trait_m.container_id(tcx)).shrink_to_lo());
span.push_span_context(tcx.def_span(trait_m.def_id).shrink_to_lo());
(span, Cow::from("return type in trait"), false)
}),
Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
expected: trait_return_ty.into(),
found: impl_return_ty.into(),
}))), terr, false, None);
return Err(diag.emit_err());
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:649",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(649u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_sig")
}> =
::tracing::__macro_support::FieldName::new("trait_sig");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_sig")
}> =
::tracing::__macro_support::FieldName::new("impl_sig");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("equating function signatures")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_sig)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_sig)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
Ok(()) => {}
Err(terr) => {
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 !unnormalized_trait_sig.output().references_error() &&
collector.types.is_empty() {
tcx.dcx().delayed_bug("expect >0 RPITITs in call to `collect_return_position_impl_trait_in_trait_tys`");
}
let collected_types = collector.types;
for (_, &(ty, _)) in &collected_types {
ocx.register_obligation(traits::Obligation::new(tcx,
misc_cause.clone(), param_env,
ty::ClauseKind::WellFormed(ty.into())));
}
let errors = ocx.evaluate_obligations_error_on_ambiguity();
if let TraitErrors::HasErrors(errors) = errors {
if let Err(guar) =
try_report_async_mismatch(tcx, infcx, &errors, trait_m,
impl_m, impl_sig) {
return Err(guar);
}
let guar =
infcx.err_ctxt().report_fulfillment_errors(errors);
return Err(guar);
}
ocx.resolve_regions_and_report_errors(impl_m_def_id,
param_env, wf_tys)?;
let mut remapped_types = DefIdMap::default();
for (def_id, (ty, args)) in collected_types {
match infcx.deeply_resolve_via_region_graph(ty) {
Ok(ty) => {
let id_args = GenericArgs::identity_for_item(tcx, def_id);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:720",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(720u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("id_args")
}> =
::tracing::__macro_support::FieldName::new("id_args");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("args")
}> =
::tracing::__macro_support::FieldName::new("args");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id_args)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let map: FxIndexMap<_, _> =
std::iter::zip(args,
id_args).skip(tcx.generics_of(trait_m.def_id).count()).filter_map(|(a,
b)| Some((a.as_region()?, b.as_region()?))).collect();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:725",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(725u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("map")
}> =
::tracing::__macro_support::FieldName::new("map");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&map)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let num_trait_args = impl_trait_ref.args.len();
let num_impl_args =
tcx.generics_of(impl_m.container_id(tcx)).own_params.len();
let ty =
match ty.try_fold_with(&mut RemapHiddenTyRegions {
tcx,
map,
num_trait_args,
num_impl_args,
def_id,
impl_m_def_id: impl_m.def_id,
ty,
return_span,
}) {
Ok(ty) => ty,
Err(guar) => Ty::new_error(tcx, guar),
};
remapped_types.insert(def_id,
ty::EarlyBinder::bind(tcx, ty));
}
Err(err) => {
tcx.dcx().span_bug(return_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("could not fully resolve: {0} => {1:?}",
ty, err))
}));
}
}
}
for assoc_item in
tcx.associated_types_for_impl_traits_in_associated_fn(trait_m.def_id)
{
if !remapped_types.contains_key(assoc_item) {
remapped_types.insert(*assoc_item,
ty::EarlyBinder::bind(tcx,
Ty::new_error_with_message(tcx, return_span,
"missing synthetic item for RPITIT")));
}
}
Ok(&*tcx.arena.alloc(remapped_types))
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:457",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(457u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(skip(tcx), level = "debug", ret)]
458pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
459 tcx: TyCtxt<'tcx>,
460 impl_m_def_id: LocalDefId,
461) -> Result<&'tcx DefIdMap<ty::EarlyBinder<'tcx, Ty<'tcx>>>, ErrorGuaranteed> {
462 let impl_m = tcx.associated_item(impl_m_def_id.to_def_id());
463 let trait_m = tcx.associated_item(impl_m.expect_trait_impl()?);
464 let impl_trait_ref = tcx
465 .impl_trait_ref(tcx.parent(impl_m_def_id.to_def_id()))
466 .instantiate_identity()
467 .skip_norm_wip();
468 check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?;
471
472 let impl_m_hir_id = tcx.local_def_id_to_hir_id(impl_m_def_id);
473 let return_span = tcx.hir_fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
474 let cause = ObligationCause::new(
475 return_span,
476 impl_m_def_id,
477 ObligationCauseCode::CompareImplItem {
478 impl_item_def_id: impl_m_def_id,
479 trait_item_def_id: trait_m.def_id,
480 kind: impl_m.kind,
481 },
482 );
483
484 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto(
486 tcx,
487 impl_m.container_id(tcx),
488 impl_trait_ref.args,
489 );
490
491 let hybrid_clauses = tcx
492 .clauses_of(impl_m.container_id(tcx))
493 .instantiate_identity(tcx)
494 .into_iter()
495 .chain(tcx.clauses_of(trait_m.def_id).instantiate_own(tcx, trait_to_impl_args))
496 .map(|(clause, _)| clause.skip_norm_wip());
497 let param_env = traits::normalize_param_env_or_error(
498 tcx,
499 hybrid_clauses.collect(),
500 ObligationCause::misc(tcx.def_span(impl_m_def_id), impl_m_def_id),
501 );
502
503 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
504 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
505
506 let impl_m_own_bounds = tcx.clauses_of(impl_m_def_id).instantiate_own_identity();
513 for (clause, span) in impl_m_own_bounds {
514 let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
515 let clause = ocx.normalize(&normalize_cause, param_env, clause);
516
517 let cause = ObligationCause::new(
518 span,
519 impl_m_def_id,
520 ObligationCauseCode::CompareImplItem {
521 impl_item_def_id: impl_m_def_id,
522 trait_item_def_id: trait_m.def_id,
523 kind: impl_m.kind,
524 },
525 );
526 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
527 }
528
529 let misc_cause = ObligationCause::misc(return_span, impl_m_def_id);
531 let impl_sig = ocx.normalize(
532 &misc_cause,
533 param_env,
534 Unnormalized::new_wip(infcx.instantiate_binder_with_fresh_vars(
535 return_span,
536 BoundRegionConversionTime::HigherRankedType,
537 tcx.fn_sig(impl_m.def_id).instantiate_identity().skip_norm_wip(),
538 )),
539 );
540 impl_sig.error_reported()?;
541 let impl_return_ty = impl_sig.output();
542
543 let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_def_id);
548 let unnormalized_trait_sig = tcx
549 .liberate_late_bound_regions(
550 impl_m.def_id,
551 tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_impl_args).skip_norm_wip(),
552 )
553 .fold_with(&mut collector);
554
555 let trait_sig =
556 ocx.normalize(&misc_cause, param_env, Unnormalized::new_wip(unnormalized_trait_sig));
557 trait_sig.error_reported()?;
558 let trait_return_ty = trait_sig.output();
559
560 let universe = infcx.create_next_universe();
580 let mut idx = ty::BoundVar::ZERO;
581 let mapping: FxIndexMap<_, _> = collector
582 .types
583 .iter()
584 .map(|(_, &(ty, _))| {
585 assert!(
586 infcx.deeply_resolve_ignoring_regions(ty) == ty && ty.is_ty_var(),
587 "{ty:?} should not have been constrained via normalization",
588 ty = infcx.deeply_resolve_ignoring_regions(ty)
589 );
590 idx += 1;
591 (
592 ty,
593 Ty::new_placeholder(
594 tcx,
595 ty::PlaceholderType::new(
596 universe,
597 ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
598 ),
599 ),
600 )
601 })
602 .collect();
603 let mut type_mapper = BottomUpFolder {
604 tcx,
605 ty_op: |ty| *mapping.get(&ty).unwrap_or(&ty),
606 lt_op: |lt| lt,
607 ct_op: |ct| ct,
608 };
609 let wf_tys = FxIndexSet::from_iter(
610 unnormalized_trait_sig
611 .inputs_and_output
612 .iter()
613 .chain(trait_sig.inputs_and_output.iter())
614 .map(|ty| ty.fold_with(&mut type_mapper)),
615 );
616
617 match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
618 Ok(()) => {}
619 Err(terr) => {
620 let mut diag = struct_span_code_err!(
621 tcx.dcx(),
622 cause.span,
623 E0053,
624 "method `{}` has an incompatible return type for trait",
625 trait_m.name()
626 );
627 diag.span_context(tcx.def_span(impl_m.container_id(tcx)).shrink_to_lo());
628 infcx.err_ctxt().note_type_err(
629 &mut diag,
630 &cause,
631 tcx.hir_get_if_local(trait_m.def_id).and_then(|node| node.fn_decl()).map(|decl| {
632 let mut span: MultiSpan = decl.output.span().into();
633 span.push_span_context(tcx.def_span(trait_m.container_id(tcx)).shrink_to_lo());
634 span.push_span_context(tcx.def_span(trait_m.def_id).shrink_to_lo());
635 (span, Cow::from("return type in trait"), false)
636 }),
637 Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
638 expected: trait_return_ty.into(),
639 found: impl_return_ty.into(),
640 }))),
641 terr,
642 false,
643 None,
644 );
645 return Err(diag.emit_err());
646 }
647 }
648
649 debug!(?trait_sig, ?impl_sig, "equating function signatures");
650
651 match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
656 Ok(()) => {}
657 Err(terr) => {
658 let emitted = report_trait_method_mismatch(
663 infcx,
664 cause,
665 param_env,
666 terr,
667 (trait_m, trait_sig),
668 (impl_m, impl_sig),
669 impl_trait_ref,
670 );
671 return Err(emitted);
672 }
673 }
674
675 if !unnormalized_trait_sig.output().references_error() && collector.types.is_empty() {
676 tcx.dcx().delayed_bug(
677 "expect >0 RPITITs in call to `collect_return_position_impl_trait_in_trait_tys`",
678 );
679 }
680
681 let collected_types = collector.types;
686 for (_, &(ty, _)) in &collected_types {
687 ocx.register_obligation(traits::Obligation::new(
688 tcx,
689 misc_cause.clone(),
690 param_env,
691 ty::ClauseKind::WellFormed(ty.into()),
692 ));
693 }
694
695 let errors = ocx.evaluate_obligations_error_on_ambiguity();
698 if let TraitErrors::HasErrors(errors) = errors {
699 if let Err(guar) = try_report_async_mismatch(tcx, infcx, &errors, trait_m, impl_m, impl_sig)
700 {
701 return Err(guar);
702 }
703
704 let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
705 return Err(guar);
706 }
707
708 ocx.resolve_regions_and_report_errors(impl_m_def_id, param_env, wf_tys)?;
711
712 let mut remapped_types = DefIdMap::default();
713 for (def_id, (ty, args)) in collected_types {
714 match infcx.deeply_resolve_via_region_graph(ty) {
715 Ok(ty) => {
716 let id_args = GenericArgs::identity_for_item(tcx, def_id);
720 debug!(?id_args, ?args);
721 let map: FxIndexMap<_, _> = std::iter::zip(args, id_args)
722 .skip(tcx.generics_of(trait_m.def_id).count())
723 .filter_map(|(a, b)| Some((a.as_region()?, b.as_region()?)))
724 .collect();
725 debug!(?map);
726
727 let num_trait_args = impl_trait_ref.args.len();
748 let num_impl_args = tcx.generics_of(impl_m.container_id(tcx)).own_params.len();
749 let ty = match ty.try_fold_with(&mut RemapHiddenTyRegions {
750 tcx,
751 map,
752 num_trait_args,
753 num_impl_args,
754 def_id,
755 impl_m_def_id: impl_m.def_id,
756 ty,
757 return_span,
758 }) {
759 Ok(ty) => ty,
760 Err(guar) => Ty::new_error(tcx, guar),
761 };
762 remapped_types.insert(def_id, ty::EarlyBinder::bind(tcx, ty));
763 }
764 Err(err) => {
765 tcx.dcx()
770 .span_bug(return_span, format!("could not fully resolve: {ty} => {err:?}"));
771 }
772 }
773 }
774
775 for assoc_item in tcx.associated_types_for_impl_traits_in_associated_fn(trait_m.def_id) {
781 if !remapped_types.contains_key(assoc_item) {
782 remapped_types.insert(
783 *assoc_item,
784 ty::EarlyBinder::bind(
785 tcx,
786 Ty::new_error_with_message(
787 tcx,
788 return_span,
789 "missing synthetic item for RPITIT",
790 ),
791 ),
792 );
793 }
794 }
795
796 Ok(&*tcx.arena.alloc(remapped_types))
797}
798
799struct ImplTraitInTraitCollector<'a, 'tcx, E> {
800 ocx: &'a ObligationCtxt<'a, 'tcx, E>,
801 types: FxIndexMap<DefId, (Ty<'tcx>, ty::GenericArgs<'tcx>)>,
802 span: Span,
803 param_env: ty::ParamEnv<'tcx>,
804 impl_m_id: LocalDefId,
805}
806
807impl<'a, 'tcx, E> ImplTraitInTraitCollector<'a, 'tcx, E>
808where
809 E: FromSolverError<'tcx, NextSolverError<'tcx>>
810 + FromSolverError<'tcx, traits::OldSolverError<'tcx>>,
811{
812 fn new(
813 ocx: &'a ObligationCtxt<'a, 'tcx, E>,
814 span: Span,
815 param_env: ty::ParamEnv<'tcx>,
816 impl_m_id: LocalDefId,
817 ) -> Self {
818 ImplTraitInTraitCollector { ocx, types: FxIndexMap::default(), span, param_env, impl_m_id }
819 }
820}
821
822impl<'tcx, E> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx, E>
823where
824 E: FromSolverError<'tcx, NextSolverError<'tcx>>
825 + FromSolverError<'tcx, traits::OldSolverError<'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_span::macros::bug_impl(None,
format_args!("FIXME(RPITIT): error here"), Location::caller());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.impl_m_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.impl_m_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_span::macros::bug_impl(None,
format_args!("expected to map region {0} to early-bound identity region, but got {1}",
region, id_region), Location::caller());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_err()
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 diag.span_context(tcx.def_span(impl_m.container_id(tcx)).shrink_to_lo());
1021 match &terr {
1022 TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
1023 if trait_m.is_method() =>
1024 {
1025 let ty = trait_sig.inputs()[0];
1026 let sugg = get_self_string(ty, |ty| ty == impl_trait_ref.self_ty());
1027
1028 let (sig, body) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1032 let span = tcx
1033 .hir_body_param_idents(body)
1034 .zip(sig.decl.inputs.iter())
1035 .map(|(param_ident, ty)| {
1036 if let Some(param_ident) = param_ident {
1037 param_ident.span.to(ty.span)
1038 } else {
1039 ty.span
1040 }
1041 })
1042 .next()
1043 .unwrap_or(impl_err_span);
1044
1045 diag.span_suggestion_verbose(
1046 span,
1047 "change the self-receiver type to match the trait",
1048 sugg,
1049 Applicability::MachineApplicable,
1050 );
1051 }
1052 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
1053 if trait_sig.inputs().len() == *i {
1054 if let ImplItemKind::Fn(sig, _) =
1057 &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).kind
1058 && !sig.header.asyncness.is_async()
1059 {
1060 let msg = "change the output type to match the trait";
1061 let ap = Applicability::MachineApplicable;
1062 match sig.decl.output {
1063 hir::FnRetTy::DefaultReturn(sp) => {
1064 let sugg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" -> {0}", trait_sig.output()))
})format!(" -> {}", trait_sig.output());
1065 diag.span_suggestion_verbose(sp, msg, sugg, ap);
1066 }
1067 hir::FnRetTy::Return(hir_ty) => {
1068 let sugg = trait_sig.output();
1069 diag.span_suggestion_verbose(hir_ty.span, msg, sugg, ap);
1070 }
1071 };
1072 };
1073 } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
1074 {
let _guard = CratePrefixGuard::new();
diag.span_suggestion_verbose(impl_err_span,
"change the parameter type to match the trait", trait_ty,
Applicability::MachineApplicable)
};rustc_middle::ty::print::with_crate_prefix!(diag.span_suggestion_verbose(
1075 impl_err_span,
1076 "change the parameter type to match the trait",
1077 trait_ty,
1078 Applicability::MachineApplicable,
1079 ));
1080 }
1081 }
1082 _ => {}
1083 }
1084
1085 cause.span = impl_err_span;
1086
1087 let mut labels = ::alloc::vec::Vec::new()vec![];
1088 let mut context = ::alloc::vec::Vec::new()vec![];
1089 if let TypeError::ArgumentSorts(_, i) = &terr
1090 && let Some(ty) =
1091 tcx.fn_sig(trait_m.def_id).skip_binder().inputs_and_output().skip_binder().get(*i)
1092 && let ty::Param(param) = ty.kind()
1093 && let generics = tcx.generics_of(trait_m.def_id)
1096 && let param = generics.type_param(*param, tcx)
1097 && let GenericParamDefKind::Type { has_default: true, .. } = param.kind
1098 {
1099 context.push(tcx.def_span(trait_m.container_id(tcx)).shrink_to_lo());
1100
1101 let param_name = param.name;
1102 let msg = if let Some(ty) = trait_sig.inputs_and_output.get(*i)
1103 && infcx.can_eq(param_env, *ty, tcx.type_of(param.def_id).skip_binder())
1104 {
1105 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected to match the default of type parameter `{0}`",
param_name))
})format!("expected to match the default of type parameter `{param_name}`")
1106 } else if let Some(ty) = trait_sig.inputs_and_output.get(*i)
1107 && let ty::Param(p) = tcx.type_of(param.def_id).skip_binder().kind()
1108 && p.name == kw::SelfUpper
1109 && infcx.can_eq(param_env, *ty, impl_trait_ref.self_ty())
1110 {
1111 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected to match the `Self` default of type parameter `{0}`",
param_name))
})format!("expected to match the `Self` default of type parameter `{param_name}`")
1112 } else {
1113 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected to match type parameter `{0}`",
param_name))
})format!("expected to match type parameter `{param_name}`")
1114 };
1115 labels.push((tcx.def_span(param.def_id), msg));
1116 }
1117
1118 infcx.err_ctxt().note_type_err(
1119 &mut diag,
1120 &cause,
1121 trait_err_span.map(|sp| {
1122 let mut span: MultiSpan = sp.into();
1123 span.push_span_context(tcx.def_span(trait_m.container_id(tcx)).shrink_to_lo());
1124 span.push_span_context(tcx.def_span(trait_m.def_id).shrink_to_lo());
1125 for (sp, label) in labels {
1126 span.push_span_label(sp, label);
1127 }
1128 for sp in context {
1129 span.push_span_context(sp);
1130 }
1131 (span, Cow::from("type in trait"), false)
1132 }),
1133 Some(param_env.and(infer::ValuePairs::PolySigs(ExpectedFound {
1134 expected: ty::Binder::dummy(trait_sig),
1135 found: ty::Binder::dummy(impl_sig),
1136 }))),
1137 terr,
1138 false,
1139 None,
1140 );
1141
1142 diag.emit_err()
1143}
1144
1145fn check_region_bounds_on_impl_item<'tcx>(
1146 tcx: TyCtxt<'tcx>,
1147 impl_m: ty::AssocItem,
1148 trait_m: ty::AssocItem,
1149 delay: bool,
1150) -> Result<(), ErrorGuaranteed> {
1151 let impl_generics = tcx.generics_of(impl_m.def_id);
1152 let impl_params = impl_generics.own_counts().lifetimes;
1153
1154 let trait_generics = tcx.generics_of(trait_m.def_id);
1155 let trait_params = trait_generics.own_counts().lifetimes;
1156
1157 let Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span }) =
1158 check_number_of_early_bound_regions(
1159 tcx,
1160 impl_m.def_id.expect_local(),
1161 trait_m.def_id,
1162 impl_generics,
1163 impl_params,
1164 trait_generics,
1165 trait_params,
1166 )
1167 else {
1168 return Ok(());
1169 };
1170
1171 if !delay && let Some(guar) = check_region_late_boundedness(tcx, impl_m, trait_m) {
1172 return Err(guar);
1173 }
1174
1175 let reported = tcx
1176 .dcx()
1177 .create_err(LifetimesOrBoundsMismatchOnTrait {
1178 span,
1179 item_kind: impl_m.descr(),
1180 ident: impl_m.ident(tcx),
1181 generics_span,
1182 bounds_span,
1183 where_span,
1184 })
1185 .emit_err_unless_delay(delay);
1186
1187 Err(reported)
1188}
1189
1190pub(super) struct CheckNumberOfEarlyBoundRegionsError {
1191 pub(super) span: Span,
1192 pub(super) generics_span: Span,
1193 pub(super) bounds_span: Vec<Span>,
1194 pub(super) where_span: Option<Span>,
1195}
1196
1197pub(super) fn check_number_of_early_bound_regions<'tcx>(
1198 tcx: TyCtxt<'tcx>,
1199 impl_def_id: LocalDefId,
1200 trait_def_id: DefId,
1201 impl_generics: &Generics,
1202 impl_params: usize,
1203 trait_generics: &Generics,
1204 trait_params: usize,
1205) -> Result<(), CheckNumberOfEarlyBoundRegionsError> {
1206 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:1206",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(1206u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_generics")
}> =
::tracing::__macro_support::FieldName::new("trait_generics");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_generics")
}> =
::tracing::__macro_support::FieldName::new("impl_generics");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_generics)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_generics)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?trait_generics, ?impl_generics);
1207
1208 if trait_params == impl_params {
1218 return Ok(());
1219 }
1220
1221 let span = tcx
1222 .hir_get_generics(impl_def_id)
1223 .expect("expected impl item to have generics or else we can't compare them")
1224 .span;
1225
1226 let mut generics_span = tcx.def_span(trait_def_id);
1227 let mut bounds_span = ::alloc::vec::Vec::new()vec![];
1228 let mut where_span = None;
1229
1230 if let Some(trait_node) = tcx.hir_get_if_local(trait_def_id)
1231 && let Some(trait_generics) = trait_node.generics()
1232 {
1233 generics_span = trait_generics.span;
1234 for p in trait_generics.predicates {
1237 match p.kind {
1238 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1239 bounds,
1240 ..
1241 })
1242 | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1243 bounds,
1244 ..
1245 }) => {
1246 for b in *bounds {
1247 if let hir::GenericBound::Outlives(lt) = b {
1248 bounds_span.push(lt.ident.span);
1249 }
1250 }
1251 }
1252 }
1253 }
1254 if let Some(impl_node) = tcx.hir_get_if_local(impl_def_id.into())
1255 && let Some(impl_generics) = impl_node.generics()
1256 {
1257 let mut impl_bounds = 0;
1258 for p in impl_generics.predicates {
1259 match p.kind {
1260 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1261 bounds,
1262 ..
1263 })
1264 | hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1265 bounds,
1266 ..
1267 }) => {
1268 for b in *bounds {
1269 if let hir::GenericBound::Outlives(_) = b {
1270 impl_bounds += 1;
1271 }
1272 }
1273 }
1274 }
1275 }
1276 if impl_bounds == bounds_span.len() {
1277 bounds_span = ::alloc::vec::Vec::new()vec![];
1278 } else if impl_generics.has_where_clause_predicates {
1279 where_span = Some(impl_generics.where_clause_span);
1280 }
1281 }
1282 }
1283
1284 Err(CheckNumberOfEarlyBoundRegionsError { span, generics_span, bounds_span, where_span })
1285}
1286
1287#[allow(unused)]
1288enum LateEarlyMismatch<'tcx> {
1289 EarlyInImpl(DefId, DefId, ty::Region<'tcx>),
1290 LateInImpl(DefId, DefId, ty::Region<'tcx>),
1291}
1292
1293fn check_region_late_boundedness<'tcx>(
1294 tcx: TyCtxt<'tcx>,
1295 impl_m: ty::AssocItem,
1296 trait_m: ty::AssocItem,
1297) -> Option<ErrorGuaranteed> {
1298 if !impl_m.is_fn() {
1299 return None;
1300 }
1301
1302 let (infcx, param_env) = tcx
1303 .infer_ctxt()
1304 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, impl_m.def_id));
1305
1306 let impl_m_args = infcx.fresh_args_for_item(DUMMY_SP, impl_m.def_id);
1307 let impl_m_sig = tcx.fn_sig(impl_m.def_id).instantiate(tcx, impl_m_args).skip_norm_wip();
1308 let impl_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, impl_m_sig);
1309
1310 let trait_m_args = infcx.fresh_args_for_item(DUMMY_SP, trait_m.def_id);
1311 let trait_m_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_args).skip_norm_wip();
1312 let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_m_sig);
1313
1314 let ocx = ObligationCtxt::new(&infcx);
1315
1316 let Ok(()) = ocx.eq(
1321 &ObligationCause::dummy(),
1322 param_env,
1323 ty::Binder::dummy(trait_m_sig),
1324 ty::Binder::dummy(impl_m_sig),
1325 ) else {
1326 return None;
1327 };
1328
1329 let errors = ocx.try_evaluate_obligations();
1330 if !errors.no_errors() {
1331 return None;
1332 }
1333
1334 let mut mismatched = ::alloc::vec::Vec::new()vec![];
1335
1336 let impl_generics = tcx.generics_of(impl_m.def_id);
1337 for (id_arg, arg) in
1338 std::iter::zip(ty::GenericArgs::identity_for_item(tcx, impl_m.def_id), impl_m_args)
1339 {
1340 if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1341 && let ty::ReVar(vid) = r.kind()
1342 && let r = infcx
1343 .inner
1344 .borrow_mut()
1345 .unwrap_region_constraints()
1346 .shallow_resolve_region_var(tcx, vid)
1347 && let ty::ReLateParam(ty::LateParamRegion {
1348 kind: ty::LateParamRegionKind::Named(trait_param_def_id),
1349 ..
1350 }) = r.kind()
1351 && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1352 {
1353 mismatched.push(LateEarlyMismatch::EarlyInImpl(
1354 impl_generics.region_param(ebr, tcx).def_id,
1355 trait_param_def_id,
1356 id_arg.expect_region(),
1357 ));
1358 }
1359 }
1360
1361 let trait_generics = tcx.generics_of(trait_m.def_id);
1362 for (id_arg, arg) in
1363 std::iter::zip(ty::GenericArgs::identity_for_item(tcx, trait_m.def_id), trait_m_args)
1364 {
1365 if let ty::GenericArgKind::Lifetime(r) = arg.kind()
1366 && let ty::ReVar(vid) = r.kind()
1367 && let r = infcx
1368 .inner
1369 .borrow_mut()
1370 .unwrap_region_constraints()
1371 .shallow_resolve_region_var(tcx, vid)
1372 && let ty::ReLateParam(ty::LateParamRegion {
1373 kind: ty::LateParamRegionKind::Named(impl_param_def_id),
1374 ..
1375 }) = r.kind()
1376 && let ty::ReEarlyParam(ebr) = id_arg.expect_region().kind()
1377 {
1378 mismatched.push(LateEarlyMismatch::LateInImpl(
1379 impl_param_def_id,
1380 trait_generics.region_param(ebr, tcx).def_id,
1381 id_arg.expect_region(),
1382 ));
1383 }
1384 }
1385
1386 if mismatched.is_empty() {
1387 return None;
1388 }
1389
1390 let spans: Vec<_> = mismatched
1391 .iter()
1392 .map(|param| {
1393 let (LateEarlyMismatch::EarlyInImpl(impl_param_def_id, ..)
1394 | LateEarlyMismatch::LateInImpl(impl_param_def_id, ..)) = *param;
1395 tcx.def_span(impl_param_def_id)
1396 })
1397 .collect();
1398
1399 let mut diag = tcx
1400 .dcx()
1401 .struct_span_err(spans, "lifetime parameters do not match the trait definition")
1402 .with_note("lifetime parameters differ in whether they are early- or late-bound")
1403 .with_code(E0195);
1404 for mismatch in mismatched {
1405 match mismatch {
1406 LateEarlyMismatch::EarlyInImpl(
1407 impl_param_def_id,
1408 trait_param_def_id,
1409 early_bound_region,
1410 ) => {
1411 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![
1412 tcx.def_span(impl_param_def_id),
1413 tcx.def_span(trait_param_def_id),
1414 ]);
1415 multispan
1416 .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1417 multispan
1418 .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1419 multispan.push_span_label(
1420 tcx.def_span(impl_param_def_id),
1421 ::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)),
1422 );
1423 multispan.push_span_label(
1424 tcx.def_span(trait_param_def_id),
1425 ::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)),
1426 );
1427 if let Some(span) = find_region_in_clauses(tcx, impl_m.def_id, early_bound_region) {
1428 multispan.push_span_label(
1429 span,
1430 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
tcx.item_name(impl_param_def_id)))
})format!(
1431 "this lifetime bound makes `{}` early-bound",
1432 tcx.item_name(impl_param_def_id)
1433 ),
1434 );
1435 }
1436 diag.span_note(
1437 multispan,
1438 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
tcx.item_name(impl_param_def_id)))
})format!(
1439 "`{}` differs between the trait and impl",
1440 tcx.item_name(impl_param_def_id)
1441 ),
1442 );
1443 }
1444 LateEarlyMismatch::LateInImpl(
1445 impl_param_def_id,
1446 trait_param_def_id,
1447 early_bound_region,
1448 ) => {
1449 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![
1450 tcx.def_span(impl_param_def_id),
1451 tcx.def_span(trait_param_def_id),
1452 ]);
1453 multispan
1454 .push_span_label(tcx.def_span(tcx.parent(impl_m.def_id)), "in this impl...");
1455 multispan
1456 .push_span_label(tcx.def_span(tcx.parent(trait_m.def_id)), "in this trait...");
1457 multispan.push_span_label(
1458 tcx.def_span(impl_param_def_id),
1459 ::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)),
1460 );
1461 multispan.push_span_label(
1462 tcx.def_span(trait_param_def_id),
1463 ::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)),
1464 );
1465 if let Some(span) = find_region_in_clauses(tcx, trait_m.def_id, early_bound_region)
1466 {
1467 multispan.push_span_label(
1468 span,
1469 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this lifetime bound makes `{0}` early-bound",
tcx.item_name(trait_param_def_id)))
})format!(
1470 "this lifetime bound makes `{}` early-bound",
1471 tcx.item_name(trait_param_def_id)
1472 ),
1473 );
1474 }
1475 diag.span_note(
1476 multispan,
1477 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` differs between the trait and impl",
tcx.item_name(impl_param_def_id)))
})format!(
1478 "`{}` differs between the trait and impl",
1479 tcx.item_name(impl_param_def_id)
1480 ),
1481 );
1482 }
1483 }
1484 }
1485
1486 Some(diag.emit_err())
1487}
1488
1489fn find_region_in_clauses<'tcx>(
1490 tcx: TyCtxt<'tcx>,
1491 def_id: DefId,
1492 early_bound_region: ty::Region<'tcx>,
1493) -> Option<Span> {
1494 for (clause, span) in tcx.explicit_clauses_of(def_id).instantiate_identity(tcx) {
1495 if clause.skip_norm_wip().visit_with(&mut FindRegion(early_bound_region)).is_break() {
1496 return Some(span);
1497 }
1498 }
1499
1500 struct FindRegion<'tcx>(ty::Region<'tcx>);
1501 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindRegion<'tcx> {
1502 type Result = ControlFlow<()>;
1503 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
1504 if r == self.0 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
1505 }
1506 }
1507
1508 None
1509}
1510
1511{}
#[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("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(1511u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("terr")
}> =
::tracing::__macro_support::FieldName::new("terr");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("cause")
}> =
::tracing::__macro_support::FieldName::new("cause");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_m")
}> =
::tracing::__macro_support::FieldName::new("impl_m");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_m")
}> =
::tracing::__macro_support::FieldName::new("trait_m");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&terr)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_m)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_m)
as &dyn ::tracing::field::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))]
1512fn extract_spans_for_error_reporting<'tcx>(
1513 infcx: &infer::InferCtxt<'tcx>,
1514 terr: TypeError<'_>,
1515 cause: &ObligationCause<'tcx>,
1516 impl_m: ty::AssocItem,
1517 trait_m: ty::AssocItem,
1518) -> (Span, Option<Span>) {
1519 let tcx = infcx.tcx;
1520 let mut impl_args = {
1521 let (sig, _) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1522 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1523 };
1524
1525 let trait_args = trait_m.def_id.as_local().map(|def_id| {
1526 let (sig, _) = tcx.hir_expect_trait_item(def_id).expect_fn();
1527 sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
1528 });
1529
1530 match terr {
1531 TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1532 (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
1533 }
1534 _ => (cause.span, tcx.hir_span_if_local(trait_m.def_id)),
1535 }
1536}
1537
1538fn compare_self_type<'tcx>(
1539 tcx: TyCtxt<'tcx>,
1540 impl_m: ty::AssocItem,
1541 trait_m: ty::AssocItem,
1542 impl_trait_ref: ty::TraitRef<'tcx>,
1543 delay: bool,
1544) -> Result<(), ErrorGuaranteed> {
1545 let self_string = |method: ty::AssocItem| {
1554 let untransformed_self_ty = match method.container {
1555 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1556 impl_trait_ref.self_ty()
1557 }
1558 ty::AssocContainer::Trait => tcx.types.self_param,
1559 };
1560 let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip().input(0);
1561 let (infcx, param_env) = tcx
1562 .infer_ctxt()
1563 .build_with_typing_env(ty::TypingEnv::non_body_analysis(tcx, method.def_id));
1564 let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1565 let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
1566 get_self_string(self_arg_ty, can_eq_self)
1567 };
1568
1569 match (trait_m.is_method(), impl_m.is_method()) {
1570 (false, false) | (true, true) => {}
1571
1572 (false, true) => {
1573 let self_descr = self_string(impl_m);
1574 let impl_m_span = tcx.def_span(impl_m.def_id);
1575 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!(
1576 tcx.dcx(),
1577 impl_m_span,
1578 E0185,
1579 "method `{}` has a `{}` declaration in the impl, but not in the trait",
1580 trait_m.name(),
1581 self_descr
1582 );
1583 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"));
1584 if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1585 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}`"));
1586 } else {
1587 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1588 }
1589 return Err(err.emit_err_unless_delay(delay));
1590 }
1591
1592 (true, false) => {
1593 let self_descr = self_string(trait_m);
1594 let impl_m_span = tcx.def_span(impl_m.def_id);
1595 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!(
1596 tcx.dcx(),
1597 impl_m_span,
1598 E0186,
1599 "method `{}` has a `{}` declaration in the trait, but not in the impl",
1600 trait_m.name(),
1601 self_descr
1602 );
1603 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"));
1604 if let Some(span) = tcx.hir_span_if_local(trait_m.def_id) {
1605 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"));
1606 } else {
1607 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1608 }
1609
1610 return Err(err.emit_err_unless_delay(delay));
1611 }
1612 }
1613
1614 Ok(())
1615}
1616
1617fn compare_number_of_generics<'tcx>(
1639 tcx: TyCtxt<'tcx>,
1640 impl_: ty::AssocItem,
1641 trait_: ty::AssocItem,
1642 delay: bool,
1643) -> Result<(), ErrorGuaranteed> {
1644 let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
1645 let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();
1646
1647 if (trait_own_counts.types + trait_own_counts.consts)
1651 == (impl_own_counts.types + impl_own_counts.consts)
1652 {
1653 return Ok(());
1654 }
1655
1656 if trait_.is_impl_trait_in_trait() {
1661 tcx.dcx()
1664 .bug("errors comparing numbers of generics of trait/impl functions were not emitted");
1665 }
1666
1667 let matchings = [
1668 ("type", trait_own_counts.types, impl_own_counts.types),
1669 ("const", trait_own_counts.consts, impl_own_counts.consts),
1670 ];
1671
1672 let item_kind = impl_.descr();
1673
1674 let mut err_occurred = None;
1675 for (kind, trait_count, impl_count) in matchings {
1676 if impl_count != trait_count {
1677 let arg_spans = |item: &ty::AssocItem, generics: &hir::Generics<'_>| {
1678 let mut spans = generics
1679 .params
1680 .iter()
1681 .filter(|p| match p.kind {
1682 hir::GenericParamKind::Lifetime {
1683 kind: hir::LifetimeParamKind::Elided(_),
1684 } => {
1685 !item.is_fn()
1688 }
1689 _ => true,
1690 })
1691 .map(|p| p.span)
1692 .collect::<Vec<Span>>();
1693 if spans.is_empty() {
1694 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]
1695 }
1696 spans
1697 };
1698 let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1699 let trait_item = tcx.hir_expect_trait_item(def_id);
1700 let arg_spans: Vec<Span> = arg_spans(&trait_, trait_item.generics);
1701 let impl_trait_spans: Vec<Span> = trait_item
1702 .generics
1703 .params
1704 .iter()
1705 .filter_map(|p| match p.kind {
1706 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1707 _ => None,
1708 })
1709 .collect();
1710 (Some(arg_spans), impl_trait_spans)
1711 } else {
1712 let trait_span = tcx.hir_span_if_local(trait_.def_id);
1713 (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![])
1714 };
1715
1716 let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
1717 let impl_item_impl_trait_spans: Vec<Span> = impl_item
1718 .generics
1719 .params
1720 .iter()
1721 .filter_map(|p| match p.kind {
1722 GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1723 _ => None,
1724 })
1725 .collect();
1726 let spans = arg_spans(&impl_, impl_item.generics);
1727 let span = spans.first().copied();
1728
1729 let mut err = tcx.dcx().struct_span_err(
1730 spans,
1731 ::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!(
1732 "{} `{}` has {} {kind} parameter{} but its trait \
1733 declaration has {} {kind} parameter{}",
1734 item_kind,
1735 trait_.name(),
1736 impl_count,
1737 pluralize!(impl_count),
1738 trait_count,
1739 pluralize!(trait_count),
1740 kind = kind,
1741 ),
1742 );
1743 err.code(E0049);
1744
1745 let msg =
1746 ::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),);
1747 if let Some(spans) = trait_spans {
1748 let mut spans = spans.iter();
1749 if let Some(span) = spans.next() {
1750 err.span_label(*span, msg);
1751 }
1752 for span in spans {
1753 err.span_label(*span, "");
1754 }
1755 } else {
1756 err.span_label(tcx.def_span(trait_.def_id), msg);
1757 }
1758
1759 if let Some(span) = span {
1760 err.span_label(
1761 span,
1762 ::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),),
1763 );
1764 }
1765
1766 for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
1767 err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
1768 }
1769
1770 let guar = err.emit_err_unless_delay(delay);
1771 err_occurred = Some(guar);
1772 }
1773 }
1774
1775 if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
1776}
1777
1778fn compare_number_of_method_arguments<'tcx>(
1779 tcx: TyCtxt<'tcx>,
1780 impl_m: ty::AssocItem,
1781 trait_m: ty::AssocItem,
1782 delay: bool,
1783) -> Result<(), ErrorGuaranteed> {
1784 let impl_m_fty = tcx.fn_sig(impl_m.def_id);
1785 let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1786 let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
1787 let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1788
1789 if trait_number_args != impl_number_args {
1790 let trait_span = trait_m
1791 .def_id
1792 .as_local()
1793 .and_then(|def_id| {
1794 let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
1795 let pos = trait_number_args.saturating_sub(1);
1796 trait_m_sig.decl.inputs.get(pos).map(|arg| {
1797 if pos == 0 {
1798 arg.span
1799 } else {
1800 arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1801 }
1802 })
1803 })
1804 .or_else(|| tcx.hir_span_if_local(trait_m.def_id));
1805
1806 let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1807 let pos = impl_number_args.saturating_sub(1);
1808 let impl_span = impl_m_sig
1809 .decl
1810 .inputs
1811 .get(pos)
1812 .map(|arg| {
1813 if pos == 0 {
1814 arg.span
1815 } else {
1816 arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1817 }
1818 })
1819 .unwrap_or_else(|| tcx.def_span(impl_m.def_id));
1820
1821 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!(
1822 tcx.dcx(),
1823 impl_span,
1824 E0050,
1825 "method `{}` has {} but the declaration in trait `{}` has {}",
1826 trait_m.name(),
1827 potentially_plural_count(impl_number_args, "parameter"),
1828 tcx.def_path_str(trait_m.def_id),
1829 trait_number_args
1830 );
1831
1832 if let Some(trait_span) = trait_span {
1833 err.span_label(
1834 trait_span,
1835 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait requires {0}",
potentially_plural_count(trait_number_args, "parameter")))
})format!(
1836 "trait requires {}",
1837 potentially_plural_count(trait_number_args, "parameter")
1838 ),
1839 );
1840 } else {
1841 err.note_trait_signature(trait_m.name(), trait_m.signature(tcx));
1842 }
1843
1844 err.span_label(
1845 impl_span,
1846 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}, found {1}",
potentially_plural_count(trait_number_args, "parameter"),
impl_number_args))
})format!(
1847 "expected {}, found {}",
1848 potentially_plural_count(trait_number_args, "parameter"),
1849 impl_number_args
1850 ),
1851 );
1852
1853 if !trait_m.def_id.is_local() {
1855 let trait_sig = tcx.fn_sig(trait_m.def_id);
1856 let trait_arg_idents = tcx.fn_arg_idents(trait_m.def_id);
1857 let sm = tcx.sess.source_map();
1858 let impl_inputs_span = if let (Some(first), Some(last)) =
1862 (impl_m_sig.decl.inputs.first(), impl_m_sig.decl.inputs.last())
1863 {
1864 let arg_idents = tcx.fn_arg_idents(impl_m.def_id);
1868 let first_lo = arg_idents
1869 .get(0)
1870 .and_then(|id| id.map(|id| id.span.lo()))
1871 .unwrap_or(first.span.lo());
1872 Some(impl_m_sig.span.with_lo(first_lo).with_hi(last.span.hi()))
1873 } else {
1874 sm.span_to_snippet(impl_m_sig.span).ok().and_then(|s| {
1879 let right_paren = s.as_bytes().iter().rposition(|&b| b == b')')?;
1880 let pos = impl_m_sig.span.lo() + BytePos(right_paren as u32);
1881 Some(impl_m_sig.span.with_lo(pos).with_hi(pos))
1882 })
1883 };
1884 let suggestion = match trait_number_args.cmp(&impl_number_args) {
1885 Ordering::Greater => {
1886 let trait_inputs = trait_sig.skip_binder().inputs().skip_binder();
1890 let missing = trait_inputs
1891 .iter()
1892 .enumerate()
1893 .skip(impl_number_args)
1894 .map(|(idx, ty)| {
1895 let name = trait_arg_idents
1896 .get(idx)
1897 .and_then(|ident| *ident)
1898 .map(|ident| ident.to_string())
1899 .unwrap_or_else(|| "_".to_string());
1900 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", name, ty))
})format!("{name}: {ty}")
1901 })
1902 .collect::<Vec<_>>();
1903
1904 if missing.is_empty() {
1905 None
1906 } else {
1907 impl_inputs_span.map(|s| {
1908 let span = s.shrink_to_hi();
1909 let prefix = if impl_number_args == 0 { "" } else { ", " };
1910 let replacement = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}", missing.join(", "),
prefix))
})format!("{prefix}{}", missing.join(", "));
1911 (
1912 span,
1913 ::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!(
1914 "add the missing parameter{} from the trait",
1915 pluralize!(trait_number_args - impl_number_args)
1916 ),
1917 replacement,
1918 )
1919 })
1920 }
1921 }
1922 Ordering::Less => impl_inputs_span.and_then(|full| {
1923 let lo = if trait_number_args == 0 {
1927 full.lo()
1928 } else {
1929 impl_m_sig
1930 .decl
1931 .inputs
1932 .get(trait_number_args - 1)
1933 .map(|arg| arg.span.hi())?
1934 };
1935 let span = full.with_lo(lo);
1936 Some((
1937 span,
1938 ::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!(
1939 "remove the extra parameter{} to match the trait",
1940 pluralize!(impl_number_args - trait_number_args)
1941 ),
1942 String::new(),
1943 ))
1944 }),
1945 Ordering::Equal => ::core::panicking::unreachable_default_msg()unreachable!(),
1946 };
1947 if let Some((span, msg, replacement)) = suggestion {
1948 err.span_suggestion_verbose(span, msg, replacement, Applicability::MaybeIncorrect);
1949 }
1950 }
1951
1952 return Err(err.emit_err_unless_delay(delay));
1953 }
1954
1955 Ok(())
1956}
1957
1958fn compare_synthetic_generics<'tcx>(
1959 tcx: TyCtxt<'tcx>,
1960 impl_m: ty::AssocItem,
1961 trait_m: ty::AssocItem,
1962 delay: bool,
1963) -> Result<(), ErrorGuaranteed> {
1964 let mut error_found = None;
1970 let impl_m_generics = tcx.generics_of(impl_m.def_id);
1971 let trait_m_generics = tcx.generics_of(trait_m.def_id);
1972 let impl_m_type_params =
1973 impl_m_generics.own_params.iter().filter_map(|param| match param.kind {
1974 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1975 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1976 });
1977 let trait_m_type_params =
1978 trait_m_generics.own_params.iter().filter_map(|param| match param.kind {
1979 GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1980 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
1981 });
1982 for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
1983 iter::zip(impl_m_type_params, trait_m_type_params)
1984 {
1985 if impl_synthetic != trait_synthetic {
1986 let impl_def_id = impl_def_id.expect_local();
1987 let impl_span = tcx.def_span(impl_def_id);
1988 let trait_span = tcx.def_span(trait_def_id);
1989 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!(
1990 tcx.dcx(),
1991 impl_span,
1992 E0643,
1993 "method `{}` has incompatible signature for trait",
1994 trait_m.name()
1995 );
1996 err.span_label(trait_span, "declaration in trait here");
1997 if impl_synthetic {
1998 err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
2001 try {
2002 let new_name = tcx.opt_item_name(trait_def_id)?;
2006 let trait_m = trait_m.def_id.as_local()?;
2007 let trait_m = tcx.hir_expect_trait_item(trait_m);
2008
2009 let impl_m = impl_m.def_id.as_local()?;
2010 let impl_m = tcx.hir_expect_impl_item(impl_m);
2011
2012 let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
2015 let generics_span = impl_m.generics.span.substitute_dummy(new_generics_span);
2017 let new_generics =
2019 tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
2020
2021 err.multipart_suggestion(
2022 "try changing the `impl Trait` argument to a generic parameter",
2023 ::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![
2024 (impl_span, new_name.to_string()),
2026 (generics_span, new_generics),
2030 ],
2031 Applicability::MaybeIncorrect,
2032 );
2033 };
2034 } else {
2035 err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
2038 try {
2039 let impl_m = impl_m.def_id.as_local()?;
2040 let impl_m = tcx.hir_expect_impl_item(impl_m);
2041 let (sig, _) = impl_m.expect_fn();
2042 let input_tys = sig.decl.inputs;
2043
2044 struct Visitor(hir::def_id::LocalDefId);
2045 impl<'v> intravisit::Visitor<'v> for Visitor {
2046 type Result = ControlFlow<Span>;
2047 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) -> Self::Result {
2048 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
2049 && let Res::Def(DefKind::TyParam, def_id) = path.res
2050 && def_id == self.0.to_def_id()
2051 {
2052 ControlFlow::Break(ty.span)
2053 } else {
2054 intravisit::walk_ty(self, ty)
2055 }
2056 }
2057 }
2058
2059 let span = input_tys
2060 .iter()
2061 .find_map(|ty| Visitor(impl_def_id).visit_ty_unambig(ty).break_value())?;
2062
2063 let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
2064 let bounds = bounds.first()?.span().to(bounds.last()?.span());
2065 let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
2066
2067 err.multipart_suggestion(
2068 "try removing the generic parameter and using `impl Trait` instead",
2069 ::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![
2070 (impl_m.generics.span, String::new()),
2072 (span, format!("impl {bounds}")),
2074 ],
2075 Applicability::MaybeIncorrect,
2076 );
2077 };
2078 }
2079 error_found = Some(err.emit_err_unless_delay(delay));
2080 }
2081 }
2082 if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
2083}
2084
2085fn compare_generic_param_kinds<'tcx>(
2088 tcx: TyCtxt<'tcx>,
2089 impl_item: ty::AssocItem,
2090 trait_item: ty::AssocItem,
2091 delay: bool,
2092) -> Result<(), ErrorGuaranteed> {
2093 {
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());
2094
2095 let ty_const_params_of = |def_id| {
2096 tcx.generics_of(def_id).own_params.iter().filter(|param| {
2097 #[allow(non_exhaustive_omitted_patterns)] match param.kind {
GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. } =>
true,
_ => false,
}matches!(
2098 param.kind,
2099 GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
2100 )
2101 })
2102 };
2103
2104 for (param_impl, param_trait) in
2105 iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
2106 {
2107 use GenericParamDefKind::*;
2108 if match (¶m_impl.kind, ¶m_trait.kind) {
2109 (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
2110 (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
2113 (Lifetime { .. }, _) | (_, Lifetime { .. }) => {
2114 ::rustc_span::macros::bug_impl(None,
format_args!("lifetime params are expected to be filtered by `ty_const_params_of`"),
Location::caller())bug!("lifetime params are expected to be filtered by `ty_const_params_of`")
2115 }
2116 } {
2117 let param_impl_span = tcx.def_span(param_impl.def_id);
2118 let param_trait_span = tcx.def_span(param_trait.def_id);
2119
2120 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!(
2121 tcx.dcx(),
2122 param_impl_span,
2123 E0053,
2124 "{} `{}` has an incompatible generic parameter for trait `{}`",
2125 impl_item.descr(),
2126 trait_item.name(),
2127 tcx.def_path_str(tcx.parent(trait_item.def_id))
2128 );
2129
2130 let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
2131 Const { .. } => {
2132 ::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!(
2133 "{} const parameter of type `{}`",
2134 prefix,
2135 tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip()
2136 )
2137 }
2138 Type { .. } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} type parameter", prefix))
})format!("{prefix} type parameter"),
2139 Lifetime { .. } => ::rustc_span::macros::bug_impl(Some(tcx.def_span(param.def_id)),
format_args!("lifetime params are expected to be filtered by `ty_const_params_of`"),
Location::caller())span_bug!(
2140 tcx.def_span(param.def_id),
2141 "lifetime params are expected to be filtered by `ty_const_params_of`"
2142 ),
2143 };
2144
2145 let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
2146 err.span_context(trait_header_span);
2147 err.span_label(param_trait_span, make_param_message("expected", param_trait));
2148
2149 let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
2150 err.span_context(impl_header_span);
2151 err.span_label(param_impl_span, make_param_message("found", param_impl));
2152
2153 let guar = err.emit_err_unless_delay(delay);
2154 return Err(guar);
2155 }
2156 }
2157
2158 Ok(())
2159}
2160
2161fn compare_const_generic_param_types<'tcx>(
2164 tcx: TyCtxt<'tcx>,
2165 impl_item: ty::AssocItem,
2166 trait_item: ty::AssocItem,
2167 impl_trait_ref: ty::TraitRef<'tcx>,
2168 delay: bool,
2169) -> Result<(), ErrorGuaranteed> {
2170 {
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());
2171 use GenericParamDefKind::*;
2172
2173 let const_params_of = |def_id| {
2174 tcx.generics_of(def_id).own_params.iter().filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
Const { .. } => true,
_ => false,
}matches!(param.kind, Const { .. }))
2175 };
2176
2177 let trait_to_impl_args = ty::GenericArgs::identity_for_item(tcx, impl_item.def_id).rebase_onto(
2179 tcx,
2180 impl_item.container_id(tcx),
2181 impl_trait_ref.args,
2182 );
2183 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2184 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2185 let param_env = tcx.param_env(impl_item.def_id);
2186
2187 let param_iter =
2188 iter::zip(const_params_of(impl_item.def_id), const_params_of(trait_item.def_id));
2189
2190 for (param_impl, param_trait) in param_iter {
2191 let param_impl_ty_span = if impl_item.is_impl_trait_in_trait() {
2197 tcx.def_span(impl_item.def_id)
2198 } else {
2199 tcx.ty_span(param_impl.def_id.expect_local())
2200 };
2201
2202 let cause = ObligationCause::new(
2203 param_impl_ty_span,
2204 impl_item.def_id.expect_local(),
2205 ObligationCauseCode::CompareImplItem {
2206 impl_item_def_id: impl_item.def_id.expect_local(),
2207 trait_item_def_id: trait_item.def_id,
2208 kind: impl_item.kind,
2209 },
2210 );
2211
2212 let impl_ty =
2213 ocx.normalize(&cause, param_env, tcx.type_of(param_impl.def_id).instantiate_identity());
2214
2215 let trait_ty = ocx.normalize(
2216 &cause,
2217 param_env,
2218 tcx.type_of(param_trait.def_id).instantiate(tcx, trait_to_impl_args),
2219 );
2220
2221 match ocx.eq(&cause, param_env, trait_ty, impl_ty) {
2222 Ok(_) => {}
2226 Err(terr) => {
2227 let param_trait_ty_span =
2228 param_trait.def_id.as_local().map(|def_id| tcx.ty_span(def_id));
2229 let mut diag = {
tcx.dcx().struct_span_err(param_impl_ty_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` has an incompatible type for const generic parameter",
trait_item.descr(), trait_item.name()))
})).with_code(E0053)
}struct_span_code_err!(
2230 tcx.dcx(),
2231 param_impl_ty_span,
2232 E0053,
2233 "{} `{}` has an incompatible type for const generic parameter",
2234 trait_item.descr(),
2235 trait_item.name(),
2236 );
2237 infcx.err_ctxt().note_type_err(
2238 &mut diag,
2239 &cause,
2240 param_trait_ty_span
2241 .map(|span| (span.into(), Cow::from("type in trait"), false)),
2242 Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2243 expected: trait_ty.into(),
2244 found: impl_ty.into(),
2245 }))),
2246 terr,
2247 false,
2248 None,
2249 );
2250 let reported = diag.emit_err_unless_delay(delay);
2251 return Err(reported);
2252 }
2253 }
2254 }
2255
2256 if let TraitErrors::HasErrors(errors) = ocx.evaluate_obligations_error_on_ambiguity() {
2257 Err(infcx.err_ctxt().report_fulfillment_errors(errors))
2258 } else {
2259 Ok(())
2260 }
2261}
2262
2263fn compare_impl_const<'tcx>(
2264 tcx: TyCtxt<'tcx>,
2265 impl_const_item: ty::AssocItem,
2266 trait_const_item: ty::AssocItem,
2267 impl_trait_ref: ty::TraitRef<'tcx>,
2268) -> Result<(), ErrorGuaranteed> {
2269 compare_const_directness(tcx, impl_const_item, trait_const_item)?;
2270 compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
2271 compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
2272 compare_const_generic_param_types(
2273 tcx,
2274 impl_const_item,
2275 trait_const_item,
2276 impl_trait_ref,
2277 false,
2278 )?;
2279 check_region_bounds_on_impl_item(tcx, impl_const_item, trait_const_item, false)?;
2280 compare_const_clause_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
2281}
2282
2283pub(super) fn compare_const_directness<'tcx>(
2284 tcx: TyCtxt<'tcx>,
2285 impl_const_item: ty::AssocItem,
2286 trait_const_item: ty::AssocItem,
2287) -> Result<(), ErrorGuaranteed> {
2288 let trait_is_gca = tcx.is_always_gca(trait_const_item.def_id);
2289 let impl_is_gca = tcx.const_of_item(impl_const_item.def_id).is_some();
2290
2291 if trait_is_gca == impl_is_gca {
2292 return Ok(());
2293 }
2294 if tcx.features().gca_const_items() && !trait_is_gca && impl_is_gca {
2296 return Ok(());
2297 }
2298
2299 let guar = if trait_is_gca {
2300 tcx.dcx()
2301 .struct_span_err(
2302 tcx.def_span(impl_const_item.def_id),
2303 "implementation of a `#[rustc_always_gca]` must have a `gca!` RHS",
2304 )
2305 .with_span_note(
2306 tcx.def_span(trait_const_item.def_id),
2307 "trait declaration of const is marked as `#[rustc_always_gca]`",
2308 )
2309 .emit_err()
2310 } else {
2311 tcx.dcx()
2312 .struct_span_err(
2313 tcx.def_span(impl_const_item.def_id),
2314 "implementation of a regular const cannot have a `gca!` RHS",
2315 )
2316 .with_span_note(
2317 tcx.def_span(trait_const_item.def_id),
2318 "trait declaration of const is not marked as `#[rustc_always_gca]`",
2319 )
2320 .emit_err()
2321 };
2322 Err(guar)
2323}
2324
2325{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("compare_const_clause_entailment",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2329u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_ct")
}> =
::tracing::__macro_support::FieldName::new("impl_ct");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ct")
}> =
::tracing::__macro_support::FieldName::new("trait_ct");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("impl_trait_ref");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ct)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ct)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
as &dyn ::tracing::field::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_clauses = tcx.clauses_of(impl_ct.def_id);
let trait_ct_clauses = tcx.clauses_of(trait_ct.def_id);
let impl_clauses =
tcx.clauses_of(impl_ct_clauses.parent.unwrap());
let mut hybrid_clauses =
impl_clauses.instantiate_identity(tcx).clauses;
hybrid_clauses.extend(trait_ct_clauses.instantiate_own(tcx,
trait_to_impl_args).map(|(clause, _)| clause));
let hybrid_clauses =
hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
let param_env =
traits::normalize_param_env_or_error(tcx,
hybrid_clauses.collect(),
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_clauses.instantiate_own_identity();
for (clause, span) in impl_ct_own_bounds {
let cause = ObligationCause::misc(span, impl_ct_def_id);
let clause = ocx.normalize(&cause, param_env, clause);
let cause =
ObligationCause::new(span, impl_ct_def_id, code.clone());
ocx.register_obligation(traits::Obligation::new(tcx, cause,
param_env, clause));
}
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 /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/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("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/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(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_ty")
}> =
::tracing::__macro_support::FieldName::new("impl_ty");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
as &dyn ::tracing::field::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 /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2397",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2397u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ty")
}> =
::tracing::__macro_support::FieldName::new("trait_ty");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
as &dyn ::tracing::field::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 /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2402",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2402u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_ty")
}> =
::tracing::__macro_support::FieldName::new("impl_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ty")
}> =
::tracing::__macro_support::FieldName::new("trait_ty");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
as &dyn ::tracing::field::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)
};
diag.span_context(tcx.def_span(impl_ct.container_id(tcx)).shrink_to_lo());
diag.span_context(tcx.def_span(impl_ct.def_id).shrink_to_lo());
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|
{
let mut span: MultiSpan = span.into();
span.push_span_context(tcx.def_span(trait_ct.container_id(tcx)).shrink_to_lo());
span.push_span_context(tcx.def_span(trait_ct.def_id).shrink_to_lo());
(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_err());
};
let errors = ocx.evaluate_obligations_error_on_ambiguity();
if let TraitErrors::HasErrors(errors) = errors {
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))]
2330fn compare_const_clause_entailment<'tcx>(
2331 tcx: TyCtxt<'tcx>,
2332 impl_ct: ty::AssocItem,
2333 trait_ct: ty::AssocItem,
2334 impl_trait_ref: ty::TraitRef<'tcx>,
2335) -> Result<(), ErrorGuaranteed> {
2336 let impl_ct_def_id = impl_ct.def_id.expect_local();
2337 let impl_ct_span = tcx.def_span(impl_ct_def_id);
2338
2339 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id).rebase_onto(
2345 tcx,
2346 impl_ct.container_id(tcx),
2347 impl_trait_ref.args,
2348 );
2349
2350 let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();
2353
2354 let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
2355 let code = ObligationCauseCode::CompareImplItem {
2356 impl_item_def_id: impl_ct_def_id,
2357 trait_item_def_id: trait_ct.def_id,
2358 kind: impl_ct.kind,
2359 };
2360 let mut cause = ObligationCause::new(impl_ct_span, impl_ct_def_id, code.clone());
2361
2362 let impl_ct_clauses = tcx.clauses_of(impl_ct.def_id);
2363 let trait_ct_clauses = tcx.clauses_of(trait_ct.def_id);
2364
2365 let impl_clauses = tcx.clauses_of(impl_ct_clauses.parent.unwrap());
2368 let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
2369 hybrid_clauses.extend(
2370 trait_ct_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(clause, _)| clause),
2371 );
2372 let hybrid_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
2373
2374 let param_env = traits::normalize_param_env_or_error(
2375 tcx,
2376 hybrid_clauses.collect(),
2377 ObligationCause::misc(impl_ct_span, impl_ct_def_id),
2378 );
2379
2380 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2381 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2382
2383 let impl_ct_own_bounds = impl_ct_clauses.instantiate_own_identity();
2384 for (clause, span) in impl_ct_own_bounds {
2385 let cause = ObligationCause::misc(span, impl_ct_def_id);
2386 let clause = ocx.normalize(&cause, param_env, clause);
2387
2388 let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
2389 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
2390 }
2391
2392 let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
2394 debug!(?impl_ty);
2395
2396 let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
2397 debug!(?trait_ty);
2398
2399 let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
2400
2401 if let Err(terr) = err {
2402 debug!(?impl_ty, ?trait_ty);
2403
2404 let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
2406 cause.span = ty.span;
2407
2408 let mut diag = struct_span_code_err!(
2409 tcx.dcx(),
2410 cause.span,
2411 E0326,
2412 "implemented const `{}` has an incompatible type for trait",
2413 trait_ct.name()
2414 );
2415 diag.span_context(tcx.def_span(impl_ct.container_id(tcx)).shrink_to_lo());
2416 diag.span_context(tcx.def_span(impl_ct.def_id).shrink_to_lo());
2417
2418 let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
2419 let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
2421 ty.span
2422 });
2423
2424 infcx.err_ctxt().note_type_err(
2425 &mut diag,
2426 &cause,
2427 trait_c_span.map(|span| {
2428 let mut span: MultiSpan = span.into();
2429 span.push_span_context(tcx.def_span(trait_ct.container_id(tcx)).shrink_to_lo());
2430 span.push_span_context(tcx.def_span(trait_ct.def_id).shrink_to_lo());
2431 (span, Cow::from("type in trait"), false)
2432 }),
2433 Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
2434 expected: trait_ty.into(),
2435 found: impl_ty.into(),
2436 }))),
2437 terr,
2438 false,
2439 None,
2440 );
2441 return Err(diag.emit_err());
2442 };
2443
2444 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2447 if let TraitErrors::HasErrors(errors) = errors {
2448 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2449 }
2450
2451 ocx.resolve_regions_and_report_errors(impl_ct_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("compare_impl_ty",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2454u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_ty")
}> =
::tracing::__macro_support::FieldName::new("impl_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ty")
}> =
::tracing::__macro_support::FieldName::new("trait_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("impl_trait_ref");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
as &dyn ::tracing::field::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)?;
compare_const_generic_param_types(tcx, impl_ty, trait_ty,
impl_trait_ref, false)?;
check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
compare_type_clause_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))]
2455fn compare_impl_ty<'tcx>(
2456 tcx: TyCtxt<'tcx>,
2457 impl_ty: ty::AssocItem,
2458 trait_ty: ty::AssocItem,
2459 impl_trait_ref: ty::TraitRef<'tcx>,
2460) -> Result<(), ErrorGuaranteed> {
2461 compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
2462 compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
2463 compare_const_generic_param_types(tcx, impl_ty, trait_ty, impl_trait_ref, false)?;
2464 check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
2465 compare_type_clause_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
2466 check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)
2467}
2468
2469{}
#[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_clause_entailment",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2471u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_ty")
}> =
::tracing::__macro_support::FieldName::new("impl_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ty")
}> =
::tracing::__macro_support::FieldName::new("trait_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("impl_trait_ref");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
as &dyn ::tracing::field::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_clauses = tcx.clauses_of(impl_ty.def_id);
let trait_ty_clauses = tcx.clauses_of(trait_ty.def_id);
let impl_ty_own_bounds =
impl_ty_clauses.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 /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2499",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2499u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_to_impl_args")
}> =
::tracing::__macro_support::FieldName::new("trait_to_impl_args");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_to_impl_args)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let impl_clauses =
tcx.clauses_of(impl_ty_clauses.parent.unwrap());
let mut hybrid_clauses =
impl_clauses.instantiate_identity(tcx).clauses;
hybrid_clauses.extend(trait_ty_clauses.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 /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2508",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2508u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("hybrid_clauses")
}> =
::tracing::__macro_support::FieldName::new("hybrid_clauses");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hybrid_clauses)
as &dyn ::tracing::field::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_clauses.extend(tcx.const_conditions(impl_ty_clauses.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_clauses =
hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
let param_env =
traits::normalize_param_env_or_error(tcx,
hybrid_clauses.collect(), normalize_cause);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2533",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2533u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param_env")
}> =
::tracing::__macro_support::FieldName::new("param_env");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_env)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let infcx =
tcx.infer_ctxt().build(TypingMode::non_body_analysis());
let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
for (clause, span) in impl_ty_own_bounds {
let cause = ObligationCause::misc(span, impl_ty_def_id);
let clause = ocx.normalize(&cause, param_env, clause);
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, clause));
}
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 let TraitErrors::HasErrors(errors) = errors {
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))]
2472fn compare_type_clause_entailment<'tcx>(
2473 tcx: TyCtxt<'tcx>,
2474 impl_ty: ty::AssocItem,
2475 trait_ty: ty::AssocItem,
2476 impl_trait_ref: ty::TraitRef<'tcx>,
2477) -> Result<(), ErrorGuaranteed> {
2478 let impl_def_id = impl_ty.container_id(tcx);
2479 let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id).rebase_onto(
2480 tcx,
2481 impl_def_id,
2482 impl_trait_ref.args,
2483 );
2484
2485 let impl_ty_clauses = tcx.clauses_of(impl_ty.def_id);
2486 let trait_ty_clauses = tcx.clauses_of(trait_ty.def_id);
2487
2488 let impl_ty_own_bounds = impl_ty_clauses.instantiate_own_identity();
2489 if impl_ty_own_bounds.len() == 0 {
2491 return Ok(());
2493 }
2494
2495 let impl_ty_def_id = impl_ty.def_id.expect_local();
2499 debug!(?trait_to_impl_args);
2500
2501 let impl_clauses = tcx.clauses_of(impl_ty_clauses.parent.unwrap());
2504 let mut hybrid_clauses = impl_clauses.instantiate_identity(tcx).clauses;
2505 hybrid_clauses.extend(
2506 trait_ty_clauses.instantiate_own(tcx, trait_to_impl_args).map(|(predicate, _)| predicate),
2507 );
2508 debug!(?hybrid_clauses);
2509
2510 let impl_ty_span = tcx.def_span(impl_ty_def_id);
2511 let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
2512
2513 let is_conditionally_const = tcx.is_conditionally_const(impl_ty.def_id);
2514 if is_conditionally_const {
2515 hybrid_clauses.extend(
2518 tcx.const_conditions(impl_ty_clauses.parent.unwrap())
2519 .instantiate_identity(tcx)
2520 .into_iter()
2521 .chain(
2522 tcx.const_conditions(trait_ty.def_id).instantiate_own(tcx, trait_to_impl_args),
2523 )
2524 .map(|(trait_ref, _)| {
2525 trait_ref.to_host_effect_clause(tcx, ty::BoundConstness::Maybe)
2526 }),
2527 );
2528 }
2529
2530 let hybrid_clauses = hybrid_clauses.into_iter().map(Unnormalized::skip_norm_wip);
2531 let param_env =
2532 traits::normalize_param_env_or_error(tcx, hybrid_clauses.collect(), normalize_cause);
2533 debug!(?param_env);
2534
2535 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2536 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2537
2538 for (clause, span) in impl_ty_own_bounds {
2539 let cause = ObligationCause::misc(span, impl_ty_def_id);
2540 let clause = ocx.normalize(&cause, param_env, clause);
2541
2542 let cause = ObligationCause::new(
2543 span,
2544 impl_ty_def_id,
2545 ObligationCauseCode::CompareImplItem {
2546 impl_item_def_id: impl_ty.def_id.expect_local(),
2547 trait_item_def_id: trait_ty.def_id,
2548 kind: impl_ty.kind,
2549 },
2550 );
2551 ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, clause));
2552 }
2553
2554 if is_conditionally_const {
2555 let impl_ty_own_const_conditions =
2557 tcx.const_conditions(impl_ty.def_id).instantiate_own_identity();
2558 for (const_condition, span) in impl_ty_own_const_conditions {
2559 let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id);
2560 let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition);
2561
2562 let cause = ObligationCause::new(
2563 span,
2564 impl_ty_def_id,
2565 ObligationCauseCode::CompareImplItem {
2566 impl_item_def_id: impl_ty_def_id,
2567 trait_item_def_id: trait_ty.def_id,
2568 kind: impl_ty.kind,
2569 },
2570 );
2571 ocx.register_obligation(traits::Obligation::new(
2572 tcx,
2573 cause,
2574 param_env,
2575 const_condition.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2576 ));
2577 }
2578 }
2579
2580 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2583 if let TraitErrors::HasErrors(errors) = errors {
2584 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2585 return Err(reported);
2586 }
2587
2588 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, [])
2591}
2592
2593{}
#[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("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2606u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ty")
}> =
::tracing::__macro_support::FieldName::new("trait_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_ty")
}> =
::tracing::__macro_support::FieldName::new("impl_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("impl_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("impl_trait_ref");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_trait_ref)
as &dyn ::tracing::field::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 /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2618",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2618u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param_env")
}> =
::tracing::__macro_support::FieldName::new("param_env");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_env)
as &dyn ::tracing::field::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_span::macros::bug_impl(Some(tcx.def_span(impl_ty_def_id)),
format_args!("cannot call `check_type_bounds` on item: {0:?}",
item), Location::caller()),
}
};
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 /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2667",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2667u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("concrete_ty_bound")
}> =
::tracing::__macro_support::FieldName::new("concrete_ty_bound");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&concrete_ty_bound)
as &dyn ::tracing::field::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 /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs:2690",
"rustc_hir_analysis::check::compare_impl_item",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs"),
::tracing_core::__macro_support::Option::Some(2690u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::compare_impl_item"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item_bounds")
}> =
::tracing::__macro_support::FieldName::new("item_bounds");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligations)
as &dyn ::tracing::field::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 let TraitErrors::HasErrors(errors) = errors {
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))]
2607pub(super) fn check_type_bounds<'tcx>(
2608 tcx: TyCtxt<'tcx>,
2609 trait_ty: ty::AssocItem,
2610 impl_ty: ty::AssocItem,
2611 impl_trait_ref: ty::TraitRef<'tcx>,
2612) -> Result<(), ErrorGuaranteed> {
2613 tcx.ensure_result().coherent_trait(impl_trait_ref.def_id)?;
2616
2617 let param_env = tcx.param_env(impl_ty.def_id);
2618 debug!(?param_env);
2619
2620 let container_id = impl_ty.container_id(tcx);
2621 let impl_ty_def_id = impl_ty.def_id.expect_local();
2622 let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
2623 let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2624
2625 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2626 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2627
2628 let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2632 tcx.def_span(impl_ty_def_id)
2633 } else {
2634 match tcx.hir_node_by_def_id(impl_ty_def_id) {
2635 hir::Node::TraitItem(hir::TraitItem {
2636 kind: hir::TraitItemKind::Type(_, Some(ty)),
2637 ..
2638 }) => ty.span,
2639 hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
2640 item => span_bug!(
2641 tcx.def_span(impl_ty_def_id),
2642 "cannot call `check_type_bounds` on item: {item:?}",
2643 ),
2644 }
2645 };
2646 let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
2647
2648 let normalize_cause = ObligationCause::new(
2649 impl_ty_span,
2650 impl_ty_def_id,
2651 ObligationCauseCode::CheckAssociatedTypeBounds {
2652 impl_item_def_id: impl_ty.def_id.expect_local(),
2653 trait_item_def_id: trait_ty.def_id,
2654 },
2655 );
2656 let mk_cause = |span: Span| {
2657 let code = ObligationCauseCode::WhereClause(trait_ty.def_id, span);
2658 ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2659 };
2660
2661 let mut obligations: Vec<_> = util::elaborate(
2662 tcx,
2663 tcx.explicit_item_bounds(trait_ty.def_id)
2664 .iter_instantiated_copied(tcx, rebased_args)
2665 .map(Unnormalized::skip_norm_wip)
2666 .map(|(concrete_ty_bound, span)| {
2667 debug!(?concrete_ty_bound);
2668 traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2669 }),
2670 )
2671 .collect();
2672
2673 if tcx.is_conditionally_const(impl_ty_def_id) {
2675 obligations.extend(util::elaborate(
2676 tcx,
2677 tcx.explicit_implied_const_bounds(trait_ty.def_id)
2678 .iter_instantiated_copied(tcx, rebased_args)
2679 .map(Unnormalized::skip_norm_wip)
2680 .map(|(c, span)| {
2681 traits::Obligation::new(
2682 tcx,
2683 mk_cause(span),
2684 param_env,
2685 c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
2686 )
2687 }),
2688 ));
2689 }
2690 debug!(item_bounds=?obligations);
2691
2692 let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
2697 for obligation in &mut obligations {
2698 match ocx.deeply_normalize(
2699 &normalize_cause,
2700 normalize_param_env,
2701 Unnormalized::new_wip(obligation.predicate),
2702 ) {
2703 Ok(pred) => obligation.predicate = pred,
2704 Err(e) => {
2705 return Err(infcx.err_ctxt().report_fulfillment_errors(e));
2706 }
2707 }
2708 }
2709
2710 ocx.register_obligations(obligations);
2713 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2714 if let TraitErrors::HasErrors(errors) = errors {
2715 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
2716 return Err(reported);
2717 }
2718
2719 ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
2722}
2723
2724fn param_env_with_gat_bounds<'tcx>(
2772 tcx: TyCtxt<'tcx>,
2773 impl_ty: ty::AssocItem,
2774 impl_trait_ref: ty::TraitRef<'tcx>,
2775) -> ty::ParamEnv<'tcx> {
2776 let mut param_env = tcx.param_env(impl_ty.def_id).into_builder(tcx);
2777 let container_id = impl_ty.container_id(tcx);
2778
2779 let impl_tys_to_install = match impl_ty.kind {
2784 ty::AssocKind::Type {
2785 data:
2786 ty::AssocTypeData::Rpitit(
2787 ty::ImplTraitInTraitData::Impl { fn_def_id }
2788 | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
2789 ),
2790 } => tcx
2791 .associated_types_for_impl_traits_in_associated_fn(fn_def_id)
2792 .iter()
2793 .map(|def_id| tcx.associated_item(*def_id))
2794 .collect(),
2795 _ => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[impl_ty]))vec![impl_ty],
2796 };
2797
2798 for impl_ty in impl_tys_to_install {
2799 let trait_ty = match impl_ty.container {
2800 ty::AssocContainer::InherentImpl => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!(),
2801 ty::AssocContainer::Trait => impl_ty,
2802 ty::AssocContainer::TraitImpl(Err(_)) => continue,
2803 ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) => {
2804 tcx.associated_item(trait_item_def_id)
2805 }
2806 };
2807
2808 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind<'tcx>; 8]> =
2809 smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len());
2810 let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id)
2812 .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind {
2813 GenericParamDefKind::Type { .. } => {
2814 let kind = ty::BoundTyKind::Param(param.def_id);
2815 let bound_var = ty::BoundVariableKind::Ty(kind);
2816 bound_vars.push(bound_var);
2817 Ty::new_bound(
2818 tcx,
2819 ty::INNERMOST,
2820 ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
2821 )
2822 .into()
2823 }
2824 GenericParamDefKind::Lifetime => {
2825 let kind = ty::BoundRegionKind::Named(param.def_id);
2826 let bound_var = ty::BoundVariableKind::Region(kind);
2827 bound_vars.push(bound_var);
2828 ty::Region::new_bound(
2829 tcx,
2830 ty::INNERMOST,
2831 ty::BoundRegion {
2832 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
2833 kind,
2834 },
2835 )
2836 .into()
2837 }
2838 GenericParamDefKind::Const { .. } => {
2839 let bound_var = ty::BoundVariableKind::Const;
2840 bound_vars.push(bound_var);
2841 ty::Const::new_bound(
2842 tcx,
2843 ty::INNERMOST,
2844 ty::BoundConst::new(ty::BoundVar::from_usize(bound_vars.len() - 1)),
2845 )
2846 .into()
2847 }
2848 });
2849 let normalize_impl_ty =
2859 tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args).skip_norm_wip();
2860 let rebased_args =
2861 normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2862 let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2863
2864 match normalize_impl_ty.kind() {
2865 &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
2866 if def_id == trait_ty.def_id && args == rebased_args =>
2867 {
2868 }
2874 _ => param_env.add_clause(
2875 ty::Binder::bind_with_vars(
2876 ty::ProjectionClause {
2877 projection_term: ty::AliasTerm::new(
2878 tcx,
2879 ty::AliasTermKind::ProjectionTy { def_id: trait_ty.def_id },
2880 rebased_args,
2881 ),
2882 term: normalize_impl_ty.into(),
2883 },
2884 bound_vars,
2885 )
2886 .upcast(tcx),
2887 ),
2888 };
2889 }
2890
2891 param_env.build()
2892}
2893
2894fn try_report_async_mismatch<'tcx>(
2897 tcx: TyCtxt<'tcx>,
2898 infcx: &InferCtxt<'tcx>,
2899 errors: &[FulfillmentError<'tcx>],
2900 trait_m: ty::AssocItem,
2901 impl_m: ty::AssocItem,
2902 impl_sig: ty::FnSig<'tcx>,
2903) -> Result<(), ErrorGuaranteed> {
2904 if !tcx.asyncness(trait_m.def_id).is_async() {
2905 return Ok(());
2906 }
2907
2908 let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id: async_future_def_id }, .. }) =
2909 *tcx.fn_sig(trait_m.def_id).skip_binder().skip_binder().output().kind()
2910 else {
2911 ::rustc_span::macros::bug_impl(None,
format_args!("expected `async fn` to return an RPITIT"),
Location::caller());bug!("expected `async fn` to return an RPITIT");
2912 };
2913
2914 for error in errors {
2915 if let ObligationCauseCode::WhereClause(def_id, _) = *error.root_obligation.cause.code()
2916 && def_id == async_future_def_id
2917 && let Some(proj) = error.root_obligation.predicate.as_projection_clause()
2918 && let Some(proj) = proj.no_bound_vars()
2919 && infcx.can_eq(
2920 error.root_obligation.param_env,
2921 proj.term.expect_type(),
2922 impl_sig.output(),
2923 )
2924 {
2925 return Err(tcx.sess.dcx().emit_err(MethodShouldReturnFuture {
2928 span: tcx.def_span(impl_m.def_id),
2929 method_name: tcx.item_ident(impl_m.def_id),
2930 trait_item_span: tcx.hir_span_if_local(trait_m.def_id),
2931 }));
2932 }
2933 }
2934
2935 Ok(())
2936}