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_middle::bug;
20use rustc_middle::query::LocalCrate;
21use rustc_middle::traits::query::NoSolution;
22use rustc_middle::ty::print::PrintTraitRefExtas _;
23use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, TypingMode};
24use rustc_session::lint::builtin::COHERENCE_LEAK_CHECK;
25use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, sym};
26use specialization_graph::GraphExt;
27use tracing::{debug, instrument};
2829use crate::error_reporting::traits::to_pretty_impl_header;
30use crate::errors::NegativePositiveConflict;
31use crate::infer::{InferCtxt, TyCtxtInferExt};
32use crate::traits::select::IntercrateAmbiguityCause;
33use crate::traits::{
34FutureCompatOverlapErrorKind, ObligationCause, ObligationCtxt, coherence,
35predicates_for_generics,
36};
3738/// Information pertinent to an overlapping impl error.
39#[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)]
40pub struct OverlapError<'tcx> {
41pub with_impl: DefId,
42pub trait_ref: ty::TraitRef<'tcx>,
43pub self_ty: Option<Ty<'tcx>>,
44pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
45pub involves_placeholder: bool,
46pub overflowing_predicates: Vec<ty::Predicate<'tcx>>,
47}
4849/// Given the generic parameters for the requested impl, translate it to the generic parameters
50/// appropriate for the actual item definition (whether it be in that impl,
51/// a parent impl, or the trait).
52///
53/// When we have selected one impl, but are actually using item definitions from
54/// a parent impl providing a default, we need a way to translate between the
55/// type parameters of the two impls. Here the `source_impl` is the one we've
56/// selected, and `source_args` is its generic parameters.
57/// And `target_node` is the impl/trait we're actually going to get the
58/// definition from. The resulting instantiation will map from `target_node`'s
59/// generics to `source_impl`'s generics as instantiated by `source_args`.
60///
61/// For example, consider the following scenario:
62///
63/// ```ignore (illustrative)
64/// trait Foo { ... }
65/// impl<T, U> Foo for (T, U) { ... } // target impl
66/// impl<V> Foo for (V, V) { ... } // source impl
67/// ```
68///
69/// Suppose we have selected "source impl" with `V` instantiated with `u32`.
70/// This function will produce an instantiation with `T` and `U` both mapping to `u32`.
71///
72/// where-clauses add some trickiness here, because they can be used to "define"
73/// an argument indirectly:
74///
75/// ```ignore (illustrative)
76/// impl<'a, I, T: 'a> Iterator for Cloned<I>
77/// where I: Iterator<Item = &'a T>, T: Clone
78/// ```
79///
80/// In a case like this, the instantiation for `T` is determined indirectly,
81/// through associated type projection. We deal with such cases by using
82/// *fulfillment* to relate the two impls, requiring that all projections are
83/// resolved.
84pub fn translate_args<'tcx>(
85 infcx: &InferCtxt<'tcx>,
86 param_env: ty::ParamEnv<'tcx>,
87 source_impl: DefId,
88 source_args: GenericArgsRef<'tcx>,
89 target_node: specialization_graph::Node,
90) -> GenericArgsRef<'tcx> {
91translate_args_with_cause(
92infcx,
93param_env,
94source_impl,
95source_args,
96target_node,
97&ObligationCause::dummy(),
98 )
99}
100101/// Like [translate_args], but obligations from the parent implementation
102/// are registered with the provided `ObligationCause`.
103///
104/// This is for reporting *region* errors from those bounds. Type errors should
105/// not happen because the specialization graph already checks for those, and
106/// will result in an ICE.
107pub fn translate_args_with_cause<'tcx>(
108 infcx: &InferCtxt<'tcx>,
109 param_env: ty::ParamEnv<'tcx>,
110 source_impl: DefId,
111 source_args: GenericArgsRef<'tcx>,
112 target_node: specialization_graph::Node,
113 cause: &ObligationCause<'tcx>,
114) -> GenericArgsRef<'tcx> {
115{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/specialize/mod.rs:115",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(115u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("translate_args({0:?}, {1:?}, {2:?}, {3:?})",
param_env, source_impl, source_args, target_node) as
&dyn Value))])
});
} else { ; }
};debug!(
116"translate_args({:?}, {:?}, {:?}, {:?})",
117 param_env, source_impl, source_args, target_node
118 );
119let source_trait_ref =
120infcx.tcx.impl_trait_ref(source_impl).instantiate(infcx.tcx, source_args);
121122// translate the Self and Param parts of the generic parameters, since those
123 // vary across impls
124let target_args = match target_node {
125 specialization_graph::Node::Impl(target_impl) => {
126// no need to translate if we're targeting the impl we started with
127if source_impl == target_impl {
128return source_args;
129 }
130131fulfill_implication(infcx, param_env, source_trait_ref, source_impl, target_impl, cause)
132 .unwrap_or_else(|_| {
133::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!(
134"When translating generic parameters from {source_impl:?} to \
135 {target_impl:?}, the expected specialization failed to hold"
136)137 })
138 }
139 specialization_graph::Node::Trait(..) => source_trait_ref.args,
140 };
141142// directly inherent the method generics, since those do not vary across impls
143source_args.rebase_onto(infcx.tcx, source_impl, target_args)
144}
145146/// Attempt to fulfill all obligations of `target_impl` after unification with
147/// `source_trait_ref`. If successful, returns the generic parameters for *all* the
148/// generics of `target_impl`, including both those needed to unify with
149/// `source_trait_ref` and those whose identity is determined via a where
150/// clause in the impl.
151fn fulfill_implication<'tcx>(
152 infcx: &InferCtxt<'tcx>,
153 param_env: ty::ParamEnv<'tcx>,
154 source_trait_ref: ty::TraitRef<'tcx>,
155 source_impl: DefId,
156 target_impl: DefId,
157 cause: &ObligationCause<'tcx>,
158) -> Result<GenericArgsRef<'tcx>, NoSolution> {
159{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/specialize/mod.rs:159",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(159u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("fulfill_implication({0:?}, trait_ref={1:?} |- {2:?} applies)",
param_env, source_trait_ref, target_impl) as &dyn Value))])
});
} else { ; }
};debug!(
160"fulfill_implication({:?}, trait_ref={:?} |- {:?} applies)",
161 param_env, source_trait_ref, target_impl
162 );
163164let ocx = ObligationCtxt::new(infcx);
165let source_trait_ref = ocx.normalize(cause, param_env, source_trait_ref);
166167if !ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
168infcx.dcx().span_delayed_bug(
169infcx.tcx.def_span(source_impl),
170::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}"),
171 );
172return Err(NoSolution);
173 }
174175let target_args = infcx.fresh_args_for_item(DUMMY_SP, target_impl);
176let target_trait_ref = ocx.normalize(
177cause,
178param_env,
179infcx.tcx.impl_trait_ref(target_impl).instantiate(infcx.tcx, target_args),
180 );
181182// do the impls unify? If not, no specialization.
183ocx.eq(cause, param_env, source_trait_ref, target_trait_ref)?;
184185// Now check that the source trait ref satisfies all the where clauses of the target impl.
186 // This is not just for correctness; we also need this to constrain any params that may
187 // only be referenced via projection predicates.
188let predicates = infcx.tcx.predicates_of(target_impl).instantiate(infcx.tcx, target_args);
189let obligations = predicates_for_generics(
190 |_, _| cause.clone(),
191 |pred| ocx.normalize(cause, param_env, pred),
192param_env,
193predicates,
194 );
195ocx.register_obligations(obligations);
196197let errors = ocx.evaluate_obligations_error_on_ambiguity();
198if !errors.is_empty() {
199// no dice!
200{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/specialize/mod.rs:200",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(200u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("fulfill_implication: for impls on {0:?} and {1:?}, could not fulfill: {2:?} given {3:?}",
source_trait_ref, target_trait_ref, errors,
param_env.caller_bounds()) as &dyn Value))])
});
} else { ; }
};debug!(
201"fulfill_implication: for impls on {:?} and {:?}, \
202 could not fulfill: {:?} given {:?}",
203 source_trait_ref,
204 target_trait_ref,
205 errors,
206 param_env.caller_bounds()
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 compiler/rustc_trait_selection/src/traits/specialize/mod.rs:211",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("fulfill_implication: an impl for {0:?} specializes {1:?}",
source_trait_ref, target_trait_ref) as &dyn 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("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(&["specializing_impl_def_id",
"parent_impl_def_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&specializing_impl_def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_impl_def_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: 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 compiler/rustc_trait_selection/src/traits/specialize/mod.rs:285",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("fulfill_implication({0:?}, trait_ref={1:?} |- {2:?} applies)",
param_env, specializing_impl_trait_ref, parent_impl_def_id)
as &dyn 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().is_empty() {
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 predicates =
infcx.tcx.predicates_of(parent_impl_def_id).instantiate(infcx.tcx,
parent_args);
let obligations =
predicates_for_generics(|_, _| cause.clone(),
|pred| ocx.normalize(cause, param_env, pred), param_env,
predicates);
ocx.register_obligations(obligations);
let errors = ocx.evaluate_obligations_error_on_ambiguity();
if !errors.is_empty() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/specialize/mod.rs:332",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(332u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("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.caller_bounds()) as &dyn 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 =
ocx.normalize(cause, param_env,
infcx.tcx.const_conditions(parent_impl_def_id).instantiate(infcx.tcx,
parent_args));
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.is_empty() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/specialize/mod.rs:368",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(368u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("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.caller_bounds()) as &dyn 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 compiler/rustc_trait_selection/src/traits/specialize/mod.rs:380",
"rustc_trait_selection::traits::specialize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
::tracing_core::__macro_support::Option::Some(380u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("fulfill_implication: an impl for {0:?} specializes {1:?}",
specializing_impl_trait_ref, parent_impl_trait_ref) as
&dyn 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().is_empty() {
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 predicates =
320 infcx.tcx.predicates_of(parent_impl_def_id).instantiate(infcx.tcx, parent_args);
321let obligations = predicates_for_generics(
322 |_, _| cause.clone(),
323 |pred| ocx.normalize(cause, param_env, pred),
324 param_env,
325 predicates,
326 );
327 ocx.register_obligations(obligations);
328329let errors = ocx.evaluate_obligations_error_on_ambiguity();
330if !errors.is_empty() {
331// no dice!
332debug!(
333"fulfill_implication: for impls on {:?} and {:?}, \
334 could not fulfill: {:?} given {:?}",
335 specializing_impl_trait_ref,
336 parent_impl_trait_ref,
337 errors,
338 param_env.caller_bounds()
339 );
340return false;
341 }
342343// If the parent impl is const, then the specializing impl must be const,
344 // and it must not be *more restrictive* than the parent impl (that is,
345 // it cannot be const in fewer cases than the parent impl).
346if tcx.is_conditionally_const(parent_impl_def_id) {
347if !tcx.is_conditionally_const(specializing_impl_def_id) {
348return false;
349 }
350351let const_conditions = ocx.normalize(
352 cause,
353 param_env,
354 infcx.tcx.const_conditions(parent_impl_def_id).instantiate(infcx.tcx, parent_args),
355 );
356 ocx.register_obligations(const_conditions.into_iter().map(|(trait_ref, _)| {
357 Obligation::new(
358 infcx.tcx,
359 cause.clone(),
360 param_env,
361 trait_ref.to_host_effect_clause(infcx.tcx, ty::BoundConstness::Maybe),
362 )
363 }));
364365let errors = ocx.evaluate_obligations_error_on_ambiguity();
366if !errors.is_empty() {
367// no dice!
368debug!(
369"fulfill_implication: for impls on {:?} and {:?}, \
370 could not fulfill: {:?} given {:?}",
371 specializing_impl_trait_ref,
372 parent_impl_trait_ref,
373 errors,
374 param_env.caller_bounds()
375 );
376return false;
377 }
378 }
379380debug!(
381"fulfill_implication: an impl for {:?} specializes {:?}",
382 specializing_impl_trait_ref, parent_impl_trait_ref
383 );
384385true
386}
387388/// Query provider for `specialization_graph_of`.
389pub(super) fn specialization_graph_provider(
390 tcx: TyCtxt<'_>,
391 trait_id: DefId,
392) -> Result<&'_ specialization_graph::Graph, ErrorGuaranteed> {
393let mut sg = specialization_graph::Graph::new();
394let overlap_mode = specialization_graph::OverlapMode::get(tcx, trait_id);
395396let mut trait_impls: Vec<_> = tcx.all_impls(trait_id).collect();
397398// The coherence checking implementation seems to rely on impls being
399 // iterated over (roughly) in definition order, so we are sorting by
400 // negated `CrateNum` (so remote definitions are visited first) and then
401 // by a flattened version of the `DefIndex`.
402trait_impls403 .sort_unstable_by_key(|def_id| (-(def_id.krate.as_u32() as i64), def_id.index.index()));
404405let mut errored = Ok(());
406407for impl_def_id in trait_impls {
408if let Some(impl_def_id) = impl_def_id.as_local() {
409// This is where impl overlap checking happens:
410let insert_result = sg.insert(tcx, impl_def_id.to_def_id(), overlap_mode);
411// Report error if there was one.
412let (overlap, used_to_be_allowed) = match insert_result {
413Err(overlap) => (Some(overlap), None),
414Ok(Some(overlap)) => (Some(overlap.error), Some(overlap.kind)),
415Ok(None) => (None, None),
416 };
417418if let Some(overlap) = overlap {
419 errored = errored.and(report_overlap_conflict(
420 tcx,
421 overlap,
422 impl_def_id,
423 used_to_be_allowed,
424 ));
425 }
426 } else {
427let parent = tcx.impl_parent(impl_def_id).unwrap_or(trait_id);
428 sg.record_impl_from_cstore(tcx, parent, impl_def_id)
429 }
430 }
431errored?;
432433Ok(tcx.arena.alloc(sg))
434}
435436// This function is only used when
437// encountering errors and inlining
438// it negatively impacts perf.
439#[cold]
440#[inline(never)]
441fn report_overlap_conflict<'tcx>(
442 tcx: TyCtxt<'tcx>,
443 overlap: OverlapError<'tcx>,
444 impl_def_id: LocalDefId,
445 used_to_be_allowed: Option<FutureCompatOverlapErrorKind>,
446) -> Result<(), ErrorGuaranteed> {
447let impl_polarity = tcx.impl_polarity(impl_def_id.to_def_id());
448let other_polarity = tcx.impl_polarity(overlap.with_impl);
449match (impl_polarity, other_polarity) {
450 (ty::ImplPolarity::Negative, ty::ImplPolarity::Positive) => {
451Err(report_negative_positive_conflict(
452tcx,
453&overlap,
454impl_def_id,
455impl_def_id.to_def_id(),
456overlap.with_impl,
457 ))
458 }
459460 (ty::ImplPolarity::Positive, ty::ImplPolarity::Negative) => {
461Err(report_negative_positive_conflict(
462tcx,
463&overlap,
464impl_def_id,
465overlap.with_impl,
466impl_def_id.to_def_id(),
467 ))
468 }
469470_ => report_conflicting_impls(tcx, overlap, impl_def_id, used_to_be_allowed),
471 }
472}
473474fn report_negative_positive_conflict<'tcx>(
475 tcx: TyCtxt<'tcx>,
476 overlap: &OverlapError<'tcx>,
477 local_impl_def_id: LocalDefId,
478 negative_impl_def_id: DefId,
479 positive_impl_def_id: DefId,
480) -> ErrorGuaranteed {
481let mut diag = tcx.dcx().create_err(NegativePositiveConflict {
482 impl_span: tcx.def_span(local_impl_def_id),
483 trait_desc: overlap.trait_ref,
484 self_ty: overlap.self_ty,
485 negative_impl_span: tcx.span_of_impl(negative_impl_def_id),
486 positive_impl_span: tcx.span_of_impl(positive_impl_def_id),
487 });
488489for cause in &overlap.intercrate_ambiguity_causes {
490 cause.add_intercrate_ambiguity_hint(&mut diag);
491 }
492493diag.emit()
494}
495496fn report_conflicting_impls<'tcx>(
497 tcx: TyCtxt<'tcx>,
498 overlap: OverlapError<'tcx>,
499 impl_def_id: LocalDefId,
500 used_to_be_allowed: Option<FutureCompatOverlapErrorKind>,
501) -> Result<(), ErrorGuaranteed> {
502let impl_span = tcx.def_span(impl_def_id);
503504// Work to be done after we've built the Diag. We have to define it now
505 // because the lint emit methods don't return back the Diag that's passed
506 // in.
507fn decorate<'tcx, G: EmissionGuarantee>(
508 tcx: TyCtxt<'tcx>,
509 overlap: &OverlapError<'tcx>,
510 impl_span: Span,
511 err: &mut Diag<'_, G>,
512 ) {
513match tcx.span_of_impl(overlap.with_impl) {
514Ok(span) => {
515err.span_label(span, "first implementation here");
516517err.span_label(
518impl_span,
519::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!(
520"conflicting implementation{}",
521 overlap.self_ty.map_or_else(String::new, |ty| format!(" for `{ty}`"))
522 ),
523 );
524 }
525Err(cname) => {
526let msg = match to_pretty_impl_header(tcx, overlap.with_impl) {
527Some(s) => {
528::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}")529 }
530None => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("conflicting implementation in crate `{0}`",
cname))
})format!("conflicting implementation in crate `{cname}`"),
531 };
532err.note(msg);
533 }
534 }
535536for cause in &overlap.intercrate_ambiguity_causes {
537 cause.add_intercrate_ambiguity_hint(err);
538 }
539540if overlap.involves_placeholder {
541 coherence::add_placeholder_note(err);
542 }
543544if !overlap.overflowing_predicates.is_empty() {
545 coherence::suggest_increasing_recursion_limit(
546tcx,
547err,
548&overlap.overflowing_predicates,
549 );
550 }
551 }
552553let msg = || {
554::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!(
555"conflicting implementations of trait `{}`{}",
556 overlap.trait_ref.print_trait_sugared(),
557 overlap.self_ty.map_or_else(String::new, |ty| format!(" for type `{ty}`")),
558 )559 };
560561// Don't report overlap errors if the header references error
562if let Err(err) = (overlap.trait_ref, overlap.self_ty).error_reported() {
563return Err(err);
564 }
565566match used_to_be_allowed {
567None => {
568let reported = if overlap.with_impl.is_local()
569 || tcx.ensure_result().orphan_check_impl(impl_def_id).is_ok()
570 {
571let mut err = tcx.dcx().struct_span_err(impl_span, msg());
572err.code(E0119);
573decorate(tcx, &overlap, impl_span, &mut err);
574err.emit()
575 } else {
576tcx.dcx().span_delayed_bug(impl_span, "impl should have failed the orphan check")
577 };
578Err(reported)
579 }
580Some(kind) => {
581let lint = match kind {
582 FutureCompatOverlapErrorKind::LeakCheck => COHERENCE_LEAK_CHECK,
583 };
584tcx.emit_node_span_lint(
585lint,
586tcx.local_def_id_to_hir_id(impl_def_id),
587impl_span,
588 rustc_errors::DiagDecorator(|err| {
589err.primary_message(msg());
590decorate(tcx, &overlap, impl_span, err);
591 }),
592 );
593Ok(())
594 }
595 }
596}