]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/specialize/mod.rs
rustc: ban registering obligations during InferCtxt snapshots.
[rust.git] / src / librustc / traits / specialize / mod.rs
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.
4 //
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.
10
11 // Logic and data structures related to impl specialization, explained in
12 // greater detail below.
13 //
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.
16 //
17 // See traits/README.md for a bit more detail on how specialization
18 // fits together with the rest of the trait machinery.
19
20 use super::{SelectionContext, FulfillmentContext};
21 use super::util::impl_trait_ref_and_oblig;
22
23 use rustc_data_structures::fx::FxHashMap;
24 use hir::def_id::DefId;
25 use infer::{InferCtxt, InferOk};
26 use middle::region;
27 use ty::subst::{Subst, Substs};
28 use traits::{self, Reveal, ObligationCause};
29 use ty::{self, TyCtxt, TypeFoldable};
30 use syntax_pos::DUMMY_SP;
31
32 pub mod specialization_graph;
33
34 /// Information pertinent to an overlapping impl error.
35 pub struct OverlapError {
36     pub with_impl: DefId,
37     pub trait_desc: String,
38     pub self_desc: Option<String>,
39 }
40
41 /// Given a subst for the requested impl, translate it to a subst
42 /// appropriate for the actual item definition (whether it be in that impl,
43 /// a parent impl, or the trait).
44 /// When we have selected one impl, but are actually using item definitions from
45 /// a parent impl providing a default, we need a way to translate between the
46 /// type parameters of the two impls. Here the `source_impl` is the one we've
47 /// selected, and `source_substs` is a substitution of its generics.
48 /// And `target_node` is the impl/trait we're actually going to get the
49 /// definition from. The resulting substitution will map from `target_node`'s
50 /// generics to `source_impl`'s generics as instantiated by `source_subst`.
51 ///
52 /// For example, consider the following scenario:
53 ///
54 /// ```rust
55 /// trait Foo { ... }
56 /// impl<T, U> Foo for (T, U) { ... }  // target impl
57 /// impl<V> Foo for (V, V) { ... }     // source impl
58 /// ```
59 ///
60 /// Suppose we have selected "source impl" with `V` instantiated with `u32`.
61 /// This function will produce a substitution with `T` and `U` both mapping to `u32`.
62 ///
63 /// Where clauses add some trickiness here, because they can be used to "define"
64 /// an argument indirectly:
65 ///
66 /// ```rust
67 /// impl<'a, I, T: 'a> Iterator for Cloned<I>
68 ///    where I: Iterator<Item=&'a T>, T: Clone
69 /// ```
70 ///
71 /// In a case like this, the substitution for `T` is determined indirectly,
72 /// through associated type projection. We deal with such cases by using
73 /// *fulfillment* to relate the two impls, requiring that all projections are
74 /// resolved.
75 pub fn translate_substs<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
76                                         source_impl: DefId,
77                                         source_substs: &'tcx Substs<'tcx>,
78                                         target_node: specialization_graph::Node)
79                                         -> &'tcx Substs<'tcx> {
80     let source_trait_ref = infcx.tcx
81                                 .impl_trait_ref(source_impl)
82                                 .unwrap()
83                                 .subst(infcx.tcx, &source_substs);
84
85     // translate the Self and TyParam parts of the substitution, since those
86     // vary across impls
87     let target_substs = match target_node {
88         specialization_graph::Node::Impl(target_impl) => {
89             // no need to translate if we're targetting the impl we started with
90             if source_impl == target_impl {
91                 return source_substs;
92             }
93
94             fulfill_implication(infcx, source_trait_ref, target_impl).unwrap_or_else(|_| {
95                 bug!("When translating substitutions for specialization, the expected \
96                       specializaiton failed to hold")
97             })
98         }
99         specialization_graph::Node::Trait(..) => source_trait_ref.substs,
100     };
101
102     // directly inherent the method generics, since those do not vary across impls
103     source_substs.rebase_onto(infcx.tcx, source_impl, target_substs)
104 }
105
106 /// Given a selected impl described by `impl_data`, returns the
107 /// definition and substitions for the method with the name `name`
108 /// the kind `kind`, and trait method substitutions `substs`, in
109 /// that impl, a less specialized impl, or the trait default,
110 /// whichever applies.
111 pub fn find_associated_item<'a, 'tcx>(
112     tcx: TyCtxt<'a, 'tcx, 'tcx>,
113     item: &ty::AssociatedItem,
114     substs: &'tcx Substs<'tcx>,
115     impl_data: &super::VtableImplData<'tcx, ()>,
116 ) -> (DefId, &'tcx Substs<'tcx>) {
117     assert!(!substs.needs_infer());
118
119     let trait_def_id = tcx.trait_id_of_impl(impl_data.impl_def_id).unwrap();
120     let trait_def = tcx.lookup_trait_def(trait_def_id);
121
122     let ancestors = trait_def.ancestors(impl_data.impl_def_id);
123     match ancestors.defs(tcx, item.name, item.kind).next() {
124         Some(node_item) => {
125             let substs = tcx.infer_ctxt((), Reveal::All).enter(|infcx| {
126                 let substs = substs.rebase_onto(tcx, trait_def_id, impl_data.substs);
127                 let substs = translate_substs(&infcx, impl_data.impl_def_id,
128                                               substs, node_item.node);
129                 let substs = infcx.tcx.erase_regions(&substs);
130                 tcx.lift(&substs).unwrap_or_else(|| {
131                     bug!("find_method: translate_substs \
132                           returned {:?} which contains inference types/regions",
133                          substs);
134                 })
135             });
136             (node_item.item.def_id, substs)
137         }
138         None => {
139             bug!("{:?} not found in {:?}", item, impl_data.impl_def_id)
140         }
141     }
142 }
143
144 /// Is impl1 a specialization of impl2?
145 ///
146 /// Specialization is determined by the sets of types to which the impls apply;
147 /// impl1 specializes impl2 if it applies to a subset of the types impl2 applies
148 /// to.
149 pub fn specializes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
150                              impl1_def_id: DefId,
151                              impl2_def_id: DefId) -> bool {
152     debug!("specializes({:?}, {:?})", impl1_def_id, impl2_def_id);
153
154     if let Some(r) = tcx.specializes_cache.borrow().check(impl1_def_id, impl2_def_id) {
155         return r;
156     }
157
158     // The feature gate should prevent introducing new specializations, but not
159     // taking advantage of upstream ones.
160     if !tcx.sess.features.borrow().specialization &&
161         (impl1_def_id.is_local() || impl2_def_id.is_local()) {
162         return false;
163     }
164
165     // We determine whether there's a subset relationship by:
166     //
167     // - skolemizing impl1,
168     // - assuming the where clauses for impl1,
169     // - instantiating impl2 with fresh inference variables,
170     // - unifying,
171     // - attempting to prove the where clauses for impl2
172     //
173     // The last three steps are encapsulated in `fulfill_implication`.
174     //
175     // See RFC 1210 for more details and justification.
176
177     // Currently we do not allow e.g. a negative impl to specialize a positive one
178     if tcx.trait_impl_polarity(impl1_def_id) != tcx.trait_impl_polarity(impl2_def_id) {
179         return false;
180     }
181
182     // create a parameter environment corresponding to a (skolemized) instantiation of impl1
183     let penv = tcx.construct_parameter_environment(DUMMY_SP,
184                                                    impl1_def_id,
185                                                    region::DUMMY_CODE_EXTENT);
186     let impl1_trait_ref = tcx.impl_trait_ref(impl1_def_id)
187                              .unwrap()
188                              .subst(tcx, &penv.free_substs);
189
190     // Create a infcx, taking the predicates of impl1 as assumptions:
191     let result = tcx.infer_ctxt(penv, Reveal::UserFacing).enter(|infcx| {
192         // Normalize the trait reference. The WF rules ought to ensure
193         // that this always succeeds.
194         let impl1_trait_ref =
195             match traits::fully_normalize(&infcx, ObligationCause::dummy(), &impl1_trait_ref) {
196                 Ok(impl1_trait_ref) => impl1_trait_ref,
197                 Err(err) => {
198                     bug!("failed to fully normalize {:?}: {:?}", impl1_trait_ref, err);
199                 }
200             };
201
202         // Attempt to prove that impl2 applies, given all of the above.
203         fulfill_implication(&infcx, impl1_trait_ref, impl2_def_id).is_ok()
204     });
205
206     tcx.specializes_cache.borrow_mut().insert(impl1_def_id, impl2_def_id, result);
207     result
208 }
209
210 /// Attempt to fulfill all obligations of `target_impl` after unification with
211 /// `source_trait_ref`. If successful, returns a substitution for *all* the
212 /// generics of `target_impl`, including both those needed to unify with
213 /// `source_trait_ref` and those whose identity is determined via a where
214 /// clause in the impl.
215 fn fulfill_implication<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
216                                        source_trait_ref: ty::TraitRef<'tcx>,
217                                        target_impl: DefId)
218                                        -> Result<&'tcx Substs<'tcx>, ()> {
219     let selcx = &mut SelectionContext::new(&infcx);
220     let target_substs = infcx.fresh_substs_for_item(DUMMY_SP, target_impl);
221     let (target_trait_ref, obligations) = impl_trait_ref_and_oblig(selcx,
222                                                                    target_impl,
223                                                                    target_substs);
224
225     // do the impls unify? If not, no specialization.
226     match infcx.eq_trait_refs(true,
227                               &ObligationCause::dummy(),
228                               source_trait_ref,
229                               target_trait_ref) {
230         Ok(InferOk { obligations, .. }) => {
231             // FIXME(#32730) propagate obligations
232             assert!(obligations.is_empty())
233         }
234         Err(_) => {
235             debug!("fulfill_implication: {:?} does not unify with {:?}",
236                    source_trait_ref,
237                    target_trait_ref);
238             return Err(());
239         }
240     }
241
242     // attempt to prove all of the predicates for impl2 given those for impl1
243     // (which are packed up in penv)
244
245     infcx.save_and_restore_in_snapshot_flag(|infcx| {
246         let mut fulfill_cx = FulfillmentContext::new();
247         for oblig in obligations.into_iter() {
248             fulfill_cx.register_predicate_obligation(&infcx, oblig);
249         }
250         match fulfill_cx.select_all_or_error(infcx) {
251             Err(errors) => {
252                 // no dice!
253                 debug!("fulfill_implication: for impls on {:?} and {:?}, \
254                         could not fulfill: {:?} given {:?}",
255                        source_trait_ref,
256                        target_trait_ref,
257                        errors,
258                        infcx.parameter_environment.caller_bounds);
259                 Err(())
260             }
261
262             Ok(()) => {
263                 debug!("fulfill_implication: an impl for {:?} specializes {:?}",
264                        source_trait_ref,
265                        target_trait_ref);
266
267                 // Now resolve the *substitution* we built for the target earlier, replacing
268                 // the inference variables inside with whatever we got from fulfillment.
269                 Ok(infcx.resolve_type_vars_if_possible(&target_substs))
270             }
271         }
272     })
273 }
274
275 pub struct SpecializesCache {
276     map: FxHashMap<(DefId, DefId), bool>,
277 }
278
279 impl SpecializesCache {
280     pub fn new() -> Self {
281         SpecializesCache {
282             map: FxHashMap()
283         }
284     }
285
286     pub fn check(&self, a: DefId, b: DefId) -> Option<bool> {
287         self.map.get(&(a, b)).cloned()
288     }
289
290     pub fn insert(&mut self, a: DefId, b: DefId, result: bool) {
291         self.map.insert((a, b), result);
292     }
293 }