]> git.lizzy.rs Git - rust.git/blob - src/librustc_infer/traits/util.rs
ee9846c64b67c1033608b52baf62e00cf11061e1
[rust.git] / src / librustc_infer / traits / util.rs
1 use smallvec::smallvec;
2
3 use crate::traits::{Obligation, ObligationCause, PredicateObligation};
4 use rustc_data_structures::fx::FxHashSet;
5 use rustc_middle::ty::outlives::Component;
6 use rustc_middle::ty::{self, ToPolyTraitRef, ToPredicate, TyCtxt, WithConstness};
7 use rustc_span::Span;
8
9 pub fn anonymize_predicate<'tcx>(
10     tcx: TyCtxt<'tcx>,
11     pred: ty::Predicate<'tcx>,
12 ) -> ty::Predicate<'tcx> {
13     let kind = pred.kind();
14     let new = match kind {
15         &ty::PredicateKind::Trait(ref data, constness) => {
16             ty::PredicateKind::Trait(tcx.anonymize_late_bound_regions(data), constness)
17         }
18
19         ty::PredicateKind::RegionOutlives(data) => {
20             ty::PredicateKind::RegionOutlives(tcx.anonymize_late_bound_regions(data))
21         }
22
23         ty::PredicateKind::TypeOutlives(data) => {
24             ty::PredicateKind::TypeOutlives(tcx.anonymize_late_bound_regions(data))
25         }
26
27         ty::PredicateKind::Projection(data) => {
28             ty::PredicateKind::Projection(tcx.anonymize_late_bound_regions(data))
29         }
30
31         &ty::PredicateKind::WellFormed(data) => ty::PredicateKind::WellFormed(data),
32
33         &ty::PredicateKind::ObjectSafe(data) => ty::PredicateKind::ObjectSafe(data),
34
35         &ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
36             ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind)
37         }
38
39         ty::PredicateKind::Subtype(data) => {
40             ty::PredicateKind::Subtype(tcx.anonymize_late_bound_regions(data))
41         }
42
43         &ty::PredicateKind::ConstEvaluatable(def_id, substs) => {
44             ty::PredicateKind::ConstEvaluatable(def_id, substs)
45         }
46
47         ty::PredicateKind::ConstEquate(c1, c2) => ty::PredicateKind::ConstEquate(c1, c2),
48     };
49
50     if new != *kind { new.to_predicate(tcx) } else { pred }
51 }
52
53 struct PredicateSet<'tcx> {
54     tcx: TyCtxt<'tcx>,
55     set: FxHashSet<ty::Predicate<'tcx>>,
56 }
57
58 impl PredicateSet<'tcx> {
59     fn new(tcx: TyCtxt<'tcx>) -> Self {
60         Self { tcx, set: Default::default() }
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 impl Extend<ty::Predicate<'tcx>> for PredicateSet<'tcx> {
79     fn extend<I: IntoIterator<Item = ty::Predicate<'tcx>>>(&mut self, iter: I) {
80         for pred in iter {
81             self.insert(pred);
82         }
83     }
84
85     fn extend_one(&mut self, pred: ty::Predicate<'tcx>) {
86         self.insert(pred);
87     }
88
89     fn extend_reserve(&mut self, additional: usize) {
90         Extend::<ty::Predicate<'tcx>>::extend_reserve(&mut self.set, additional);
91     }
92 }
93
94 ///////////////////////////////////////////////////////////////////////////
95 // `Elaboration` iterator
96 ///////////////////////////////////////////////////////////////////////////
97
98 /// "Elaboration" is the process of identifying all the predicates that
99 /// are implied by a source predicate. Currently, this basically means
100 /// walking the "supertraits" and other similar assumptions. For example,
101 /// if we know that `T: Ord`, the elaborator would deduce that `T: PartialOrd`
102 /// holds as well. Similarly, if we have `trait Foo: 'static`, and we know that
103 /// `T: Foo`, then we know that `T: 'static`.
104 pub struct Elaborator<'tcx> {
105     stack: Vec<PredicateObligation<'tcx>>,
106     visited: PredicateSet<'tcx>,
107 }
108
109 pub fn elaborate_trait_ref<'tcx>(
110     tcx: TyCtxt<'tcx>,
111     trait_ref: ty::PolyTraitRef<'tcx>,
112 ) -> Elaborator<'tcx> {
113     elaborate_predicates(tcx, std::iter::once(trait_ref.without_const().to_predicate(tcx)))
114 }
115
116 pub fn elaborate_trait_refs<'tcx>(
117     tcx: TyCtxt<'tcx>,
118     trait_refs: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
119 ) -> Elaborator<'tcx> {
120     let predicates = trait_refs.map(|trait_ref| trait_ref.without_const().to_predicate(tcx));
121     elaborate_predicates(tcx, predicates)
122 }
123
124 pub fn elaborate_predicates<'tcx>(
125     tcx: TyCtxt<'tcx>,
126     predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
127 ) -> Elaborator<'tcx> {
128     let obligations = predicates.map(|predicate| predicate_obligation(predicate, None)).collect();
129     elaborate_obligations(tcx, obligations)
130 }
131
132 pub fn elaborate_obligations<'tcx>(
133     tcx: TyCtxt<'tcx>,
134     mut obligations: Vec<PredicateObligation<'tcx>>,
135 ) -> Elaborator<'tcx> {
136     let mut visited = PredicateSet::new(tcx);
137     obligations.retain(|obligation| visited.insert(obligation.predicate));
138     Elaborator { stack: obligations, visited }
139 }
140
141 fn predicate_obligation<'tcx>(
142     predicate: ty::Predicate<'tcx>,
143     span: Option<Span>,
144 ) -> PredicateObligation<'tcx> {
145     let cause = if let Some(span) = span {
146         ObligationCause::dummy_with_span(span)
147     } else {
148         ObligationCause::dummy()
149     };
150
151     Obligation { cause, param_env: ty::ParamEnv::empty(), recursion_depth: 0, predicate }
152 }
153
154 impl Elaborator<'tcx> {
155     pub fn filter_to_traits(self) -> FilterToTraits<Self> {
156         FilterToTraits::new(self)
157     }
158
159     fn elaborate(&mut self, obligation: &PredicateObligation<'tcx>) {
160         let tcx = self.visited.tcx;
161         match obligation.predicate.kind() {
162             ty::PredicateKind::Trait(ref data, _) => {
163                 // Get predicates declared on the trait.
164                 let predicates = tcx.super_predicates_of(data.def_id());
165
166                 let obligations = predicates.predicates.iter().map(|(pred, span)| {
167                     predicate_obligation(
168                         pred.subst_supertrait(tcx, &data.to_poly_trait_ref()),
169                         Some(*span),
170                     )
171                 });
172                 debug!("super_predicates: data={:?}", data);
173
174                 // Only keep those bounds that we haven't already seen.
175                 // This is necessary to prevent infinite recursion in some
176                 // cases. One common case is when people define
177                 // `trait Sized: Sized { }` rather than `trait Sized { }`.
178                 let visited = &mut self.visited;
179                 let obligations = obligations.filter(|o| visited.insert(o.predicate));
180
181                 self.stack.extend(obligations);
182             }
183             ty::PredicateKind::WellFormed(..) => {
184                 // Currently, we do not elaborate WF predicates,
185                 // although we easily could.
186             }
187             ty::PredicateKind::ObjectSafe(..) => {
188                 // Currently, we do not elaborate object-safe
189                 // predicates.
190             }
191             ty::PredicateKind::Subtype(..) => {
192                 // Currently, we do not "elaborate" predicates like `X <: Y`,
193                 // though conceivably we might.
194             }
195             ty::PredicateKind::Projection(..) => {
196                 // Nothing to elaborate in a projection predicate.
197             }
198             ty::PredicateKind::ClosureKind(..) => {
199                 // Nothing to elaborate when waiting for a closure's kind to be inferred.
200             }
201             ty::PredicateKind::ConstEvaluatable(..) => {
202                 // Currently, we do not elaborate const-evaluatable
203                 // predicates.
204             }
205             ty::PredicateKind::ConstEquate(..) => {
206                 // Currently, we do not elaborate const-equate
207                 // predicates.
208             }
209             ty::PredicateKind::RegionOutlives(..) => {
210                 // Nothing to elaborate from `'a: 'b`.
211             }
212             ty::PredicateKind::TypeOutlives(ref data) => {
213                 // We know that `T: 'a` for some type `T`. We can
214                 // often elaborate this. For example, if we know that
215                 // `[U]: 'a`, that implies that `U: 'a`. Similarly, if
216                 // we know `&'a U: 'b`, then we know that `'a: 'b` and
217                 // `U: 'b`.
218                 //
219                 // We can basically ignore bound regions here. So for
220                 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
221                 // `'a: 'b`.
222
223                 // Ignore `for<'a> T: 'a` -- we might in the future
224                 // consider this as evidence that `T: 'static`, but
225                 // I'm a bit wary of such constructions and so for now
226                 // I want to be conservative. --nmatsakis
227                 let ty_max = data.skip_binder().0;
228                 let r_min = data.skip_binder().1;
229                 if r_min.is_late_bound() {
230                     return;
231                 }
232
233                 let visited = &mut self.visited;
234                 let mut components = smallvec![];
235                 tcx.push_outlives_components(ty_max, &mut components);
236                 self.stack.extend(
237                     components
238                         .into_iter()
239                         .filter_map(|component| match component {
240                             Component::Region(r) => {
241                                 if r.is_late_bound() {
242                                     None
243                                 } else {
244                                     Some(ty::PredicateKind::RegionOutlives(ty::Binder::dummy(
245                                         ty::OutlivesPredicate(r, r_min),
246                                     )))
247                                 }
248                             }
249
250                             Component::Param(p) => {
251                                 let ty = tcx.mk_ty_param(p.index, p.name);
252                                 Some(ty::PredicateKind::TypeOutlives(ty::Binder::dummy(
253                                     ty::OutlivesPredicate(ty, r_min),
254                                 )))
255                             }
256
257                             Component::UnresolvedInferenceVariable(_) => None,
258
259                             Component::Projection(_) | Component::EscapingProjection(_) => {
260                                 // We can probably do more here. This
261                                 // corresponds to a case like `<T as
262                                 // Foo<'a>>::U: 'b`.
263                                 None
264                             }
265                         })
266                         .map(|predicate_kind| predicate_kind.to_predicate(tcx))
267                         .filter(|&predicate| visited.insert(predicate))
268                         .map(|predicate| predicate_obligation(predicate, None)),
269                 );
270             }
271         }
272     }
273 }
274
275 impl Iterator for Elaborator<'tcx> {
276     type Item = PredicateObligation<'tcx>;
277
278     fn size_hint(&self) -> (usize, Option<usize>) {
279         (self.stack.len(), None)
280     }
281
282     fn next(&mut self) -> Option<Self::Item> {
283         // Extract next item from top-most stack frame, if any.
284         if let Some(obligation) = self.stack.pop() {
285             self.elaborate(&obligation);
286             Some(obligation)
287         } else {
288             None
289         }
290     }
291 }
292
293 ///////////////////////////////////////////////////////////////////////////
294 // Supertrait iterator
295 ///////////////////////////////////////////////////////////////////////////
296
297 pub type Supertraits<'tcx> = FilterToTraits<Elaborator<'tcx>>;
298
299 pub fn supertraits<'tcx>(
300     tcx: TyCtxt<'tcx>,
301     trait_ref: ty::PolyTraitRef<'tcx>,
302 ) -> Supertraits<'tcx> {
303     elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
304 }
305
306 pub fn transitive_bounds<'tcx>(
307     tcx: TyCtxt<'tcx>,
308     bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
309 ) -> Supertraits<'tcx> {
310     elaborate_trait_refs(tcx, bounds).filter_to_traits()
311 }
312
313 ///////////////////////////////////////////////////////////////////////////
314 // Other
315 ///////////////////////////////////////////////////////////////////////////
316
317 /// A filter around an iterator of predicates that makes it yield up
318 /// just trait references.
319 pub struct FilterToTraits<I> {
320     base_iterator: I,
321 }
322
323 impl<I> FilterToTraits<I> {
324     fn new(base: I) -> FilterToTraits<I> {
325         FilterToTraits { base_iterator: base }
326     }
327 }
328
329 impl<'tcx, I: Iterator<Item = PredicateObligation<'tcx>>> Iterator for FilterToTraits<I> {
330     type Item = ty::PolyTraitRef<'tcx>;
331
332     fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
333         while let Some(obligation) = self.base_iterator.next() {
334             if let ty::PredicateKind::Trait(data, _) = obligation.predicate.kind() {
335                 return Some(data.to_poly_trait_ref());
336             }
337         }
338         None
339     }
340
341     fn size_hint(&self) -> (usize, Option<usize>) {
342         let (_, upper) = self.base_iterator.size_hint();
343         (0, upper)
344     }
345 }