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