1//! Logic and data structures related to impl specialization, explained in
2//! greater detail below.
3//!
4//! At the moment, this implementation support only the simple "chain" rule:
5//! If any two impls overlap, one must be a strict subset of the other.
6//!
7//! See the [rustc dev guide] for a bit more detail on how specialization
8//! fits together with the rest of the trait machinery.
9//!
10//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/specialization.html
1112pub mod specialization_graph;
1314use rustc_data_structures::fx::FxIndexSet;
15use rustc_errors::codes::*;
16use rustc_errors::{Diag, EmissionGuarantee};
17use rustc_hir::def_id::{DefId, LocalDefId};
18use rustc_infer::traits::Obligation;
19use rustc_lint_defs::builtin::COHERENCE_LEAK_CHECK;
20use rustc_middle::bug;
21use rustc_middle::query::LocalCrate;
22use rustc_middle::traits::query::NoSolution;
23use rustc_middle::ty::fast_reject::{self, TreatParams};
24use rustc_middle::ty::print::PrintTraitRefExtas _;
25use rustc_middle::ty::{
26self, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized,
27};
28use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, sym};
29use specialization_graph::GraphExt;
30use tracing::{debug, instrument};
3132use crate::diagnostics::NegativePositiveConflict;
33use crate::error_reporting::traits::to_pretty_impl_header;
34use crate::infer::{InferCtxt, TyCtxtInferExt};
35use crate::traits::select::IntercrateAmbiguityCause;
36use crate::traits::{
37FutureCompatOverlapErrorKind, ObligationCause, ObligationCtxt, coherence,
38predicates_for_generics,
39};
4041/// Information pertinent to an overlapping impl error.
42#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for OverlapError<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["with_impl", "trait_ref", "self_ty",
"intercrate_ambiguity_causes", "involves_placeholder",
"overflowing_predicates"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.with_impl, &self.trait_ref, &self.self_ty,
&self.intercrate_ambiguity_causes,
&self.involves_placeholder, &&self.overflowing_predicates];
::core::fmt::Formatter::debug_struct_fields_finish(f, "OverlapError",
names, values)
}
}Debug)]
43pub struct OverlapError<'tcx> {
44pub with_impl: DefId,
45pub trait_ref: ty::TraitRef<'tcx>,
46pub self_ty: Option<Ty<'tcx>>,
47pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
48pub involves_placeholder: bool,
49pub overflowing_predicates: Vec<ty::Predicate<'tcx>>,
50}
5152/// Given the generic parameters for the requested impl, translate it to the generic parameters
53/// appropriate for the actual item definition (whether it be in that impl,
54/// a parent impl, or the trait).
55///
56/// When we have selected one impl, but are actually using item definitions from
57/// a parent impl providing a default, we need a way to translate between the
58/// type parameters of the two impls. Here the `source_impl` is the one we've
59/// selected, and `source_args` is its generic parameters.
60/// And `target_node` is the impl/trait we're actually going to get the
61/// definition from. The resulting instantiation will map from `target_node`'s
62/// generics to `source_impl`'s generics as instantiated by `source_args`.
63///
64/// For example, consider the following scenario:
65///
66/// ```ignore (illustrative)
67/// trait Foo { ... }
68/// impl<T, U> Foo for (T, U) { ... } // target impl
69/// impl<V> Foo for (V, V) { ... } // source impl
70/// ```
71///
72/// Suppose we have selected "source impl" with `V` instantiated with `u32`.
73/// This function will produce an instantiation with `T` and `U` both mapping to `u32`.
74///
75/// where-clauses add some trickiness here, because they can be used to "define"
76/// an argument indirectly:
77///
78/// ```ignore (illustrative)
79/// impl<'a, I, T: 'a> Iterator for Cloned<I>
80/// where I: Iterator<Item = &'a T>, T: Clone
81/// ```
82///
83/// In a case like this, the instantiation for `T` is determined indirectly,
84/// through associated type projection. We deal with such cases by using
85/// *fulfillment* to relate the two impls, requiring that all projections are
86/// resolved.
87pub fn translate_args<'tcx>(
88 infcx: &InferCtxt<'tcx>,
89 param_env: ty::ParamEnv<'tcx>,
90 source_impl: DefId,
91 source_args: GenericArgsRef<'tcx>,
92 target_node: specialization_graph::Node,
93) -> GenericArgsRef<'tcx> {
94translate_args_with_cause(
95infcx,
96param_env,
97source_impl,
98source_args,
99target_node,
100&ObligationCause::dummy(),
101 )
102}
103104/// Like [translate_args], but obligations from the parent implementation
105/// are registered with the provided `ObligationCause`.
106///
107/// This is for reporting *region* errors from those bounds. Type errors should
108/// not happen because the specialization graph already checks for those, and
109/// will result in an ICE.
110pub fn translate_args_with_cause<'tcx>(
111 infcx: &InferCtxt<'tcx>,
112 param_env: ty::ParamEnv<'tcx>,
113 source_impl: DefId,
114 source_args: GenericArgsRef<'tcx>,
115 target_node: specialization_graph::Node,
116 cause: &ObligationCause<'tcx>,
117) -> GenericArgsRef<'tcx> {
118{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:118",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(118u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
::tracing_core::field::FieldSet::new(&["message"],
::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!("translate_args({0:?}, {1:?}, {2:?}, {3:?})",
param_env, source_impl, source_args, target_node) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
119"translate_args({:?}, {:?}, {:?}, {:?})",
120 param_env, source_impl, source_args, target_node
121 );
122let source_trait_ref =
123infcx.tcx.impl_trait_ref(source_impl).instantiate(infcx.tcx, source_args).skip_norm_wip();
124125// translate the Self and Param parts of the generic parameters, since those
126 // vary across impls
127let target_args = match target_node {
128 specialization_graph::Node::Impl(target_impl) => {
129// no need to translate if we're targeting the impl we started with
130if source_impl == target_impl {
131return source_args;
132 }
133134fulfill_implication(infcx, param_env, source_trait_ref, source_impl, target_impl, cause)
135 .unwrap_or_else(|_| {
136::rustc_middle::util::bug::bug_fmt(format_args!("When translating generic parameters from {0:?} to {1:?}, the expected specialization failed to hold",
source_impl, target_impl))bug!(
137"When translating generic parameters from {source_impl:?} to \
138 {target_impl:?}, the expected specialization failed to hold"
139)140 })
141 }
142 specialization_graph::Node::Trait(..) => source_trait_ref.args,
143 };
144145// directly inherent the method generics, since those do not vary across impls
146source_args.rebase_onto(infcx.tcx, source_impl, target_args)
147}
148149/// Attempt to fulfill all obligations of `target_impl` after unification with
150/// `source_trait_ref`. If successful, returns the generic parameters for *all* the
151/// generics of `target_impl`, including both those needed to unify with
152/// `source_trait_ref` and those whose identity is determined via a where
153/// clause in the impl.
154fn fulfill_implication<'tcx>(
155 infcx: &InferCtxt<'tcx>,
156 param_env: ty::ParamEnv<'tcx>,
157 source_trait_ref: ty::TraitRef<'tcx>,
158 source_impl: DefId,
159 target_impl: DefId,
160 cause: &ObligationCause<'tcx>,
161) -> Result<GenericArgsRef<'tcx>, NoSolution> {
162{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:162",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(162u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
::tracing_core::field::FieldSet::new(&["message"],
::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!("fulfill_implication({0:?}, trait_ref={1:?} |- {2:?} applies)",
param_env, source_trait_ref, target_impl) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
163"fulfill_implication({:?}, trait_ref={:?} |- {:?} applies)",
164 param_env, source_trait_ref, target_impl
165 );
166167let ocx = ObligationCtxt::new(infcx);
168let source_trait_ref = ocx.normalize(cause, param_env, Unnormalized::new_wip(source_trait_ref));
169170if !ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
171infcx.dcx().span_delayed_bug(
172infcx.tcx.def_span(source_impl),
173::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to fully normalize {0}",
source_trait_ref))
})format!("failed to fully normalize {source_trait_ref}"),
174 );
175return Err(NoSolution);
176 }
177178let target_args = infcx.fresh_args_for_item(DUMMY_SP, target_impl);
179let target_trait_ref = ocx.normalize(
180cause,
181param_env,
182infcx.tcx.impl_trait_ref(target_impl).instantiate(infcx.tcx, target_args),
183 );
184185// do the impls unify? If not, no specialization.
186ocx.eq(cause, param_env, source_trait_ref, target_trait_ref)?;
187188// Now check that the source trait ref satisfies all the where clauses of the target impl.
189 // This is not just for correctness; we also need this to constrain any params that may
190 // only be referenced via projection predicates.
191let clauses = infcx.tcx.clauses_of(target_impl).instantiate(infcx.tcx, target_args);
192let obligations = predicates_for_generics(
193 |_, _| cause.clone(),
194 |clause| ocx.normalize(cause, param_env, clause),
195param_env,
196clauses,
197 );
198ocx.register_obligations(obligations);
199200let errors = ocx.evaluate_obligations_error_on_ambiguity();
201if !errors.no_errors() {
202// no dice!
203{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:203",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(203u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
::tracing_core::field::FieldSet::new(&["message"],
::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!("fulfill_implication: for impls on {0:?} and {1:?}, could not fulfill: {2:?} given {3:?}",
source_trait_ref, target_trait_ref, errors, param_env) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
204"fulfill_implication: for impls on {:?} and {:?}, \
205 could not fulfill: {:?} given {:?}",
206 source_trait_ref, target_trait_ref, errors, param_env
207 );
208return Err(NoSolution);
209 }
210211{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:211",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(211u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
::tracing_core::field::FieldSet::new(&["message"],
::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!("fulfill_implication: an impl for {0:?} specializes {1:?}",
source_trait_ref, target_trait_ref) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
212"fulfill_implication: an impl for {:?} specializes {:?}",
213 source_trait_ref, target_trait_ref
214 );
215216// Now resolve the *generic parameters* we built for the target earlier, replacing
217 // the inference variables inside with whatever we got from fulfillment.
218Ok(infcx.resolve_vars_if_possible(target_args))
219}
220221pub(super) fn specialization_enabled_in(tcx: TyCtxt<'_>, _: LocalCrate) -> bool {
222tcx.features().specialization() || tcx.features().min_specialization()
223}
224225/// Is `specializing_impl_def_id` a specialization of `parent_impl_def_id`?
226///
227/// For every type that could apply to `specializing_impl_def_id`, we prove that
228/// the `parent_impl_def_id` also applies (i.e. it has a valid impl header and
229/// its where-clauses hold).
230///
231/// For the purposes of const traits, we also check that the specializing
232/// impl is not more restrictive than the parent impl. That is, if the
233/// `parent_impl_def_id` is a const impl (conditionally based off of some `[const]`
234/// bounds), then `specializing_impl_def_id` must also be const for the same
235/// set of types.
236{}
#[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("specializes",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(236u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("specializing_impl_def_id")
}> =
::tracing::__macro_support::FieldName::new("specializing_impl_def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("parent_impl_def_id")
}> =
::tracing::__macro_support::FieldName::new("parent_impl_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(&specializing_impl_def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_impl_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();
}
#[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: bool = loop {};
return __tracing_attr_fake_return;
}
{
if !tcx.specialization_enabled_in(specializing_impl_def_id.krate)
{
let span = tcx.def_span(specializing_impl_def_id);
if !span.allows_unstable(sym::specialization) &&
!span.allows_unstable(sym::min_specialization) {
return false;
}
}
let specializing_impl_trait_header =
tcx.impl_trait_header(specializing_impl_def_id);
if specializing_impl_trait_header.polarity !=
tcx.impl_polarity(parent_impl_def_id) {
return false;
}
let param_env = tcx.param_env(specializing_impl_def_id);
let infcx =
tcx.infer_ctxt().build(TypingMode::non_body_analysis());
let specializing_impl_trait_ref =
specializing_impl_trait_header.trait_ref.instantiate_identity();
let cause = &ObligationCause::dummy();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:285",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(285u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
::tracing_core::field::FieldSet::new(&["message"],
::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!("fulfill_implication({0:?}, trait_ref={1:?} |- {2:?} applies)",
param_env, specializing_impl_trait_ref, parent_impl_def_id)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let ocx = ObligationCtxt::new(&infcx);
let specializing_impl_trait_ref =
ocx.normalize(cause, param_env, specializing_impl_trait_ref);
if !ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
infcx.dcx().span_delayed_bug(infcx.tcx.def_span(specializing_impl_def_id),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to fully normalize {0}",
specializing_impl_trait_ref))
}));
return false;
}
let parent_args =
infcx.fresh_args_for_item(DUMMY_SP, parent_impl_def_id);
let parent_impl_trait_ref =
ocx.normalize(cause, param_env,
infcx.tcx.impl_trait_ref(parent_impl_def_id).instantiate(infcx.tcx,
parent_args));
let Ok(()) =
ocx.eq(cause, param_env, specializing_impl_trait_ref,
parent_impl_trait_ref) else { return false; };
let clauses =
infcx.tcx.clauses_of(parent_impl_def_id).instantiate(infcx.tcx,
parent_args);
let obligations =
predicates_for_generics(|_, _| cause.clone(),
|clause| ocx.normalize(cause, param_env, clause), param_env,
clauses);
ocx.register_obligations(obligations);
let errors = ocx.evaluate_obligations_error_on_ambiguity();
if !errors.no_errors() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:331",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(331u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
::tracing_core::field::FieldSet::new(&["message"],
::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!("fulfill_implication: for impls on {0:?} and {1:?}, could not fulfill: {2:?} given {3:?}",
specializing_impl_trait_ref, parent_impl_trait_ref, errors,
param_env) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
return false;
}
if tcx.is_conditionally_const(parent_impl_def_id) {
if !tcx.is_conditionally_const(specializing_impl_def_id) {
return false;
}
let const_conditions =
infcx.tcx.const_conditions(parent_impl_def_id).instantiate(infcx.tcx,
parent_args);
let const_conditions =
const_conditions.into_iter().map(|(trait_ref, span)|
(ocx.normalize(cause, param_env, trait_ref), span));
ocx.register_obligations(const_conditions.into_iter().map(|(trait_ref,
_)|
{
Obligation::new(infcx.tcx, cause.clone(), param_env,
trait_ref.to_host_effect_clause(infcx.tcx,
ty::BoundConstness::Maybe))
}));
let errors = ocx.evaluate_obligations_error_on_ambiguity();
if !errors.no_errors() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:364",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(364u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
::tracing_core::field::FieldSet::new(&["message"],
::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!("fulfill_implication: for impls on {0:?} and {1:?}, could not fulfill: {2:?} given {3:?}",
specializing_impl_trait_ref, parent_impl_trait_ref, errors,
param_env) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
return false;
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:373",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(373u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
::tracing_core::field::FieldSet::new(&["message"],
::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!("fulfill_implication: an impl for {0:?} specializes {1:?}",
specializing_impl_trait_ref, parent_impl_trait_ref) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
true
}
}
}#[instrument(skip(tcx), level = "debug")]237pub(super) fn specializes(
238 tcx: TyCtxt<'_>,
239 (specializing_impl_def_id, parent_impl_def_id): (DefId, DefId),
240) -> bool {
241// We check that the specializing impl comes from a crate that has specialization enabled,
242 // or if the specializing impl is marked with `allow_internal_unstable`.
243 //
244 // We don't really care if the specialized impl (the parent) is in a crate that has
245 // specialization enabled, since it's not being specialized, and it's already been checked
246 // for coherence.
247if !tcx.specialization_enabled_in(specializing_impl_def_id.krate) {
248let span = tcx.def_span(specializing_impl_def_id);
249if !span.allows_unstable(sym::specialization)
250 && !span.allows_unstable(sym::min_specialization)
251 {
252return false;
253 }
254 }
255256let specializing_impl_trait_header = tcx.impl_trait_header(specializing_impl_def_id);
257258// We determine whether there's a subset relationship by:
259 //
260 // - replacing bound vars with placeholders in impl1,
261 // - assuming the where clauses for impl1,
262 // - instantiating impl2 with fresh inference variables,
263 // - unifying,
264 // - attempting to prove the where clauses for impl2
265 //
266 // The last three steps are encapsulated in `fulfill_implication`.
267 //
268 // See RFC 1210 for more details and justification.
269270 // Currently we do not allow e.g., a negative impl to specialize a positive one
271if specializing_impl_trait_header.polarity != tcx.impl_polarity(parent_impl_def_id) {
272return false;
273 }
274275// create a parameter environment corresponding to an identity instantiation of the specializing impl,
276 // i.e. the most generic instantiation of the specializing impl.
277let param_env = tcx.param_env(specializing_impl_def_id);
278279// Create an infcx, taking the predicates of the specializing impl as assumptions:
280let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
281282let specializing_impl_trait_ref =
283 specializing_impl_trait_header.trait_ref.instantiate_identity();
284let cause = &ObligationCause::dummy();
285debug!(
286"fulfill_implication({:?}, trait_ref={:?} |- {:?} applies)",
287 param_env, specializing_impl_trait_ref, parent_impl_def_id
288 );
289290// Attempt to prove that the parent impl applies, given all of the above.
291292let ocx = ObligationCtxt::new(&infcx);
293let specializing_impl_trait_ref = ocx.normalize(cause, param_env, specializing_impl_trait_ref);
294295if !ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
296 infcx.dcx().span_delayed_bug(
297 infcx.tcx.def_span(specializing_impl_def_id),
298format!("failed to fully normalize {specializing_impl_trait_ref}"),
299 );
300return false;
301 }
302303let parent_args = infcx.fresh_args_for_item(DUMMY_SP, parent_impl_def_id);
304let parent_impl_trait_ref = ocx.normalize(
305 cause,
306 param_env,
307 infcx.tcx.impl_trait_ref(parent_impl_def_id).instantiate(infcx.tcx, parent_args),
308 );
309310// do the impls unify? If not, no specialization.
311let Ok(()) = ocx.eq(cause, param_env, specializing_impl_trait_ref, parent_impl_trait_ref)
312else {
313return false;
314 };
315316// Now check that the source trait ref satisfies all the where clauses of the target impl.
317 // This is not just for correctness; we also need this to constrain any params that may
318 // only be referenced via projection predicates.
319let clauses = infcx.tcx.clauses_of(parent_impl_def_id).instantiate(infcx.tcx, parent_args);
320let obligations = predicates_for_generics(
321 |_, _| cause.clone(),
322 |clause| ocx.normalize(cause, param_env, clause),
323 param_env,
324 clauses,
325 );
326 ocx.register_obligations(obligations);
327328let errors = ocx.evaluate_obligations_error_on_ambiguity();
329if !errors.no_errors() {
330// no dice!
331debug!(
332"fulfill_implication: for impls on {:?} and {:?}, \
333 could not fulfill: {:?} given {:?}",
334 specializing_impl_trait_ref, parent_impl_trait_ref, errors, param_env
335 );
336return false;
337 }
338339// If the parent impl is const, then the specializing impl must be const,
340 // and it must not be *more restrictive* than the parent impl (that is,
341 // it cannot be const in fewer cases than the parent impl).
342if tcx.is_conditionally_const(parent_impl_def_id) {
343if !tcx.is_conditionally_const(specializing_impl_def_id) {
344return false;
345 }
346347let const_conditions =
348 infcx.tcx.const_conditions(parent_impl_def_id).instantiate(infcx.tcx, parent_args);
349let const_conditions = const_conditions
350 .into_iter()
351 .map(|(trait_ref, span)| (ocx.normalize(cause, param_env, trait_ref), span));
352 ocx.register_obligations(const_conditions.into_iter().map(|(trait_ref, _)| {
353 Obligation::new(
354 infcx.tcx,
355 cause.clone(),
356 param_env,
357 trait_ref.to_host_effect_clause(infcx.tcx, ty::BoundConstness::Maybe),
358 )
359 }));
360361let errors = ocx.evaluate_obligations_error_on_ambiguity();
362if !errors.no_errors() {
363// no dice!
364debug!(
365"fulfill_implication: for impls on {:?} and {:?}, \
366 could not fulfill: {:?} given {:?}",
367 specializing_impl_trait_ref, parent_impl_trait_ref, errors, param_env
368 );
369return false;
370 }
371 }
372373debug!(
374"fulfill_implication: an impl for {:?} specializes {:?}",
375 specializing_impl_trait_ref, parent_impl_trait_ref
376 );
377378true
379}
380381/// Query provider for `specialization_graph_of`.
382pub(super) fn specialization_graph_provider(
383 tcx: TyCtxt<'_>,
384 trait_id: DefId,
385) -> Result<&'_ specialization_graph::Graph, ErrorGuaranteed> {
386let mut sg = specialization_graph::Graph::new();
387let overlap_mode = specialization_graph::OverlapMode::get(tcx, trait_id);
388389// Skip foreign non-blanket impls whose simplified-self bucket holds no
390 // local impl. This is sound because:
391 // - foreign impls are never overlap-checked, only recorded; `Ancestors`
392 // reads their parent lazily from metadata instead (the same value).
393 // - a local non-blanket impl is only compared against blanket impls and
394 // impls in its own bucket (see `filtered_children`), and instantiation
395 // preserves the simplified type, so kept buckets are complete at every
396 // level of the tree.
397 // - a local blanket impl, including alias self types which simplify to
398 // `None`, is compared against every child, so then all buckets are kept;
399 // pruning them would change error recovery (see impl-unpin.rs, `tait`
400 // revision).
401let all_impls = tcx.trait_impls_of(trait_id);
402let mut trait_impls: Vec<DefId> = all_impls.blanket_impls().to_vec();
403let has_local_blanket_impl =
404all_impls.blanket_impls().iter().any(|impl_def_id| impl_def_id.is_local());
405for (&simplified_self, bucket) in all_impls.non_blanket_impls() {
406if has_local_blanket_impl || bucket.iter().any(|impl_def_id| impl_def_id.is_local()) {
407 trait_impls.extend(bucket.iter().copied());
408 } else if truecfg!(debug_assertions) {
409// Assert metadata-derived key matches what the overlap checker recomputes.
410for &impl_def_id in bucket {
411let self_ty = tcx.impl_trait_ref(impl_def_id).skip_binder().self_ty();
412if true {
{
match (&fast_reject::simplify_type(tcx, self_ty,
TreatParams::InstantiateWithInfer), &Some(simplified_self))
{
(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::Some(format_args!("trait_impls_of bucket key disagrees with overlap-check simplification for foreign impl {0:?}",
impl_def_id)));
}
}
}
};
};debug_assert_eq!(
413 fast_reject::simplify_type(tcx, self_ty, TreatParams::InstantiateWithInfer),
414Some(simplified_self),
415"trait_impls_of bucket key disagrees with overlap-check \
416 simplification for foreign impl {impl_def_id:?}",
417 );
418 }
419 }
420 }
421422// The coherence checking implementation seems to rely on impls being
423 // iterated over (roughly) in definition order, so we are sorting by
424 // negated `CrateNum` (so remote definitions are visited first) and then
425 // by a flattened version of the `DefIndex`.
426trait_impls427 .sort_unstable_by_key(|def_id| (-(def_id.krate.as_u32() as i64), def_id.index.index()));
428429let mut errored = Ok(());
430431for impl_def_id in trait_impls {
432if let Some(impl_def_id) = impl_def_id.as_local() {
433// This is where impl overlap checking happens:
434let insert_result = sg.insert(tcx, impl_def_id.to_def_id(), overlap_mode);
435// Report error if there was one.
436let (overlap, used_to_be_allowed) = match insert_result {
437Err(overlap) => (Some(overlap), None),
438Ok(Some(overlap)) => (Some(overlap.error), Some(overlap.kind)),
439Ok(None) => (None, None),
440 };
441442if let Some(overlap) = overlap {
443 errored = errored.and(report_overlap_conflict(
444 tcx,
445 overlap,
446 impl_def_id,
447 used_to_be_allowed,
448 ));
449 }
450 } else {
451let parent = tcx.impl_parent(impl_def_id).unwrap_or(trait_id);
452 sg.record_impl_from_cstore(tcx, parent, impl_def_id)
453 }
454 }
455 errored?;
456457Ok(tcx.arena.alloc(sg))
458}
459460// This function is only used when
461// encountering errors and inlining
462// it negatively impacts perf.
463#[cold]
464#[inline(never)]
465fn report_overlap_conflict<'tcx>(
466 tcx: TyCtxt<'tcx>,
467 overlap: OverlapError<'tcx>,
468 impl_def_id: LocalDefId,
469 used_to_be_allowed: Option<FutureCompatOverlapErrorKind>,
470) -> Result<(), ErrorGuaranteed> {
471let impl_polarity = tcx.impl_polarity(impl_def_id.to_def_id());
472let other_polarity = tcx.impl_polarity(overlap.with_impl);
473match (impl_polarity, other_polarity) {
474 (ty::ImplPolarity::Negative, ty::ImplPolarity::Positive) => {
475Err(report_negative_positive_conflict(
476tcx,
477&overlap,
478impl_def_id,
479impl_def_id.to_def_id(),
480overlap.with_impl,
481 ))
482 }
483484 (ty::ImplPolarity::Positive, ty::ImplPolarity::Negative) => {
485Err(report_negative_positive_conflict(
486tcx,
487&overlap,
488impl_def_id,
489overlap.with_impl,
490impl_def_id.to_def_id(),
491 ))
492 }
493494_ => report_conflicting_impls(tcx, overlap, impl_def_id, used_to_be_allowed),
495 }
496}
497498fn report_negative_positive_conflict<'tcx>(
499 tcx: TyCtxt<'tcx>,
500 overlap: &OverlapError<'tcx>,
501 local_impl_def_id: LocalDefId,
502 negative_impl_def_id: DefId,
503 positive_impl_def_id: DefId,
504) -> ErrorGuaranteed {
505let mut diag = tcx.dcx().create_err(NegativePositiveConflict {
506 impl_span: tcx.def_span(local_impl_def_id),
507 trait_desc: overlap.trait_ref,
508 self_ty: overlap.self_ty,
509 negative_impl_span: tcx.span_of_impl(negative_impl_def_id),
510 positive_impl_span: tcx.span_of_impl(positive_impl_def_id),
511 });
512513for cause in &overlap.intercrate_ambiguity_causes {
514 cause.add_intercrate_ambiguity_hint(&mut diag);
515 }
516517diag.emit()
518}
519520fn report_conflicting_impls<'tcx>(
521 tcx: TyCtxt<'tcx>,
522 overlap: OverlapError<'tcx>,
523 impl_def_id: LocalDefId,
524 used_to_be_allowed: Option<FutureCompatOverlapErrorKind>,
525) -> Result<(), ErrorGuaranteed> {
526let impl_span = tcx.def_span(impl_def_id);
527528// Work to be done after we've built the Diag. We have to define it now
529 // because the lint emit methods don't return back the Diag that's passed
530 // in.
531fn decorate<'tcx, G: EmissionGuarantee>(
532 tcx: TyCtxt<'tcx>,
533 overlap: &OverlapError<'tcx>,
534 impl_span: Span,
535 err: &mut Diag<'_, G>,
536 ) {
537match tcx.span_of_impl(overlap.with_impl) {
538Ok(span) => {
539err.span_label(span, "first implementation here");
540541err.span_label(
542impl_span,
543::alloc::__export::must_use({
::alloc::fmt::format(format_args!("conflicting implementation{0}",
overlap.self_ty.map_or_else(String::new,
|ty|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" for `{0}`", ty))
}))))
})format!(
544"conflicting implementation{}",
545 overlap.self_ty.map_or_else(String::new, |ty| format!(" for `{ty}`"))
546 ),
547 );
548 }
549Err(cname) => {
550let msg = match to_pretty_impl_header(tcx, overlap.with_impl) {
551Some(s) => {
552::alloc::__export::must_use({
::alloc::fmt::format(format_args!("conflicting implementation in crate `{0}`:\n- {1}",
cname, s))
})format!("conflicting implementation in crate `{cname}`:\n- {s}")553 }
554None => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("conflicting implementation in crate `{0}`",
cname))
})format!("conflicting implementation in crate `{cname}`"),
555 };
556err.note(msg);
557 }
558 }
559560for cause in &overlap.intercrate_ambiguity_causes {
561 cause.add_intercrate_ambiguity_hint(err);
562 }
563564if overlap.involves_placeholder {
565 coherence::add_placeholder_note(err);
566 }
567568if !overlap.overflowing_predicates.is_empty() {
569 coherence::suggest_increasing_recursion_limit(
570tcx,
571err,
572&overlap.overflowing_predicates,
573 );
574 }
575 }
576577let msg = || {
578::alloc::__export::must_use({
::alloc::fmt::format(format_args!("conflicting implementations of trait `{0}`{1}",
overlap.trait_ref.print_trait_sugared(),
overlap.self_ty.map_or_else(String::new,
|ty|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" for type `{0}`", ty))
}))))
})format!(
579"conflicting implementations of trait `{}`{}",
580 overlap.trait_ref.print_trait_sugared(),
581 overlap.self_ty.map_or_else(String::new, |ty| format!(" for type `{ty}`")),
582 )583 };
584585// Don't report overlap errors if the header references error
586if let Err(err) = (overlap.trait_ref, overlap.self_ty).error_reported() {
587return Err(err);
588 }
589590match used_to_be_allowed {
591None => {
592let reported = if overlap.with_impl.is_local()
593 || tcx.ensure_result().orphan_check_impl(impl_def_id).is_ok()
594 {
595let mut err = tcx.dcx().struct_span_err(impl_span, msg());
596err.code(E0119);
597decorate(tcx, &overlap, impl_span, &mut err);
598err.emit()
599 } else {
600tcx.dcx().span_delayed_bug(impl_span, "impl should have failed the orphan check")
601 };
602Err(reported)
603 }
604Some(kind) => {
605let lint = match kind {
606 FutureCompatOverlapErrorKind::LeakCheck => COHERENCE_LEAK_CHECK,
607 };
608tcx.emit_node_span_lint(
609lint,
610tcx.local_def_id_to_hir_id(impl_def_id),
611impl_span,
612 rustc_errors::DiagDecorator(|err| {
613err.primary_message(msg());
614decorate(tcx, &overlap, impl_span, err);
615 }),
616 );
617Ok(())
618 }
619 }
620}