]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/specialize/mod.rs
d11565618a687ede894f069fa6f841c4ab38599c
[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 the [rustc guide] for a bit more detail on how specialization
18 //! fits together with the rest of the trait machinery.
19 //!
20 //! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/trait-specialization.html
21
22 use super::{SelectionContext, FulfillmentContext};
23 use super::util::impl_trait_ref_and_oblig;
24
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, Reveal, ObligationCause};
30 use traits::select::IntercrateAmbiguityCause;
31 use ty::{self, TyCtxt, TypeFoldable};
32 use syntax_pos::DUMMY_SP;
33 use rustc_data_structures::sync::Lrc;
34
35 use lint;
36
37 pub mod specialization_graph;
38
39 /// Information pertinent to an overlapping impl error.
40 pub struct OverlapError {
41     pub with_impl: DefId,
42     pub trait_desc: String,
43     pub self_desc: Option<String>,
44     pub intercrate_ambiguity_causes: Vec<IntercrateAmbiguityCause>,
45 }
46
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).
50 ///
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`.
58 ///
59 /// For example, consider the following scenario:
60 ///
61 /// ```rust
62 /// trait Foo { ... }
63 /// impl<T, U> Foo for (T, U) { ... }  // target impl
64 /// impl<V> Foo for (V, V) { ... }     // source impl
65 /// ```
66 ///
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`.
69 ///
70 /// Where clauses add some trickiness here, because they can be used to "define"
71 /// an argument indirectly:
72 ///
73 /// ```rust
74 /// impl<'a, I, T: 'a> Iterator for Cloned<I>
75 ///    where I: Iterator<Item=&'a T>, T: Clone
76 /// ```
77 ///
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
81 /// resolved.
82 pub fn translate_substs<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
83                                         param_env: ty::ParamEnv<'tcx>,
84                                         source_impl: DefId,
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)
90                                 .unwrap()
91                                 .subst(infcx.tcx, &source_substs);
92
93     // translate the Self and TyParam parts of the substitution, since those
94     // vary across impls
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 {
99                 return source_substs;
100             }
101
102             fulfill_implication(infcx, param_env, source_trait_ref, target_impl)
103                 .unwrap_or_else(|_| {
104                     bug!("When translating substitutions for specialization, the expected \
105                           specialization failed to hold")
106                 })
107         }
108         specialization_graph::Node::Trait(..) => source_trait_ref.substs,
109     };
110
111     // directly inherent the method generics, since those do not vary across impls
112     source_substs.rebase_onto(infcx.tcx, source_impl, target_substs)
113 }
114
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());
127
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);
130
131     let ancestors = trait_def.ancestors(tcx, impl_data.impl_def_id);
132     match ancestors.defs(tcx, item.name, item.kind, trait_def_id).next() {
133         Some(node_item) => {
134             let substs = tcx.infer_ctxt().enter(|infcx| {
135                 let param_env = ty::ParamEnv::empty(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",
143                          substs);
144                 })
145             });
146             (node_item.item.def_id, substs)
147         }
148         None => {
149             bug!("{:?} not found in {:?}", item, impl_data.impl_def_id)
150         }
151     }
152 }
153
154 /// Is impl1 a specialization of impl2?
155 ///
156 /// Specialization is determined by the sets of types to which the impls apply;
157 /// impl1 specializes impl2 if it applies to a subset of the types impl2 applies
158 /// to.
159 pub(super) fn specializes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
160                                     (impl1_def_id, impl2_def_id): (DefId, DefId))
161     -> bool
162 {
163     debug!("specializes({:?}, {:?})", impl1_def_id, impl2_def_id);
164
165     // The feature gate should prevent introducing new specializations, but not
166     // taking advantage of upstream ones.
167     if !tcx.features().specialization &&
168         (impl1_def_id.is_local() || impl2_def_id.is_local()) {
169         return false;
170     }
171
172     // We determine whether there's a subset relationship by:
173     //
174     // - skolemizing impl1,
175     // - assuming the where clauses for impl1,
176     // - instantiating impl2 with fresh inference variables,
177     // - unifying,
178     // - attempting to prove the where clauses for impl2
179     //
180     // The last three steps are encapsulated in `fulfill_implication`.
181     //
182     // See RFC 1210 for more details and justification.
183
184     // Currently we do not allow e.g. a negative impl to specialize a positive one
185     if tcx.impl_polarity(impl1_def_id) != tcx.impl_polarity(impl2_def_id) {
186         return false;
187     }
188
189     // create a parameter environment corresponding to a (skolemized) instantiation of impl1
190     let penv = tcx.param_env(impl1_def_id);
191     let impl1_trait_ref = tcx.impl_trait_ref(impl1_def_id).unwrap();
192
193     // Create a infcx, taking the predicates of impl1 as assumptions:
194     tcx.infer_ctxt().enter(|infcx| {
195         // Normalize the trait reference. The WF rules ought to ensure
196         // that this always succeeds.
197         let impl1_trait_ref =
198             match traits::fully_normalize(&infcx,
199                                           ObligationCause::dummy(),
200                                           penv,
201                                           &impl1_trait_ref) {
202                 Ok(impl1_trait_ref) => impl1_trait_ref,
203                 Err(err) => {
204                     bug!("failed to fully normalize {:?}: {:?}", impl1_trait_ref, err);
205                 }
206             };
207
208         // Attempt to prove that impl2 applies, given all of the above.
209         fulfill_implication(&infcx, penv, impl1_trait_ref, impl2_def_id).is_ok()
210     })
211 }
212
213 /// Attempt to fulfill all obligations of `target_impl` after unification with
214 /// `source_trait_ref`. If successful, returns a substitution for *all* the
215 /// generics of `target_impl`, including both those needed to unify with
216 /// `source_trait_ref` and those whose identity is determined via a where
217 /// clause in the impl.
218 fn fulfill_implication<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
219                                        param_env: ty::ParamEnv<'tcx>,
220                                        source_trait_ref: ty::TraitRef<'tcx>,
221                                        target_impl: DefId)
222                                        -> Result<&'tcx Substs<'tcx>, ()> {
223     let selcx = &mut SelectionContext::new(&infcx);
224     let target_substs = infcx.fresh_substs_for_item(param_env.universe, DUMMY_SP, target_impl);
225     let (target_trait_ref, mut obligations) = impl_trait_ref_and_oblig(selcx,
226                                                                        param_env,
227                                                                        target_impl,
228                                                                        target_substs);
229
230     // do the impls unify? If not, no specialization.
231     match infcx.at(&ObligationCause::dummy(), param_env)
232                .eq(source_trait_ref, target_trait_ref) {
233         Ok(InferOk { obligations: o, .. }) => {
234             obligations.extend(o);
235         }
236         Err(_) => {
237             debug!("fulfill_implication: {:?} does not unify with {:?}",
238                    source_trait_ref,
239                    target_trait_ref);
240             return Err(());
241         }
242     }
243
244     // attempt to prove all of the predicates for impl2 given those for impl1
245     // (which are packed up in penv)
246
247     infcx.save_and_restore_in_snapshot_flag(|infcx| {
248         // If we came from `translate_substs`, we already know that the
249         // predicates for our impl hold (after all, we know that a more
250         // specialized impl holds, so our impl must hold too), and
251         // we only want to process the projections to determine the
252         // the types in our substs using RFC 447, so we can safely
253         // ignore region obligations, which allows us to avoid threading
254         // a node-id to assign them with.
255         //
256         // If we came from specialization graph construction, then
257         // we already make a mockery out of the region system, so
258         // why not ignore them a bit earlier?
259         let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
260         for oblig in obligations.into_iter() {
261             fulfill_cx.register_predicate_obligation(&infcx, oblig);
262         }
263         match fulfill_cx.select_all_or_error(infcx) {
264             Err(errors) => {
265                 // no dice!
266                 debug!("fulfill_implication: for impls on {:?} and {:?}, \
267                         could not fulfill: {:?} given {:?}",
268                        source_trait_ref,
269                        target_trait_ref,
270                        errors,
271                        param_env.caller_bounds);
272                 Err(())
273             }
274
275             Ok(()) => {
276                 debug!("fulfill_implication: an impl for {:?} specializes {:?}",
277                        source_trait_ref,
278                        target_trait_ref);
279
280                 // Now resolve the *substitution* we built for the target earlier, replacing
281                 // the inference variables inside with whatever we got from fulfillment.
282                 Ok(infcx.resolve_type_vars_if_possible(&target_substs))
283             }
284         }
285     })
286 }
287
288 pub struct SpecializesCache {
289     map: FxHashMap<(DefId, DefId), bool>,
290 }
291
292 impl SpecializesCache {
293     pub fn new() -> Self {
294         SpecializesCache {
295             map: FxHashMap()
296         }
297     }
298
299     pub fn check(&self, a: DefId, b: DefId) -> Option<bool> {
300         self.map.get(&(a, b)).cloned()
301     }
302
303     pub fn insert(&mut self, a: DefId, b: DefId, result: bool) {
304         self.map.insert((a, b), result);
305     }
306 }
307
308 // Query provider for `specialization_graph_of`.
309 pub(super) fn specialization_graph_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
310                                                       trait_id: DefId)
311                                                       -> Lrc<specialization_graph::Graph> {
312     let mut sg = specialization_graph::Graph::new();
313
314     let mut trait_impls = Vec::new();
315     tcx.for_each_impl(trait_id, |impl_did| trait_impls.push(impl_did));
316
317     // The coherence checking implementation seems to rely on impls being
318     // iterated over (roughly) in definition order, so we are sorting by
319     // negated CrateNum (so remote definitions are visited first) and then
320     // by a flattened version of the DefIndex.
321     trait_impls.sort_unstable_by_key(|def_id| {
322         (-(def_id.krate.as_u32() as i64),
323          def_id.index.address_space().index(),
324          def_id.index.as_array_index())
325     });
326
327     for impl_def_id in trait_impls {
328         if impl_def_id.is_local() {
329             // This is where impl overlap checking happens:
330             let insert_result = sg.insert(tcx, impl_def_id);
331             // Report error if there was one.
332             let (overlap, used_to_be_allowed) = match insert_result {
333                 Err(overlap) => (Some(overlap), false),
334                 Ok(opt_overlap) => (opt_overlap, true)
335             };
336
337             if let Some(overlap) = overlap {
338                 let msg = format!("conflicting implementations of trait `{}`{}:{}",
339                     overlap.trait_desc,
340                     overlap.self_desc.clone().map_or(
341                         String::new(), |ty| {
342                             format!(" for type `{}`", ty)
343                         }),
344                     if used_to_be_allowed { " (E0119)" } else { "" }
345                 );
346                 let impl_span = tcx.sess.codemap().def_span(
347                     tcx.span_of_impl(impl_def_id).unwrap()
348                 );
349                 let mut err = if used_to_be_allowed {
350                     tcx.struct_span_lint_node(
351                         lint::builtin::INCOHERENT_FUNDAMENTAL_IMPLS,
352                         tcx.hir.as_local_node_id(impl_def_id).unwrap(),
353                         impl_span,
354                         &msg)
355                 } else {
356                     struct_span_err!(tcx.sess,
357                                      impl_span,
358                                      E0119,
359                                      "{}",
360                                      msg)
361                 };
362
363                 match tcx.span_of_impl(overlap.with_impl) {
364                     Ok(span) => {
365                         err.span_label(tcx.sess.codemap().def_span(span),
366                                        format!("first implementation here"));
367                         err.span_label(impl_span,
368                                        format!("conflicting implementation{}",
369                                                 overlap.self_desc
370                                                     .map_or(String::new(),
371                                                             |ty| format!(" for `{}`", ty))));
372                     }
373                     Err(cname) => {
374                         let msg = match to_pretty_impl_header(tcx, overlap.with_impl) {
375                             Some(s) => format!(
376                                 "conflicting implementation in crate `{}`:\n- {}", cname, s),
377                             None => format!("conflicting implementation in crate `{}`", cname),
378                         };
379                         err.note(&msg);
380                     }
381                 }
382
383                 for cause in &overlap.intercrate_ambiguity_causes {
384                     cause.add_intercrate_ambiguity_hint(&mut err);
385                 }
386
387                 err.emit();
388             }
389         } else {
390             let parent = tcx.impl_parent(impl_def_id).unwrap_or(trait_id);
391             sg.record_impl_from_cstore(tcx, parent, impl_def_id)
392         }
393     }
394
395     Lrc::new(sg)
396 }
397
398 /// Recovers the "impl X for Y" signature from `impl_def_id` and returns it as a
399 /// string.
400 fn to_pretty_impl_header(tcx: TyCtxt, impl_def_id: DefId) -> Option<String> {
401     use std::fmt::Write;
402
403     let trait_ref = if let Some(tr) = tcx.impl_trait_ref(impl_def_id) {
404         tr
405     } else {
406         return None;
407     };
408
409     let mut w = "impl".to_owned();
410
411     let substs = Substs::identity_for_item(tcx, impl_def_id);
412
413     // FIXME: Currently only handles ?Sized.
414     //        Needs to support ?Move and ?DynSized when they are implemented.
415     let mut types_without_default_bounds = FxHashSet::default();
416     let sized_trait = tcx.lang_items().sized_trait();
417
418     if !substs.is_noop() {
419         types_without_default_bounds.extend(substs.types());
420         w.push('<');
421         w.push_str(&substs.iter().map(|k| k.to_string()).collect::<Vec<_>>().join(", "));
422         w.push('>');
423     }
424
425     write!(w, " {} for {}", trait_ref, tcx.type_of(impl_def_id)).unwrap();
426
427     // The predicates will contain default bounds like `T: Sized`. We need to
428     // remove these bounds, and add `T: ?Sized` to any untouched type parameters.
429     let predicates = tcx.predicates_of(impl_def_id).predicates;
430     let mut pretty_predicates = Vec::with_capacity(predicates.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());
435                 continue;
436             }
437         }
438         pretty_predicates.push(p.to_string());
439     }
440     for ty in types_without_default_bounds {
441         pretty_predicates.push(format!("{}: ?Sized", ty));
442     }
443     if !pretty_predicates.is_empty() {
444         write!(w, "\n  where {}", pretty_predicates.join(", ")).unwrap();
445     }
446
447     w.push(';');
448     Some(w)
449 }