1 //! Logic and data structures related to impl specialization, explained in
2 //! greater detail below.
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.
7 //! See the [rustc guide] for a bit more detail on how specialization
8 //! fits together with the rest of the trait machinery.
10 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/specialization.html
12 pub mod specialization_graph;
14 use crate::hir::def_id::DefId;
15 use crate::infer::{InferCtxt, InferOk};
17 use crate::traits::{self, coherence, FutureCompatOverlapErrorKind, ObligationCause, TraitEngine};
18 use rustc_data_structures::fx::FxHashSet;
19 use syntax_pos::DUMMY_SP;
20 use crate::traits::select::IntercrateAmbiguityCause;
21 use crate::ty::{self, TyCtxt, TypeFoldable};
22 use crate::ty::subst::{Subst, InternalSubsts, SubstsRef};
24 use super::{SelectionContext, FulfillmentContext};
25 use super::util::impl_trait_ref_and_oblig;
27 /// Information pertinent to an overlapping impl error.
29 pub struct OverlapError {
31 pub trait_desc: String,
32 pub self_desc: Option<String>,
33 pub intercrate_ambiguity_causes: Vec<IntercrateAmbiguityCause>,
34 pub involves_placeholder: bool,
37 /// Given a subst for the requested impl, translate it to a subst
38 /// appropriate for the actual item definition (whether it be in that impl,
39 /// a parent impl, or the trait).
41 /// When we have selected one impl, but are actually using item definitions from
42 /// a parent impl providing a default, we need a way to translate between the
43 /// type parameters of the two impls. Here the `source_impl` is the one we've
44 /// selected, and `source_substs` is a substitution of its generics.
45 /// And `target_node` is the impl/trait we're actually going to get the
46 /// definition from. The resulting substitution will map from `target_node`'s
47 /// generics to `source_impl`'s generics as instantiated by `source_subst`.
49 /// For example, consider the following scenario:
53 /// impl<T, U> Foo for (T, U) { ... } // target impl
54 /// impl<V> Foo for (V, V) { ... } // source impl
57 /// Suppose we have selected "source impl" with `V` instantiated with `u32`.
58 /// This function will produce a substitution with `T` and `U` both mapping to `u32`.
60 /// where-clauses add some trickiness here, because they can be used to "define"
61 /// an argument indirectly:
64 /// impl<'a, I, T: 'a> Iterator for Cloned<I>
65 /// where I: Iterator<Item = &'a T>, T: Clone
68 /// In a case like this, the substitution for `T` is determined indirectly,
69 /// through associated type projection. We deal with such cases by using
70 /// *fulfillment* to relate the two impls, requiring that all projections are
72 pub fn translate_substs<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
73 param_env: ty::ParamEnv<'tcx>,
75 source_substs: SubstsRef<'tcx>,
76 target_node: specialization_graph::Node)
78 debug!("translate_substs({:?}, {:?}, {:?}, {:?})",
79 param_env, source_impl, source_substs, target_node);
80 let source_trait_ref = infcx.tcx
81 .impl_trait_ref(source_impl)
83 .subst(infcx.tcx, &source_substs);
85 // translate the Self and Param parts of the substitution, since those
87 let target_substs = match target_node {
88 specialization_graph::Node::Impl(target_impl) => {
89 // no need to translate if we're targeting the impl we started with
90 if source_impl == target_impl {
94 fulfill_implication(infcx, param_env, source_trait_ref, target_impl)
96 bug!("When translating substitutions for specialization, the expected \
97 specialization failed to hold")
100 specialization_graph::Node::Trait(..) => source_trait_ref.substs,
103 // directly inherent the method generics, since those do not vary across impls
104 source_substs.rebase_onto(infcx.tcx, source_impl, target_substs)
107 /// Given a selected impl described by `impl_data`, returns the
108 /// definition and substitutions for the method with the name `name`
109 /// the kind `kind`, and trait method substitutions `substs`, in
110 /// that impl, a less specialized impl, or the trait default,
111 /// whichever applies.
112 pub fn find_associated_item<'a, 'tcx>(
113 tcx: TyCtxt<'a, 'tcx, 'tcx>,
114 param_env: ty::ParamEnv<'tcx>,
115 item: &ty::AssociatedItem,
116 substs: SubstsRef<'tcx>,
117 impl_data: &super::VtableImplData<'tcx, ()>,
118 ) -> (DefId, SubstsRef<'tcx>) {
119 debug!("find_associated_item({:?}, {:?}, {:?}, {:?})",
120 param_env, item, substs, impl_data);
121 assert!(!substs.needs_infer());
123 let trait_def_id = tcx.trait_id_of_impl(impl_data.impl_def_id).unwrap();
124 let trait_def = tcx.trait_def(trait_def_id);
126 let ancestors = trait_def.ancestors(tcx, impl_data.impl_def_id);
127 match ancestors.defs(tcx, item.ident, item.kind, trait_def_id).next() {
129 let substs = tcx.infer_ctxt().enter(|infcx| {
130 let param_env = param_env.with_reveal_all();
131 let substs = substs.rebase_onto(tcx, trait_def_id, impl_data.substs);
132 let substs = translate_substs(&infcx, param_env, impl_data.impl_def_id,
133 substs, node_item.node);
134 let substs = infcx.tcx.erase_regions(&substs);
135 tcx.lift(&substs).unwrap_or_else(||
136 bug!("find_method: translate_substs \
137 returned {:?} which contains inference types/regions",
141 (node_item.item.def_id, substs)
143 None => bug!("{:?} not found in {:?}", item, impl_data.impl_def_id)
147 /// Is `impl1` a specialization of `impl2`?
149 /// Specialization is determined by the sets of types to which the impls apply;
150 /// `impl1` specializes `impl2` if it applies to a subset of the types `impl2` applies
152 pub(super) fn specializes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
153 (impl1_def_id, impl2_def_id): (DefId, DefId))
156 debug!("specializes({:?}, {:?})", impl1_def_id, impl2_def_id);
158 // The feature gate should prevent introducing new specializations, but not
159 // taking advantage of upstream ones.
160 if !tcx.features().specialization &&
161 (impl1_def_id.is_local() || impl2_def_id.is_local()) {
165 // We determine whether there's a subset relationship by:
167 // - skolemizing impl1,
168 // - assuming the where clauses for impl1,
169 // - instantiating impl2 with fresh inference variables,
171 // - attempting to prove the where clauses for impl2
173 // The last three steps are encapsulated in `fulfill_implication`.
175 // See RFC 1210 for more details and justification.
177 // Currently we do not allow e.g., a negative impl to specialize a positive one
178 if tcx.impl_polarity(impl1_def_id) != tcx.impl_polarity(impl2_def_id) {
182 // create a parameter environment corresponding to a (placeholder) instantiation of impl1
183 let penv = tcx.param_env(impl1_def_id);
184 let impl1_trait_ref = tcx.impl_trait_ref(impl1_def_id).unwrap();
186 // Create a infcx, taking the predicates of impl1 as assumptions:
187 tcx.infer_ctxt().enter(|infcx| {
188 // Normalize the trait reference. The WF rules ought to ensure
189 // that this always succeeds.
190 let impl1_trait_ref =
191 match traits::fully_normalize(&infcx,
192 FulfillmentContext::new(),
193 ObligationCause::dummy(),
196 Ok(impl1_trait_ref) => impl1_trait_ref,
198 bug!("failed to fully normalize {:?}: {:?}", impl1_trait_ref, err);
202 // Attempt to prove that impl2 applies, given all of the above.
203 fulfill_implication(&infcx, penv, impl1_trait_ref, impl2_def_id).is_ok()
207 /// Attempt to fulfill all obligations of `target_impl` after unification with
208 /// `source_trait_ref`. If successful, returns a substitution for *all* the
209 /// generics of `target_impl`, including both those needed to unify with
210 /// `source_trait_ref` and those whose identity is determined via a where
211 /// clause in the impl.
212 fn fulfill_implication<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
213 param_env: ty::ParamEnv<'tcx>,
214 source_trait_ref: ty::TraitRef<'tcx>,
216 -> Result<SubstsRef<'tcx>, ()> {
217 debug!("fulfill_implication({:?}, trait_ref={:?} |- {:?} applies)",
218 param_env, source_trait_ref, target_impl);
220 let selcx = &mut SelectionContext::new(&infcx);
221 let target_substs = infcx.fresh_substs_for_item(DUMMY_SP, target_impl);
222 let (target_trait_ref, mut obligations) = impl_trait_ref_and_oblig(selcx,
226 debug!("fulfill_implication: target_trait_ref={:?}, obligations={:?}",
227 target_trait_ref, obligations);
229 // do the impls unify? If not, no specialization.
230 match infcx.at(&ObligationCause::dummy(), param_env)
231 .eq(source_trait_ref, target_trait_ref) {
232 Ok(InferOk { obligations: o, .. }) => {
233 obligations.extend(o);
236 debug!("fulfill_implication: {:?} does not unify with {:?}",
243 // attempt to prove all of the predicates for impl2 given those for impl1
244 // (which are packed up in penv)
246 infcx.save_and_restore_in_snapshot_flag(|infcx| {
247 // If we came from `translate_substs`, we already know that the
248 // predicates for our impl hold (after all, we know that a more
249 // specialized impl holds, so our impl must hold too), and
250 // we only want to process the projections to determine the
251 // the types in our substs using RFC 447, so we can safely
252 // ignore region obligations, which allows us to avoid threading
253 // a node-id to assign them with.
255 // If we came from specialization graph construction, then
256 // we already make a mockery out of the region system, so
257 // why not ignore them a bit earlier?
258 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
259 for oblig in obligations.into_iter() {
260 fulfill_cx.register_predicate_obligation(&infcx, oblig);
262 match fulfill_cx.select_all_or_error(infcx) {
265 debug!("fulfill_implication: for impls on {:?} and {:?}, \
266 could not fulfill: {:?} given {:?}",
270 param_env.caller_bounds);
275 debug!("fulfill_implication: an impl for {:?} specializes {:?}",
279 // Now resolve the *substitution* we built for the target earlier, replacing
280 // the inference variables inside with whatever we got from fulfillment.
281 Ok(infcx.resolve_type_vars_if_possible(&target_substs))
287 // Query provider for `specialization_graph_of`.
288 pub(super) fn specialization_graph_provider<'a, 'tcx>(
289 tcx: TyCtxt<'a, 'tcx, 'tcx>,
291 ) -> &'tcx specialization_graph::Graph {
292 let mut sg = specialization_graph::Graph::new();
294 let mut trait_impls = tcx.all_impls(trait_id);
296 // The coherence checking implementation seems to rely on impls being
297 // iterated over (roughly) in definition order, so we are sorting by
298 // negated `CrateNum` (so remote definitions are visited first) and then
299 // by a flattened version of the `DefIndex`.
300 trait_impls.sort_unstable_by_key(|def_id| {
301 (-(def_id.krate.as_u32() as i64), def_id.index.as_array_index())
304 for impl_def_id in trait_impls {
305 if impl_def_id.is_local() {
306 // This is where impl overlap checking happens:
307 let insert_result = sg.insert(tcx, impl_def_id);
308 // Report error if there was one.
309 let (overlap, used_to_be_allowed) = match insert_result {
310 Err(overlap) => (Some(overlap), None),
311 Ok(Some(overlap)) => (Some(overlap.error), Some(overlap.kind)),
312 Ok(None) => (None, None)
315 if let Some(overlap) = overlap {
316 let msg = format!("conflicting implementations of trait `{}`{}:{}",
318 overlap.self_desc.clone().map_or(
319 String::new(), |ty| {
320 format!(" for type `{}`", ty)
322 match used_to_be_allowed {
323 Some(FutureCompatOverlapErrorKind::Issue33140) => " (E0119)",
327 let impl_span = tcx.sess.source_map().def_span(
328 tcx.span_of_impl(impl_def_id).unwrap()
330 let mut err = match used_to_be_allowed {
331 Some(FutureCompatOverlapErrorKind::Issue43355) | None =>
332 struct_span_err!(tcx.sess,
338 let lint = match kind {
339 FutureCompatOverlapErrorKind::Issue43355 =>
340 unreachable!("converted to hard error above"),
341 FutureCompatOverlapErrorKind::Issue33140 =>
342 lint::builtin::ORDER_DEPENDENT_TRAIT_OBJECTS,
344 tcx.struct_span_lint_hir(
346 tcx.hir().as_local_hir_id(impl_def_id).unwrap(),
352 match tcx.span_of_impl(overlap.with_impl) {
354 err.span_label(tcx.sess.source_map().def_span(span),
355 "first implementation here".to_string());
356 err.span_label(impl_span,
357 format!("conflicting implementation{}",
359 .map_or(String::new(),
360 |ty| format!(" for `{}`", ty))));
363 let msg = match to_pretty_impl_header(tcx, overlap.with_impl) {
365 "conflicting implementation in crate `{}`:\n- {}", cname, s),
366 None => format!("conflicting implementation in crate `{}`", cname),
372 for cause in &overlap.intercrate_ambiguity_causes {
373 cause.add_intercrate_ambiguity_hint(&mut err);
376 if overlap.involves_placeholder {
377 coherence::add_placeholder_note(&mut err);
383 let parent = tcx.impl_parent(impl_def_id).unwrap_or(trait_id);
384 sg.record_impl_from_cstore(tcx, parent, impl_def_id)
391 /// Recovers the "impl X for Y" signature from `impl_def_id` and returns it as a
393 fn to_pretty_impl_header(tcx: TyCtxt<'_, '_, '_>, impl_def_id: DefId) -> Option<String> {
396 let trait_ref = if let Some(tr) = tcx.impl_trait_ref(impl_def_id) {
402 let mut w = "impl".to_owned();
404 let substs = InternalSubsts::identity_for_item(tcx, impl_def_id);
406 // FIXME: Currently only handles ?Sized.
407 // Needs to support ?Move and ?DynSized when they are implemented.
408 let mut types_without_default_bounds = FxHashSet::default();
409 let sized_trait = tcx.lang_items().sized_trait();
411 if !substs.is_noop() {
412 types_without_default_bounds.extend(substs.types());
414 w.push_str(&substs.iter()
415 .map(|k| k.to_string())
416 .filter(|k| k != "'_")
417 .collect::<Vec<_>>().join(", "));
421 write!(w, " {} for {}", trait_ref, tcx.type_of(impl_def_id)).unwrap();
423 // The predicates will contain default bounds like `T: Sized`. We need to
424 // remove these bounds, and add `T: ?Sized` to any untouched type parameters.
425 let predicates = &tcx.predicates_of(impl_def_id).predicates;
426 let mut pretty_predicates = Vec::with_capacity(
427 predicates.len() + types_without_default_bounds.len());
429 for (p, _) in predicates {
430 if let Some(poly_trait_ref) = p.to_opt_poly_trait_ref() {
431 if Some(poly_trait_ref.def_id()) == sized_trait {
432 types_without_default_bounds.remove(poly_trait_ref.self_ty());
436 pretty_predicates.push(p.to_string());
439 pretty_predicates.extend(
440 types_without_default_bounds.iter().map(|ty| format!("{}: ?Sized", ty))
443 if !pretty_predicates.is_empty() {
444 write!(w, "\n where {}", pretty_predicates.join(", ")).unwrap();