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