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