]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/specialize/mod.rs
Rollup merge of #47117 - tinaun:no_more_dups, r=frewsxcv
[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, FxHashSet};
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 traits::select::IntercrateAmbiguityCause;
29 use ty::{self, TyCtxt, TypeFoldable};
30 use syntax_pos::DUMMY_SP;
31 use std::rc::Rc;
32
33 use lint;
34
35 pub mod specialization_graph;
36
37 /// Information pertinent to an overlapping impl error.
38 pub struct OverlapError {
39     pub with_impl: DefId,
40     pub trait_desc: String,
41     pub self_desc: Option<String>,
42     pub intercrate_ambiguity_causes: Vec<IntercrateAmbiguityCause>,
43 }
44
45 /// Given a subst for the requested impl, translate it to a subst
46 /// appropriate for the actual item definition (whether it be in that impl,
47 /// a parent impl, or the trait).
48 ///
49 /// When we have selected one impl, but are actually using item definitions from
50 /// a parent impl providing a default, we need a way to translate between the
51 /// type parameters of the two impls. Here the `source_impl` is the one we've
52 /// selected, and `source_substs` is a substitution of its generics.
53 /// And `target_node` is the impl/trait we're actually going to get the
54 /// definition from. The resulting substitution will map from `target_node`'s
55 /// generics to `source_impl`'s generics as instantiated by `source_subst`.
56 ///
57 /// For example, consider the following scenario:
58 ///
59 /// ```rust
60 /// trait Foo { ... }
61 /// impl<T, U> Foo for (T, U) { ... }  // target impl
62 /// impl<V> Foo for (V, V) { ... }     // source impl
63 /// ```
64 ///
65 /// Suppose we have selected "source impl" with `V` instantiated with `u32`.
66 /// This function will produce a substitution with `T` and `U` both mapping to `u32`.
67 ///
68 /// Where clauses add some trickiness here, because they can be used to "define"
69 /// an argument indirectly:
70 ///
71 /// ```rust
72 /// impl<'a, I, T: 'a> Iterator for Cloned<I>
73 ///    where I: Iterator<Item=&'a T>, T: Clone
74 /// ```
75 ///
76 /// In a case like this, the substitution for `T` is determined indirectly,
77 /// through associated type projection. We deal with such cases by using
78 /// *fulfillment* to relate the two impls, requiring that all projections are
79 /// resolved.
80 pub fn translate_substs<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
81                                         param_env: ty::ParamEnv<'tcx>,
82                                         source_impl: DefId,
83                                         source_substs: &'tcx Substs<'tcx>,
84                                         target_node: specialization_graph::Node)
85                                         -> &'tcx Substs<'tcx> {
86     let source_trait_ref = infcx.tcx
87                                 .impl_trait_ref(source_impl)
88                                 .unwrap()
89                                 .subst(infcx.tcx, &source_substs);
90
91     // translate the Self and TyParam parts of the substitution, since those
92     // vary across impls
93     let target_substs = match target_node {
94         specialization_graph::Node::Impl(target_impl) => {
95             // no need to translate if we're targeting the impl we started with
96             if source_impl == target_impl {
97                 return source_substs;
98             }
99
100             fulfill_implication(infcx, param_env, source_trait_ref, target_impl)
101                 .unwrap_or_else(|_| {
102                     bug!("When translating substitutions for specialization, the expected \
103                           specialization failed to hold")
104                 })
105         }
106         specialization_graph::Node::Trait(..) => source_trait_ref.substs,
107     };
108
109     // directly inherent the method generics, since those do not vary across impls
110     source_substs.rebase_onto(infcx.tcx, source_impl, target_substs)
111 }
112
113 /// Given a selected impl described by `impl_data`, returns the
114 /// definition and substitutions for the method with the name `name`
115 /// the kind `kind`, and trait method substitutions `substs`, in
116 /// that impl, a less specialized impl, or the trait default,
117 /// whichever applies.
118 pub fn find_associated_item<'a, 'tcx>(
119     tcx: TyCtxt<'a, 'tcx, 'tcx>,
120     item: &ty::AssociatedItem,
121     substs: &'tcx Substs<'tcx>,
122     impl_data: &super::VtableImplData<'tcx, ()>,
123 ) -> (DefId, &'tcx Substs<'tcx>) {
124     assert!(!substs.needs_infer());
125
126     let trait_def_id = tcx.trait_id_of_impl(impl_data.impl_def_id).unwrap();
127     let trait_def = tcx.trait_def(trait_def_id);
128
129     let ancestors = trait_def.ancestors(tcx, impl_data.impl_def_id);
130     match ancestors.defs(tcx, item.name, item.kind, trait_def_id).next() {
131         Some(node_item) => {
132             let substs = tcx.infer_ctxt().enter(|infcx| {
133                 let param_env = ty::ParamEnv::empty(Reveal::All);
134                 let substs = substs.rebase_onto(tcx, trait_def_id, impl_data.substs);
135                 let substs = translate_substs(&infcx, param_env, impl_data.impl_def_id,
136                                               substs, node_item.node);
137                 let substs = infcx.tcx.erase_regions(&substs);
138                 tcx.lift(&substs).unwrap_or_else(|| {
139                     bug!("find_method: translate_substs \
140                           returned {:?} which contains inference types/regions",
141                          substs);
142                 })
143             });
144             (node_item.item.def_id, substs)
145         }
146         None => {
147             bug!("{:?} not found in {:?}", item, impl_data.impl_def_id)
148         }
149     }
150 }
151
152 /// Is impl1 a specialization of impl2?
153 ///
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
156 /// to.
157 pub(super) fn specializes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
158                                     (impl1_def_id, impl2_def_id): (DefId, DefId))
159     -> bool
160 {
161     debug!("specializes({:?}, {:?})", impl1_def_id, impl2_def_id);
162
163     // The feature gate should prevent introducing new specializations, but not
164     // taking advantage of upstream ones.
165     if !tcx.sess.features.borrow().specialization &&
166         (impl1_def_id.is_local() || impl2_def_id.is_local()) {
167         return false;
168     }
169
170     // We determine whether there's a subset relationship by:
171     //
172     // - skolemizing impl1,
173     // - assuming the where clauses for impl1,
174     // - instantiating impl2 with fresh inference variables,
175     // - unifying,
176     // - attempting to prove the where clauses for impl2
177     //
178     // The last three steps are encapsulated in `fulfill_implication`.
179     //
180     // See RFC 1210 for more details and justification.
181
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) {
184         return false;
185     }
186
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();
190
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                                           ObligationCause::dummy(),
198                                           penv,
199                                           &impl1_trait_ref) {
200                 Ok(impl1_trait_ref) => impl1_trait_ref,
201                 Err(err) => {
202                     bug!("failed to fully normalize {:?}: {:?}", impl1_trait_ref, err);
203                 }
204             };
205
206         // Attempt to prove that impl2 applies, given all of the above.
207         fulfill_implication(&infcx, penv, impl1_trait_ref, impl2_def_id).is_ok()
208     })
209 }
210
211 /// Attempt to fulfill all obligations of `target_impl` after unification with
212 /// `source_trait_ref`. If successful, returns a substitution for *all* the
213 /// generics of `target_impl`, including both those needed to unify with
214 /// `source_trait_ref` and those whose identity is determined via a where
215 /// clause in the impl.
216 fn fulfill_implication<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
217                                        param_env: ty::ParamEnv<'tcx>,
218                                        source_trait_ref: ty::TraitRef<'tcx>,
219                                        target_impl: DefId)
220                                        -> Result<&'tcx Substs<'tcx>, ()> {
221     let selcx = &mut SelectionContext::new(&infcx);
222     let target_substs = infcx.fresh_substs_for_item(DUMMY_SP, target_impl);
223     let (target_trait_ref, mut obligations) = impl_trait_ref_and_oblig(selcx,
224                                                                        param_env,
225                                                                        target_impl,
226                                                                        target_substs);
227
228     // do the impls unify? If not, no specialization.
229     match infcx.at(&ObligationCause::dummy(), param_env)
230                .eq(source_trait_ref, target_trait_ref) {
231         Ok(InferOk { obligations: o, .. }) => {
232             obligations.extend(o);
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         // If we came from `translate_substs`, we already know that the
247         // predicates for our impl hold (after all, we know that a more
248         // specialized impl holds, so our impl must hold too), and
249         // we only want to process the projections to determine the
250         // the types in our substs using RFC 447, so we can safely
251         // ignore region obligations, which allows us to avoid threading
252         // a node-id to assign them with.
253         //
254         // If we came from specialization graph construction, then
255         // we already make a mockery out of the region system, so
256         // why not ignore them a bit earlier?
257         let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
258         for oblig in obligations.into_iter() {
259             fulfill_cx.register_predicate_obligation(&infcx, oblig);
260         }
261         match fulfill_cx.select_all_or_error(infcx) {
262             Err(errors) => {
263                 // no dice!
264                 debug!("fulfill_implication: for impls on {:?} and {:?}, \
265                         could not fulfill: {:?} given {:?}",
266                        source_trait_ref,
267                        target_trait_ref,
268                        errors,
269                        param_env.caller_bounds);
270                 Err(())
271             }
272
273             Ok(()) => {
274                 debug!("fulfill_implication: an impl for {:?} specializes {:?}",
275                        source_trait_ref,
276                        target_trait_ref);
277
278                 // Now resolve the *substitution* we built for the target earlier, replacing
279                 // the inference variables inside with whatever we got from fulfillment.
280                 Ok(infcx.resolve_type_vars_if_possible(&target_substs))
281             }
282         }
283     })
284 }
285
286 pub struct SpecializesCache {
287     map: FxHashMap<(DefId, DefId), bool>,
288 }
289
290 impl SpecializesCache {
291     pub fn new() -> Self {
292         SpecializesCache {
293             map: FxHashMap()
294         }
295     }
296
297     pub fn check(&self, a: DefId, b: DefId) -> Option<bool> {
298         self.map.get(&(a, b)).cloned()
299     }
300
301     pub fn insert(&mut self, a: DefId, b: DefId, result: bool) {
302         self.map.insert((a, b), result);
303     }
304 }
305
306 // Query provider for `specialization_graph_of`.
307 pub(super) fn specialization_graph_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
308                                                       trait_id: DefId)
309                                                       -> Rc<specialization_graph::Graph> {
310     let mut sg = specialization_graph::Graph::new();
311
312     let mut trait_impls = Vec::new();
313     tcx.for_each_impl(trait_id, |impl_did| trait_impls.push(impl_did));
314
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())
323     });
324
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)
333             };
334
335             if let Some(overlap) = overlap {
336                 let msg = format!("conflicting implementations of trait `{}`{}:{}",
337                     overlap.trait_desc,
338                     overlap.self_desc.clone().map_or(
339                         String::new(), |ty| {
340                             format!(" for type `{}`", ty)
341                         }),
342                     if used_to_be_allowed { " (E0119)" } else { "" }
343                 );
344                 let impl_span = tcx.sess.codemap().def_span(
345                     tcx.span_of_impl(impl_def_id).unwrap()
346                 );
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(),
351                         impl_span,
352                         &msg)
353                 } else {
354                     struct_span_err!(tcx.sess,
355                                      impl_span,
356                                      E0119,
357                                      "{}",
358                                      msg)
359                 };
360
361                 match tcx.span_of_impl(overlap.with_impl) {
362                     Ok(span) => {
363                         err.span_label(tcx.sess.codemap().def_span(span),
364                                        format!("first implementation here"));
365                         err.span_label(impl_span,
366                                        format!("conflicting implementation{}",
367                                                 overlap.self_desc
368                                                     .map_or(String::new(),
369                                                             |ty| format!(" for `{}`", ty))));
370                     }
371                     Err(cname) => {
372                         let msg = match to_pretty_impl_header(tcx, overlap.with_impl) {
373                             Some(s) => format!(
374                                 "conflicting implementation in crate `{}`:\n- {}", cname, s),
375                             None => format!("conflicting implementation in crate `{}`", cname),
376                         };
377                         err.note(&msg);
378                     }
379                 }
380
381                 for cause in &overlap.intercrate_ambiguity_causes {
382                     cause.add_intercrate_ambiguity_hint(&mut err);
383                 }
384
385                 err.emit();
386             }
387         } else {
388             let parent = tcx.impl_parent(impl_def_id).unwrap_or(trait_id);
389             sg.record_impl_from_cstore(tcx, parent, impl_def_id)
390         }
391     }
392
393     Rc::new(sg)
394 }
395
396 /// Recovers the "impl X for Y" signature from `impl_def_id` and returns it as a
397 /// string.
398 fn to_pretty_impl_header(tcx: TyCtxt, impl_def_id: DefId) -> Option<String> {
399     use std::fmt::Write;
400
401     let trait_ref = if let Some(tr) = tcx.impl_trait_ref(impl_def_id) {
402         tr
403     } else {
404         return None;
405     };
406
407     let mut w = "impl".to_owned();
408
409     let substs = Substs::identity_for_item(tcx, impl_def_id);
410
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();
415
416     if !substs.is_noop() {
417         types_without_default_bounds.extend(substs.types());
418         w.push('<');
419         w.push_str(&substs.iter().map(|k| k.to_string()).collect::<Vec<_>>().join(", "));
420         w.push('>');
421     }
422
423     write!(w, " {} for {}", trait_ref, tcx.type_of(impl_def_id)).unwrap();
424
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(predicates.len());
429     for p in predicates {
430         if let Some(poly_trait_ref) = p.to_opt_poly_trait_ref() {
431             if Some(poly_trait_ref.def_id()) == sized_trait {
432                 types_without_default_bounds.remove(poly_trait_ref.self_ty());
433                 continue;
434             }
435         }
436         pretty_predicates.push(p.to_string());
437     }
438     for ty in types_without_default_bounds {
439         pretty_predicates.push(format!("{}: ?Sized", ty));
440     }
441     if !pretty_predicates.is_empty() {
442         write!(w, "\n  where {}", pretty_predicates.join(", ")).unwrap();
443     }
444
445     w.push(';');
446     Some(w)
447 }