1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Logic and data structures related to impl specialization, explained in
12 //! greater detail below.
14 //! At the moment, this implementation support only the simple "chain" rule:
15 //! If any two impls overlap, one must be a strict subset of the other.
17 //! See the [rustc guide] for a bit more detail on how specialization
18 //! fits together with the rest of the trait machinery.
20 //! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/traits/specialization.html
22 use super::{SelectionContext, FulfillmentContext};
23 use super::util::impl_trait_ref_and_oblig;
25 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
26 use hir::def_id::DefId;
27 use infer::{InferCtxt, InferOk};
28 use ty::subst::{Subst, Substs};
29 use traits::{self, ObligationCause, TraitEngine};
30 use traits::select::IntercrateAmbiguityCause;
31 use ty::{self, TyCtxt, TypeFoldable};
32 use syntax_pos::DUMMY_SP;
33 use rustc_data_structures::sync::Lrc;
37 pub mod specialization_graph;
39 /// Information pertinent to an overlapping impl error.
40 pub struct OverlapError {
42 pub trait_desc: String,
43 pub self_desc: Option<String>,
44 pub intercrate_ambiguity_causes: Vec<IntercrateAmbiguityCause>,
47 /// Given a subst for the requested impl, translate it to a subst
48 /// appropriate for the actual item definition (whether it be in that impl,
49 /// a parent impl, or the trait).
51 /// When we have selected one impl, but are actually using item definitions from
52 /// a parent impl providing a default, we need a way to translate between the
53 /// type parameters of the two impls. Here the `source_impl` is the one we've
54 /// selected, and `source_substs` is a substitution of its generics.
55 /// And `target_node` is the impl/trait we're actually going to get the
56 /// definition from. The resulting substitution will map from `target_node`'s
57 /// generics to `source_impl`'s generics as instantiated by `source_subst`.
59 /// For example, consider the following scenario:
63 /// impl<T, U> Foo for (T, U) { ... } // target impl
64 /// impl<V> Foo for (V, V) { ... } // source impl
67 /// Suppose we have selected "source impl" with `V` instantiated with `u32`.
68 /// This function will produce a substitution with `T` and `U` both mapping to `u32`.
70 /// Where clauses add some trickiness here, because they can be used to "define"
71 /// an argument indirectly:
74 /// impl<'a, I, T: 'a> Iterator for Cloned<I>
75 /// where I: Iterator<Item=&'a T>, T: Clone
78 /// In a case like this, the substitution for `T` is determined indirectly,
79 /// through associated type projection. We deal with such cases by using
80 /// *fulfillment* to relate the two impls, requiring that all projections are
82 pub fn translate_substs<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
83 param_env: ty::ParamEnv<'tcx>,
85 source_substs: &'tcx Substs<'tcx>,
86 target_node: specialization_graph::Node)
87 -> &'tcx Substs<'tcx> {
88 let source_trait_ref = infcx.tcx
89 .impl_trait_ref(source_impl)
91 .subst(infcx.tcx, &source_substs);
93 // translate the Self and Param parts of the substitution, since those
95 let target_substs = match target_node {
96 specialization_graph::Node::Impl(target_impl) => {
97 // no need to translate if we're targeting the impl we started with
98 if source_impl == target_impl {
102 fulfill_implication(infcx, param_env, source_trait_ref, target_impl)
104 bug!("When translating substitutions for specialization, the expected \
105 specialization failed to hold")
108 specialization_graph::Node::Trait(..) => source_trait_ref.substs,
111 // directly inherent the method generics, since those do not vary across impls
112 source_substs.rebase_onto(infcx.tcx, source_impl, target_substs)
115 /// Given a selected impl described by `impl_data`, returns the
116 /// definition and substitutions for the method with the name `name`
117 /// the kind `kind`, and trait method substitutions `substs`, in
118 /// that impl, a less specialized impl, or the trait default,
119 /// whichever applies.
120 pub fn find_associated_item<'a, 'tcx>(
121 tcx: TyCtxt<'a, 'tcx, 'tcx>,
122 item: &ty::AssociatedItem,
123 substs: &'tcx Substs<'tcx>,
124 impl_data: &super::VtableImplData<'tcx, ()>,
125 ) -> (DefId, &'tcx Substs<'tcx>) {
126 assert!(!substs.needs_infer());
128 let trait_def_id = tcx.trait_id_of_impl(impl_data.impl_def_id).unwrap();
129 let trait_def = tcx.trait_def(trait_def_id);
131 let ancestors = trait_def.ancestors(tcx, impl_data.impl_def_id);
132 match ancestors.defs(tcx, item.ident, item.kind, trait_def_id).next() {
134 let substs = tcx.infer_ctxt().enter(|infcx| {
135 let param_env = ty::ParamEnv::reveal_all();
136 let substs = substs.rebase_onto(tcx, trait_def_id, impl_data.substs);
137 let substs = translate_substs(&infcx, param_env, impl_data.impl_def_id,
138 substs, node_item.node);
139 let substs = infcx.tcx.erase_regions(&substs);
140 tcx.lift(&substs).unwrap_or_else(||
141 bug!("find_method: translate_substs \
142 returned {:?} which contains inference types/regions",
146 (node_item.item.def_id, substs)
148 None => bug!("{:?} not found in {:?}", item, impl_data.impl_def_id)
152 /// Is impl1 a specialization of impl2?
154 /// Specialization is determined by the sets of types to which the impls apply;
155 /// impl1 specializes impl2 if it applies to a subset of the types impl2 applies
157 pub(super) fn specializes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
158 (impl1_def_id, impl2_def_id): (DefId, DefId))
161 debug!("specializes({:?}, {:?})", impl1_def_id, impl2_def_id);
163 // The feature gate should prevent introducing new specializations, but not
164 // taking advantage of upstream ones.
165 if !tcx.features().specialization &&
166 (impl1_def_id.is_local() || impl2_def_id.is_local()) {
170 // We determine whether there's a subset relationship by:
172 // - skolemizing impl1,
173 // - assuming the where clauses for impl1,
174 // - instantiating impl2 with fresh inference variables,
176 // - attempting to prove the where clauses for impl2
178 // The last three steps are encapsulated in `fulfill_implication`.
180 // See RFC 1210 for more details and justification.
182 // Currently we do not allow e.g. a negative impl to specialize a positive one
183 if tcx.impl_polarity(impl1_def_id) != tcx.impl_polarity(impl2_def_id) {
187 // create a parameter environment corresponding to a (skolemized) instantiation of impl1
188 let penv = tcx.param_env(impl1_def_id);
189 let impl1_trait_ref = tcx.impl_trait_ref(impl1_def_id).unwrap();
191 // Create a infcx, taking the predicates of impl1 as assumptions:
192 tcx.infer_ctxt().enter(|infcx| {
193 // Normalize the trait reference. The WF rules ought to ensure
194 // that this always succeeds.
195 let impl1_trait_ref =
196 match traits::fully_normalize(&infcx,
197 FulfillmentContext::new(),
198 ObligationCause::dummy(),
201 Ok(impl1_trait_ref) => impl1_trait_ref,
203 bug!("failed to fully normalize {:?}: {:?}", impl1_trait_ref, err);
207 // Attempt to prove that impl2 applies, given all of the above.
208 fulfill_implication(&infcx, penv, impl1_trait_ref, impl2_def_id).is_ok()
212 /// Attempt to fulfill all obligations of `target_impl` after unification with
213 /// `source_trait_ref`. If successful, returns a substitution for *all* the
214 /// generics of `target_impl`, including both those needed to unify with
215 /// `source_trait_ref` and those whose identity is determined via a where
216 /// clause in the impl.
217 fn fulfill_implication<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
218 param_env: ty::ParamEnv<'tcx>,
219 source_trait_ref: ty::TraitRef<'tcx>,
221 -> Result<&'tcx Substs<'tcx>, ()> {
222 let selcx = &mut SelectionContext::new(&infcx);
223 let target_substs = infcx.fresh_substs_for_item(DUMMY_SP, target_impl);
224 let (target_trait_ref, mut obligations) = impl_trait_ref_and_oblig(selcx,
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 pub struct SpecializesCache {
288 map: FxHashMap<(DefId, DefId), bool>,
291 impl SpecializesCache {
292 pub fn new() -> Self {
298 pub fn check(&self, a: DefId, b: DefId) -> Option<bool> {
299 self.map.get(&(a, b)).cloned()
302 pub fn insert(&mut self, a: DefId, b: DefId, result: bool) {
303 self.map.insert((a, b), result);
307 // Query provider for `specialization_graph_of`.
308 pub(super) fn specialization_graph_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
310 -> Lrc<specialization_graph::Graph> {
311 let mut sg = specialization_graph::Graph::new();
313 let mut trait_impls = tcx.all_impls(trait_id);
315 // The coherence checking implementation seems to rely on impls being
316 // iterated over (roughly) in definition order, so we are sorting by
317 // negated CrateNum (so remote definitions are visited first) and then
318 // by a flattened version of the DefIndex.
319 trait_impls.sort_unstable_by_key(|def_id| {
320 (-(def_id.krate.as_u32() as i64),
321 def_id.index.address_space().index(),
322 def_id.index.as_array_index())
325 for impl_def_id in trait_impls {
326 if impl_def_id.is_local() {
327 // This is where impl overlap checking happens:
328 let insert_result = sg.insert(tcx, impl_def_id);
329 // Report error if there was one.
330 let (overlap, used_to_be_allowed) = match insert_result {
331 Err(overlap) => (Some(overlap), false),
332 Ok(opt_overlap) => (opt_overlap, true)
335 if let Some(overlap) = overlap {
336 let msg = format!("conflicting implementations of trait `{}`{}:{}",
338 overlap.self_desc.clone().map_or(
339 String::new(), |ty| {
340 format!(" for type `{}`", ty)
342 if used_to_be_allowed { " (E0119)" } else { "" }
344 let impl_span = tcx.sess.source_map().def_span(
345 tcx.span_of_impl(impl_def_id).unwrap()
347 let mut err = if used_to_be_allowed {
348 tcx.struct_span_lint_node(
349 lint::builtin::INCOHERENT_FUNDAMENTAL_IMPLS,
350 tcx.hir.as_local_node_id(impl_def_id).unwrap(),
354 struct_span_err!(tcx.sess,
361 match tcx.span_of_impl(overlap.with_impl) {
363 err.span_label(tcx.sess.source_map().def_span(span),
364 "first implementation here".to_string());
365 err.span_label(impl_span,
366 format!("conflicting implementation{}",
368 .map_or(String::new(),
369 |ty| format!(" for `{}`", ty))));
372 let msg = match to_pretty_impl_header(tcx, overlap.with_impl) {
374 "conflicting implementation in crate `{}`:\n- {}", cname, s),
375 None => format!("conflicting implementation in crate `{}`", cname),
381 for cause in &overlap.intercrate_ambiguity_causes {
382 cause.add_intercrate_ambiguity_hint(&mut err);
388 let parent = tcx.impl_parent(impl_def_id).unwrap_or(trait_id);
389 sg.record_impl_from_cstore(tcx, parent, impl_def_id)
396 /// Recovers the "impl X for Y" signature from `impl_def_id` and returns it as a
398 fn to_pretty_impl_header(tcx: TyCtxt<'_, '_, '_>, impl_def_id: DefId) -> Option<String> {
401 let trait_ref = if let Some(tr) = tcx.impl_trait_ref(impl_def_id) {
407 let mut w = "impl".to_owned();
409 let substs = Substs::identity_for_item(tcx, impl_def_id);
411 // FIXME: Currently only handles ?Sized.
412 // Needs to support ?Move and ?DynSized when they are implemented.
413 let mut types_without_default_bounds = FxHashSet::default();
414 let sized_trait = tcx.lang_items().sized_trait();
416 if !substs.is_noop() {
417 types_without_default_bounds.extend(substs.types());
419 w.push_str(&substs.iter().map(|k| k.to_string()).collect::<Vec<_>>().join(", "));
423 write!(w, " {} for {}", trait_ref, tcx.type_of(impl_def_id)).unwrap();
425 // The predicates will contain default bounds like `T: Sized`. We need to
426 // remove these bounds, and add `T: ?Sized` to any untouched type parameters.
427 let predicates = tcx.predicates_of(impl_def_id).predicates;
428 let mut pretty_predicates = Vec::with_capacity(
429 predicates.len() + types_without_default_bounds.len());
431 for (p, _) in predicates {
432 if let Some(poly_trait_ref) = p.to_opt_poly_trait_ref() {
433 if Some(poly_trait_ref.def_id()) == sized_trait {
434 types_without_default_bounds.remove(poly_trait_ref.self_ty());
438 pretty_predicates.push(p.to_string());
441 pretty_predicates.extend(
442 types_without_default_bounds.iter().map(|ty| format!("{}: ?Sized", ty))
445 if !pretty_predicates.is_empty() {
446 write!(w, "\n where {}", pretty_predicates.join(", ")).unwrap();