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