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.
18 use super::SelectionContext;
20 use middle::cstore::CrateStore;
21 use middle::def_id::DefId;
22 use middle::infer::{self, InferCtxt, TypeOrigin};
24 use middle::subst::{Subst, Substs};
27 use syntax::codemap::DUMMY_SP;
28 use util::nodemap::DefIdMap;
30 /// A per-trait graph of impls in specialization order.
32 /// The graph provides two key services:
34 /// - Construction, which implicitly checks for overlapping impls (i.e., impls
35 /// that overlap but where neither specializes the other -- an artifact of the
36 /// simple "chain" rule.
38 /// - Parent extraction. In particular, the graph can give you the *immediate*
39 /// parents of a given specializing impl, which is needed for extracting
40 /// default items amongst other thigns. In the simple "chain" rule, every impl
41 /// has at most one parent.
42 pub struct SpecializationGraph {
43 // all impls have a parent; the "root" impls have as their parent the def_id
45 parent: DefIdMap<DefId>,
47 // the "root" impls are found by looking up the trait's def_id.
48 children: DefIdMap<Vec<DefId>>,
51 /// Information pertinent to an overlapping impl error.
52 pub struct Overlap<'tcx> {
54 pub on_trait_ref: ty::TraitRef<'tcx>,
57 impl SpecializationGraph {
58 pub fn new() -> SpecializationGraph {
60 parent: Default::default(),
61 children: Default::default(),
65 /// Insert a local impl into the specialization graph. If an existing impl
66 /// conflicts with it (has overlap, but neither specializes the other),
67 /// information about the area of overlap is returned in the `Err`.
68 pub fn insert<'tcx>(&mut self,
71 trait_ref: ty::TraitRef)
72 -> Result<(), Overlap<'tcx>> {
73 assert!(impl_def_id.is_local());
75 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, None, false);
76 let mut parent = trait_ref.def_id;
78 let mut my_children = vec![];
80 // descend the existing tree, looking for the right location to add this impl
82 let mut possible_siblings = self.children.entry(parent).or_insert(vec![]);
84 for slot in possible_siblings.iter_mut() {
85 let possible_sibling = *slot;
87 let overlap = infcx.probe(|_| {
88 traits::overlapping_impls(&infcx, possible_sibling, impl_def_id)
91 if let Some(trait_ref) = overlap {
92 let le = specializes(&infcx, impl_def_id, possible_sibling);
93 let ge = specializes(&infcx, possible_sibling, impl_def_id);
96 // the impl specializes possible_sibling
97 parent = possible_sibling;
100 // possible_sibling specializes the impl
102 self.parent.insert(possible_sibling, impl_def_id);
103 my_children.push(possible_sibling);
105 // overlap, but no specialization; error out
107 with_impl: possible_sibling,
108 on_trait_ref: trait_ref,
116 // no overlap with any potential siblings, so add as a new sibling
117 self.parent.insert(impl_def_id, parent);
118 possible_siblings.push(impl_def_id);
122 if self.children.insert(impl_def_id, my_children).is_some() {
123 panic!("When inserting an impl into the specialization graph, existing children for \
124 the impl were already present.");
130 /// Insert cached metadata mapping from a child impl back to its parent
131 pub fn record_impl_from_cstore(&mut self, parent: DefId, child: DefId) {
132 if self.parent.insert(child, Some(parent)).is_some() {
133 panic!("When recording an impl from the crate store, information about its parent \
134 was already present.");
137 self.children.entry(parent).or_insert(vec![]).push(child);
141 fn skolemizing_subst_for_impl<'a>(tcx: &ty::ctxt<'a>, impl_def_id: DefId) -> Substs<'a> {
142 let impl_generics = tcx.lookup_item_type(impl_def_id).generics;
144 let types = impl_generics.types.map(|def| tcx.mk_param_from_def(def));
146 // FIXME: figure out what we actually want here
147 let regions = impl_generics.regions.map(|_| ty::Region::ReStatic);
148 // |d| infcx.next_region_var(infer::RegionVariableOrigin::EarlyBoundRegion(span, d.name)));
150 Substs::new(types, regions)
153 /// Is impl1 a specialization of impl2?
155 /// Specialization is determined by the sets of types to which the impls apply;
156 /// impl1 specializes impl2 if it applies to a subset of the types impl2 applies
158 pub fn specializes(infcx: &InferCtxt, impl1_def_id: DefId, impl2_def_id: DefId) -> bool {
159 let tcx = &infcx.tcx;
161 // We determine whether there's a subset relationship by:
163 // - skolemizing impl1,
164 // - assuming the where clauses for impl1,
166 // - attempting to prove the where clauses for impl2
168 // See RFC 1210 for more details and justification.
170 let impl1_substs = skolemizing_subst_for_impl(tcx, impl1_def_id);
171 let (impl1_trait_ref, impl1_obligations) = {
172 let selcx = &mut SelectionContext::new(&infcx);
173 util::impl_trait_ref_and_oblig(selcx, impl1_def_id, &impl1_substs)
176 let impl1_predicates: Vec<_> = impl1_obligations.iter()
178 .map(|oblig| oblig.predicate)
181 let penv = ty::ParameterEnvironment {
183 free_substs: impl1_substs,
184 implicit_region_bound: ty::ReEmpty, // FIXME: is this OK?
185 caller_bounds: impl1_predicates,
186 selection_cache: traits::SelectionCache::new(),
187 evaluation_cache: traits::EvaluationCache::new(),
188 free_id_outlive: region::DUMMY_CODE_EXTENT, // FIXME: is this OK?
191 // FIXME: unclear what `errors_will_be_reported` should be here...
192 let infcx = infer::new_infer_ctxt(tcx, infcx.tables, Some(penv), true);
193 let selcx = &mut SelectionContext::new(&infcx);
195 let impl2_substs = util::fresh_type_vars_for_impl(&infcx, DUMMY_SP, impl2_def_id);
196 let (impl2_trait_ref, impl2_obligations) =
197 util::impl_trait_ref_and_oblig(selcx, impl2_def_id, &impl2_substs);
199 // do the impls unify? If not, no specialization.
200 if let Err(_) = infer::mk_eq_trait_refs(&infcx,
202 TypeOrigin::Misc(DUMMY_SP),
205 debug!("specializes: {:?} does not unify with {:?}",
211 let mut fulfill_cx = infcx.fulfillment_cx.borrow_mut();
213 // attempt to prove all of the predicates for impl2 given those for impl1
214 // (which are packed up in penv)
215 for oblig in impl2_obligations.into_iter() {
216 fulfill_cx.register_predicate_obligation(&infcx, oblig);
219 if let Err(errors) = infer::drain_fulfillment_cx(&infcx, &mut fulfill_cx, &()) {
220 debug!("specializes: for impls on {:?} and {:?}, could not fulfill: {:?} given {:?}",
224 infcx.parameter_environment.caller_bounds);
228 debug!("specializes: an impl for {:?} specializes {:?} (`where` clauses elided)",