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