]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/util.rs
Rollup merge of #41249 - GuillaumeGomez:rustdoc-render, r=steveklabnik,frewsxcv
[rust.git] / src / librustc / traits / util.rs
1 // Copyright 2014 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 use hir::def_id::DefId;
12 use ty::subst::{Subst, Substs};
13 use ty::{self, Ty, TyCtxt, ToPredicate, ToPolyTraitRef};
14 use ty::outlives::Component;
15 use util::nodemap::FxHashSet;
16
17 use super::{Obligation, ObligationCause, PredicateObligation, SelectionContext, Normalized};
18
19 fn anonymize_predicate<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
20                                        pred: &ty::Predicate<'tcx>)
21                                        -> ty::Predicate<'tcx> {
22     match *pred {
23         ty::Predicate::Trait(ref data) =>
24             ty::Predicate::Trait(tcx.anonymize_late_bound_regions(data)),
25
26         ty::Predicate::Equate(ref data) =>
27             ty::Predicate::Equate(tcx.anonymize_late_bound_regions(data)),
28
29         ty::Predicate::RegionOutlives(ref data) =>
30             ty::Predicate::RegionOutlives(tcx.anonymize_late_bound_regions(data)),
31
32         ty::Predicate::TypeOutlives(ref data) =>
33             ty::Predicate::TypeOutlives(tcx.anonymize_late_bound_regions(data)),
34
35         ty::Predicate::Projection(ref data) =>
36             ty::Predicate::Projection(tcx.anonymize_late_bound_regions(data)),
37
38         ty::Predicate::WellFormed(data) =>
39             ty::Predicate::WellFormed(data),
40
41         ty::Predicate::ObjectSafe(data) =>
42             ty::Predicate::ObjectSafe(data),
43
44         ty::Predicate::ClosureKind(closure_def_id, kind) =>
45             ty::Predicate::ClosureKind(closure_def_id, kind),
46
47         ty::Predicate::Subtype(ref data) =>
48             ty::Predicate::Subtype(tcx.anonymize_late_bound_regions(data)),
49     }
50 }
51
52
53 struct PredicateSet<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
54     tcx: TyCtxt<'a, 'gcx, 'tcx>,
55     set: FxHashSet<ty::Predicate<'tcx>>,
56 }
57
58 impl<'a, 'gcx, 'tcx> PredicateSet<'a, 'gcx, 'tcx> {
59     fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PredicateSet<'a, 'gcx, 'tcx> {
60         PredicateSet { tcx: tcx, set: FxHashSet() }
61     }
62
63     fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {
64         // We have to be careful here because we want
65         //
66         //    for<'a> Foo<&'a int>
67         //
68         // and
69         //
70         //    for<'b> Foo<&'b int>
71         //
72         // to be considered equivalent. So normalize all late-bound
73         // regions before we throw things into the underlying set.
74         self.set.insert(anonymize_predicate(self.tcx, pred))
75     }
76 }
77
78 ///////////////////////////////////////////////////////////////////////////
79 // `Elaboration` iterator
80 ///////////////////////////////////////////////////////////////////////////
81
82 /// "Elaboration" is the process of identifying all the predicates that
83 /// are implied by a source predicate. Currently this basically means
84 /// walking the "supertraits" and other similar assumptions. For
85 /// example, if we know that `T : Ord`, the elaborator would deduce
86 /// that `T : PartialOrd` holds as well. Similarly, if we have `trait
87 /// Foo : 'static`, and we know that `T : Foo`, then we know that `T :
88 /// 'static`.
89 pub struct Elaborator<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
90     stack: Vec<ty::Predicate<'tcx>>,
91     visited: PredicateSet<'a, 'gcx, 'tcx>,
92 }
93
94 pub fn elaborate_trait_ref<'cx, 'gcx, 'tcx>(
95     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
96     trait_ref: ty::PolyTraitRef<'tcx>)
97     -> Elaborator<'cx, 'gcx, 'tcx>
98 {
99     elaborate_predicates(tcx, vec![trait_ref.to_predicate()])
100 }
101
102 pub fn elaborate_trait_refs<'cx, 'gcx, 'tcx>(
103     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
104     trait_refs: &[ty::PolyTraitRef<'tcx>])
105     -> Elaborator<'cx, 'gcx, 'tcx>
106 {
107     let predicates = trait_refs.iter()
108                                .map(|trait_ref| trait_ref.to_predicate())
109                                .collect();
110     elaborate_predicates(tcx, predicates)
111 }
112
113 pub fn elaborate_predicates<'cx, 'gcx, 'tcx>(
114     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
115     mut predicates: Vec<ty::Predicate<'tcx>>)
116     -> Elaborator<'cx, 'gcx, 'tcx>
117 {
118     let mut visited = PredicateSet::new(tcx);
119     predicates.retain(|pred| visited.insert(pred));
120     Elaborator { stack: predicates, visited: visited }
121 }
122
123 impl<'cx, 'gcx, 'tcx> Elaborator<'cx, 'gcx, 'tcx> {
124     pub fn filter_to_traits(self) -> FilterToTraits<Self> {
125         FilterToTraits::new(self)
126     }
127
128     fn push(&mut self, predicate: &ty::Predicate<'tcx>) {
129         let tcx = self.visited.tcx;
130         match *predicate {
131             ty::Predicate::Trait(ref data) => {
132                 // Predicates declared on the trait.
133                 let predicates = tcx.item_super_predicates(data.def_id());
134
135                 let mut predicates: Vec<_> =
136                     predicates.predicates
137                               .iter()
138                               .map(|p| p.subst_supertrait(tcx, &data.to_poly_trait_ref()))
139                               .collect();
140
141                 debug!("super_predicates: data={:?} predicates={:?}",
142                        data, predicates);
143
144                 // Only keep those bounds that we haven't already
145                 // seen.  This is necessary to prevent infinite
146                 // recursion in some cases.  One common case is when
147                 // people define `trait Sized: Sized { }` rather than `trait
148                 // Sized { }`.
149                 predicates.retain(|r| self.visited.insert(r));
150
151                 self.stack.extend(predicates);
152             }
153             ty::Predicate::WellFormed(..) => {
154                 // Currently, we do not elaborate WF predicates,
155                 // although we easily could.
156             }
157             ty::Predicate::ObjectSafe(..) => {
158                 // Currently, we do not elaborate object-safe
159                 // predicates.
160             }
161             ty::Predicate::Equate(..) => {
162                 // Currently, we do not "elaborate" predicates like
163                 // `X == Y`, though conceivably we might. For example,
164                 // `&X == &Y` implies that `X == Y`.
165             }
166             ty::Predicate::Subtype(..) => {
167                 // Currently, we do not "elaborate" predicates like `X
168                 // <: Y`, though conceivably we might.
169             }
170             ty::Predicate::Projection(..) => {
171                 // Nothing to elaborate in a projection predicate.
172             }
173             ty::Predicate::ClosureKind(..) => {
174                 // Nothing to elaborate when waiting for a closure's kind to be inferred.
175             }
176
177             ty::Predicate::RegionOutlives(..) => {
178                 // Nothing to elaborate from `'a: 'b`.
179             }
180
181             ty::Predicate::TypeOutlives(ref data) => {
182                 // We know that `T: 'a` for some type `T`. We can
183                 // often elaborate this. For example, if we know that
184                 // `[U]: 'a`, that implies that `U: 'a`. Similarly, if
185                 // we know `&'a U: 'b`, then we know that `'a: 'b` and
186                 // `U: 'b`.
187                 //
188                 // We can basically ignore bound regions here. So for
189                 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
190                 // `'a: 'b`.
191
192                 // Ignore `for<'a> T: 'a` -- we might in the future
193                 // consider this as evidence that `T: 'static`, but
194                 // I'm a bit wary of such constructions and so for now
195                 // I want to be conservative. --nmatsakis
196                 let ty_max = data.skip_binder().0;
197                 let r_min = data.skip_binder().1;
198                 if r_min.is_bound() {
199                     return;
200                 }
201
202                 let visited = &mut self.visited;
203                 self.stack.extend(
204                     tcx.outlives_components(ty_max)
205                        .into_iter()
206                        .filter_map(|component| match component {
207                            Component::Region(r) => if r.is_bound() {
208                                None
209                            } else {
210                                Some(ty::Predicate::RegionOutlives(
211                                    ty::Binder(ty::OutlivesPredicate(r, r_min))))
212                            },
213
214                            Component::Param(p) => {
215                                let ty = tcx.mk_param(p.idx, p.name);
216                                Some(ty::Predicate::TypeOutlives(
217                                    ty::Binder(ty::OutlivesPredicate(ty, r_min))))
218                            },
219
220                            Component::UnresolvedInferenceVariable(_) => {
221                                None
222                            },
223
224                            Component::Projection(_) |
225                            Component::EscapingProjection(_) => {
226                                // We can probably do more here. This
227                                // corresponds to a case like `<T as
228                                // Foo<'a>>::U: 'b`.
229                                None
230                            },
231                        })
232                        .filter(|p| visited.insert(p)));
233             }
234         }
235     }
236 }
237
238 impl<'cx, 'gcx, 'tcx> Iterator for Elaborator<'cx, 'gcx, 'tcx> {
239     type Item = ty::Predicate<'tcx>;
240
241     fn next(&mut self) -> Option<ty::Predicate<'tcx>> {
242         // Extract next item from top-most stack frame, if any.
243         let next_predicate = match self.stack.pop() {
244             Some(predicate) => predicate,
245             None => {
246                 // No more stack frames. Done.
247                 return None;
248             }
249         };
250         self.push(&next_predicate);
251         return Some(next_predicate);
252     }
253 }
254
255 ///////////////////////////////////////////////////////////////////////////
256 // Supertrait iterator
257 ///////////////////////////////////////////////////////////////////////////
258
259 pub type Supertraits<'cx, 'gcx, 'tcx> = FilterToTraits<Elaborator<'cx, 'gcx, 'tcx>>;
260
261 pub fn supertraits<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
262                                     trait_ref: ty::PolyTraitRef<'tcx>)
263                                     -> Supertraits<'cx, 'gcx, 'tcx>
264 {
265     elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
266 }
267
268 pub fn transitive_bounds<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
269                                           bounds: &[ty::PolyTraitRef<'tcx>])
270                                           -> Supertraits<'cx, 'gcx, 'tcx>
271 {
272     elaborate_trait_refs(tcx, bounds).filter_to_traits()
273 }
274
275 ///////////////////////////////////////////////////////////////////////////
276 // Iterator over def-ids of supertraits
277
278 pub struct SupertraitDefIds<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
279     tcx: TyCtxt<'a, 'gcx, 'tcx>,
280     stack: Vec<DefId>,
281     visited: FxHashSet<DefId>,
282 }
283
284 pub fn supertrait_def_ids<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
285                                            trait_def_id: DefId)
286                                            -> SupertraitDefIds<'cx, 'gcx, 'tcx>
287 {
288     SupertraitDefIds {
289         tcx: tcx,
290         stack: vec![trait_def_id],
291         visited: Some(trait_def_id).into_iter().collect(),
292     }
293 }
294
295 impl<'cx, 'gcx, 'tcx> Iterator for SupertraitDefIds<'cx, 'gcx, 'tcx> {
296     type Item = DefId;
297
298     fn next(&mut self) -> Option<DefId> {
299         let def_id = match self.stack.pop() {
300             Some(def_id) => def_id,
301             None => { return None; }
302         };
303
304         let predicates = self.tcx.item_super_predicates(def_id);
305         let visited = &mut self.visited;
306         self.stack.extend(
307             predicates.predicates
308                       .iter()
309                       .filter_map(|p| p.to_opt_poly_trait_ref())
310                       .map(|t| t.def_id())
311                       .filter(|&super_def_id| visited.insert(super_def_id)));
312         Some(def_id)
313     }
314 }
315
316 ///////////////////////////////////////////////////////////////////////////
317 // Other
318 ///////////////////////////////////////////////////////////////////////////
319
320 /// A filter around an iterator of predicates that makes it yield up
321 /// just trait references.
322 pub struct FilterToTraits<I> {
323     base_iterator: I
324 }
325
326 impl<I> FilterToTraits<I> {
327     fn new(base: I) -> FilterToTraits<I> {
328         FilterToTraits { base_iterator: base }
329     }
330 }
331
332 impl<'tcx,I:Iterator<Item=ty::Predicate<'tcx>>> Iterator for FilterToTraits<I> {
333     type Item = ty::PolyTraitRef<'tcx>;
334
335     fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
336         loop {
337             match self.base_iterator.next() {
338                 None => {
339                     return None;
340                 }
341                 Some(ty::Predicate::Trait(data)) => {
342                     return Some(data.to_poly_trait_ref());
343                 }
344                 Some(_) => {
345                 }
346             }
347         }
348     }
349 }
350
351 ///////////////////////////////////////////////////////////////////////////
352 // Other
353 ///////////////////////////////////////////////////////////////////////////
354
355 /// Instantiate all bound parameters of the impl with the given substs,
356 /// returning the resulting trait ref and all obligations that arise.
357 /// The obligations are closed under normalization.
358 pub fn impl_trait_ref_and_oblig<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,
359                                                 impl_def_id: DefId,
360                                                 impl_substs: &Substs<'tcx>)
361                                                 -> (ty::TraitRef<'tcx>,
362                                                     Vec<PredicateObligation<'tcx>>)
363 {
364     let impl_trait_ref =
365         selcx.tcx().impl_trait_ref(impl_def_id).unwrap();
366     let impl_trait_ref =
367         impl_trait_ref.subst(selcx.tcx(), impl_substs);
368     let Normalized { value: impl_trait_ref, obligations: normalization_obligations1 } =
369         super::normalize(selcx, ObligationCause::dummy(), &impl_trait_ref);
370
371     let predicates = selcx.tcx().item_predicates(impl_def_id);
372     let predicates = predicates.instantiate(selcx.tcx(), impl_substs);
373     let Normalized { value: predicates, obligations: normalization_obligations2 } =
374         super::normalize(selcx, ObligationCause::dummy(), &predicates);
375     let impl_obligations =
376         predicates_for_generics(ObligationCause::dummy(), 0, &predicates);
377
378     let impl_obligations: Vec<_> =
379         impl_obligations.into_iter()
380         .chain(normalization_obligations1)
381         .chain(normalization_obligations2)
382         .collect();
383
384     (impl_trait_ref, impl_obligations)
385 }
386
387 /// See `super::obligations_for_generics`
388 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
389                                      recursion_depth: usize,
390                                      generic_bounds: &ty::InstantiatedPredicates<'tcx>)
391                                      -> Vec<PredicateObligation<'tcx>>
392 {
393     debug!("predicates_for_generics(generic_bounds={:?})",
394            generic_bounds);
395
396     generic_bounds.predicates.iter().map(|predicate| {
397         Obligation { cause: cause.clone(),
398                      recursion_depth: recursion_depth,
399                      predicate: predicate.clone() }
400     }).collect()
401 }
402
403 pub fn predicate_for_trait_ref<'tcx>(
404     cause: ObligationCause<'tcx>,
405     trait_ref: ty::TraitRef<'tcx>,
406     recursion_depth: usize)
407     -> PredicateObligation<'tcx>
408 {
409     Obligation {
410         cause: cause,
411         recursion_depth: recursion_depth,
412         predicate: trait_ref.to_predicate(),
413     }
414 }
415
416 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
417     pub fn predicate_for_trait_def(self,
418         cause: ObligationCause<'tcx>,
419         trait_def_id: DefId,
420         recursion_depth: usize,
421         param_ty: Ty<'tcx>,
422         ty_params: &[Ty<'tcx>])
423         -> PredicateObligation<'tcx>
424     {
425         let trait_ref = ty::TraitRef {
426             def_id: trait_def_id,
427             substs: self.mk_substs_trait(param_ty, ty_params)
428         };
429         predicate_for_trait_ref(cause, trait_ref, recursion_depth)
430     }
431
432     /// Cast a trait reference into a reference to one of its super
433     /// traits; returns `None` if `target_trait_def_id` is not a
434     /// supertrait.
435     pub fn upcast_choices(self,
436                           source_trait_ref: ty::PolyTraitRef<'tcx>,
437                           target_trait_def_id: DefId)
438                           -> Vec<ty::PolyTraitRef<'tcx>>
439     {
440         if source_trait_ref.def_id() == target_trait_def_id {
441             return vec![source_trait_ref]; // shorcut the most common case
442         }
443
444         supertraits(self, source_trait_ref)
445             .filter(|r| r.def_id() == target_trait_def_id)
446             .collect()
447     }
448
449     /// Given a trait `trait_ref`, returns the number of vtable entries
450     /// that come from `trait_ref`, excluding its supertraits. Used in
451     /// computing the vtable base for an upcast trait of a trait object.
452     pub fn count_own_vtable_entries(self, trait_ref: ty::PolyTraitRef<'tcx>) -> usize {
453         let mut entries = 0;
454         // Count number of methods and add them to the total offset.
455         // Skip over associated types and constants.
456         for trait_item in self.associated_items(trait_ref.def_id()) {
457             if trait_item.kind == ty::AssociatedKind::Method {
458                 entries += 1;
459             }
460         }
461         entries
462     }
463
464     /// Given an upcast trait object described by `object`, returns the
465     /// index of the method `method_def_id` (which should be part of
466     /// `object.upcast_trait_ref`) within the vtable for `object`.
467     pub fn get_vtable_index_of_object_method<N>(self,
468                                                 object: &super::VtableObjectData<'tcx, N>,
469                                                 method_def_id: DefId) -> usize {
470         // Count number of methods preceding the one we are selecting and
471         // add them to the total offset.
472         // Skip over associated types and constants.
473         let mut entries = object.vtable_base;
474         for trait_item in self.associated_items(object.upcast_trait_ref.def_id()) {
475             if trait_item.def_id == method_def_id {
476                 // The item with the ID we were given really ought to be a method.
477                 assert_eq!(trait_item.kind, ty::AssociatedKind::Method);
478                 return entries;
479             }
480             if trait_item.kind == ty::AssociatedKind::Method {
481                 entries += 1;
482             }
483         }
484
485         bug!("get_vtable_index_of_object_method: {:?} was not found",
486              method_def_id);
487     }
488
489     pub fn closure_trait_ref_and_return_type(self,
490         fn_trait_def_id: DefId,
491         self_ty: Ty<'tcx>,
492         sig: ty::PolyFnSig<'tcx>,
493         tuple_arguments: TupleArgumentsFlag)
494         -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>)>
495     {
496         let arguments_tuple = match tuple_arguments {
497             TupleArgumentsFlag::No => sig.skip_binder().inputs()[0],
498             TupleArgumentsFlag::Yes =>
499                 self.intern_tup(sig.skip_binder().inputs(), false),
500         };
501         let trait_ref = ty::TraitRef {
502             def_id: fn_trait_def_id,
503             substs: self.mk_substs_trait(self_ty, &[arguments_tuple]),
504         };
505         ty::Binder((trait_ref, sig.skip_binder().output()))
506     }
507 }
508
509 pub enum TupleArgumentsFlag { Yes, No }