]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/traits/util.rs
Rollup merge of #89829 - voidc:assoc-const-variance, r=lcnr
[rust.git] / compiler / rustc_infer / src / traits / util.rs
1 use smallvec::smallvec;
2
3 use crate::infer::outlives::components::{push_outlives_components, Component};
4 use crate::traits::{Obligation, ObligationCause, PredicateObligation};
5 use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
6 use rustc_middle::ty::{self, ToPredicate, TyCtxt, WithConstness};
7 use rustc_span::symbol::Ident;
8
9 pub fn anonymize_predicate<'tcx>(
10     tcx: TyCtxt<'tcx>,
11     pred: ty::Predicate<'tcx>,
12 ) -> ty::Predicate<'tcx> {
13     let new = tcx.anonymize_late_bound_regions(pred.kind());
14     tcx.reuse_or_mk_predicate(pred, new)
15 }
16
17 pub struct PredicateSet<'tcx> {
18     tcx: TyCtxt<'tcx>,
19     set: FxHashSet<ty::Predicate<'tcx>>,
20 }
21
22 impl PredicateSet<'tcx> {
23     pub fn new(tcx: TyCtxt<'tcx>) -> Self {
24         Self { tcx, set: Default::default() }
25     }
26
27     pub fn insert(&mut self, pred: ty::Predicate<'tcx>) -> bool {
28         // We have to be careful here because we want
29         //
30         //    for<'a> Foo<&'a i32>
31         //
32         // and
33         //
34         //    for<'b> Foo<&'b i32>
35         //
36         // to be considered equivalent. So normalize all late-bound
37         // regions before we throw things into the underlying set.
38         self.set.insert(anonymize_predicate(self.tcx, pred))
39     }
40 }
41
42 impl Extend<ty::Predicate<'tcx>> for PredicateSet<'tcx> {
43     fn extend<I: IntoIterator<Item = ty::Predicate<'tcx>>>(&mut self, iter: I) {
44         for pred in iter {
45             self.insert(pred);
46         }
47     }
48
49     fn extend_one(&mut self, pred: ty::Predicate<'tcx>) {
50         self.insert(pred);
51     }
52
53     fn extend_reserve(&mut self, additional: usize) {
54         Extend::<ty::Predicate<'tcx>>::extend_reserve(&mut self.set, additional);
55     }
56 }
57
58 ///////////////////////////////////////////////////////////////////////////
59 // `Elaboration` iterator
60 ///////////////////////////////////////////////////////////////////////////
61
62 /// "Elaboration" is the process of identifying all the predicates that
63 /// are implied by a source predicate. Currently, this basically means
64 /// walking the "supertraits" and other similar assumptions. For example,
65 /// if we know that `T: Ord`, the elaborator would deduce that `T: PartialOrd`
66 /// holds as well. Similarly, if we have `trait Foo: 'static`, and we know that
67 /// `T: Foo`, then we know that `T: 'static`.
68 pub struct Elaborator<'tcx> {
69     stack: Vec<PredicateObligation<'tcx>>,
70     visited: PredicateSet<'tcx>,
71 }
72
73 pub fn elaborate_trait_ref<'tcx>(
74     tcx: TyCtxt<'tcx>,
75     trait_ref: ty::PolyTraitRef<'tcx>,
76 ) -> Elaborator<'tcx> {
77     elaborate_predicates(tcx, std::iter::once(trait_ref.without_const().to_predicate(tcx)))
78 }
79
80 pub fn elaborate_trait_refs<'tcx>(
81     tcx: TyCtxt<'tcx>,
82     trait_refs: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
83 ) -> Elaborator<'tcx> {
84     let predicates = trait_refs.map(|trait_ref| trait_ref.without_const().to_predicate(tcx));
85     elaborate_predicates(tcx, predicates)
86 }
87
88 pub fn elaborate_predicates<'tcx>(
89     tcx: TyCtxt<'tcx>,
90     predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
91 ) -> Elaborator<'tcx> {
92     let obligations = predicates
93         .map(|predicate| {
94             predicate_obligation(predicate, ty::ParamEnv::empty(), ObligationCause::dummy())
95         })
96         .collect();
97     elaborate_obligations(tcx, obligations)
98 }
99
100 pub fn elaborate_obligations<'tcx>(
101     tcx: TyCtxt<'tcx>,
102     mut obligations: Vec<PredicateObligation<'tcx>>,
103 ) -> Elaborator<'tcx> {
104     let mut visited = PredicateSet::new(tcx);
105     obligations.retain(|obligation| visited.insert(obligation.predicate));
106     Elaborator { stack: obligations, visited }
107 }
108
109 fn predicate_obligation<'tcx>(
110     predicate: ty::Predicate<'tcx>,
111     param_env: ty::ParamEnv<'tcx>,
112     cause: ObligationCause<'tcx>,
113 ) -> PredicateObligation<'tcx> {
114     Obligation { cause, param_env, recursion_depth: 0, predicate }
115 }
116
117 impl Elaborator<'tcx> {
118     pub fn filter_to_traits(self) -> FilterToTraits<Self> {
119         FilterToTraits::new(self)
120     }
121
122     fn elaborate(&mut self, obligation: &PredicateObligation<'tcx>) {
123         let tcx = self.visited.tcx;
124
125         let bound_predicate = obligation.predicate.kind();
126         match bound_predicate.skip_binder() {
127             ty::PredicateKind::Trait(data) => {
128                 // Get predicates declared on the trait.
129                 let predicates = tcx.super_predicates_of(data.def_id());
130
131                 let obligations = predicates.predicates.iter().map(|&(pred, _)| {
132                     predicate_obligation(
133                         pred.subst_supertrait(tcx, &bound_predicate.rebind(data.trait_ref)),
134                         obligation.param_env,
135                         obligation.cause.clone(),
136                     )
137                 });
138                 debug!("super_predicates: data={:?}", data);
139
140                 // Only keep those bounds that we haven't already seen.
141                 // This is necessary to prevent infinite recursion in some
142                 // cases. One common case is when people define
143                 // `trait Sized: Sized { }` rather than `trait Sized { }`.
144                 let visited = &mut self.visited;
145                 let obligations = obligations.filter(|o| visited.insert(o.predicate));
146
147                 self.stack.extend(obligations);
148             }
149             ty::PredicateKind::WellFormed(..) => {
150                 // Currently, we do not elaborate WF predicates,
151                 // although we easily could.
152             }
153             ty::PredicateKind::ObjectSafe(..) => {
154                 // Currently, we do not elaborate object-safe
155                 // predicates.
156             }
157             ty::PredicateKind::Subtype(..) => {
158                 // Currently, we do not "elaborate" predicates like `X <: Y`,
159                 // though conceivably we might.
160             }
161             ty::PredicateKind::Coerce(..) => {
162                 // Currently, we do not "elaborate" predicates like `X -> Y`,
163                 // though conceivably we might.
164             }
165             ty::PredicateKind::Projection(..) => {
166                 // Nothing to elaborate in a projection predicate.
167             }
168             ty::PredicateKind::ClosureKind(..) => {
169                 // Nothing to elaborate when waiting for a closure's kind to be inferred.
170             }
171             ty::PredicateKind::ConstEvaluatable(..) => {
172                 // Currently, we do not elaborate const-evaluatable
173                 // predicates.
174             }
175             ty::PredicateKind::ConstEquate(..) => {
176                 // Currently, we do not elaborate const-equate
177                 // predicates.
178             }
179             ty::PredicateKind::RegionOutlives(..) => {
180                 // Nothing to elaborate from `'a: 'b`.
181             }
182             ty::PredicateKind::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                 push_outlives_components(tcx, 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::PredicateKind::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::PredicateKind::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(ty::Binder::dummy)
235                         .map(|predicate_kind| predicate_kind.to_predicate(tcx))
236                         .filter(|&predicate| visited.insert(predicate))
237                         .map(|predicate| {
238                             predicate_obligation(
239                                 predicate,
240                                 obligation.param_env,
241                                 obligation.cause.clone(),
242                             )
243                         }),
244                 );
245             }
246             ty::PredicateKind::TypeWellFormedFromEnv(..) => {
247                 // Nothing to elaborate
248             }
249         }
250     }
251 }
252
253 impl Iterator for Elaborator<'tcx> {
254     type Item = PredicateObligation<'tcx>;
255
256     fn size_hint(&self) -> (usize, Option<usize>) {
257         (self.stack.len(), None)
258     }
259
260     fn next(&mut self) -> Option<Self::Item> {
261         // Extract next item from top-most stack frame, if any.
262         if let Some(obligation) = self.stack.pop() {
263             self.elaborate(&obligation);
264             Some(obligation)
265         } else {
266             None
267         }
268     }
269 }
270
271 ///////////////////////////////////////////////////////////////////////////
272 // Supertrait iterator
273 ///////////////////////////////////////////////////////////////////////////
274
275 pub type Supertraits<'tcx> = FilterToTraits<Elaborator<'tcx>>;
276
277 pub fn supertraits<'tcx>(
278     tcx: TyCtxt<'tcx>,
279     trait_ref: ty::PolyTraitRef<'tcx>,
280 ) -> Supertraits<'tcx> {
281     elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
282 }
283
284 pub fn transitive_bounds<'tcx>(
285     tcx: TyCtxt<'tcx>,
286     bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
287 ) -> Supertraits<'tcx> {
288     elaborate_trait_refs(tcx, bounds).filter_to_traits()
289 }
290
291 /// A specialized variant of `elaborate_trait_refs` that only elaborates trait references that may
292 /// define the given associated type `assoc_name`. It uses the
293 /// `super_predicates_that_define_assoc_type` query to avoid enumerating super-predicates that
294 /// aren't related to `assoc_item`.  This is used when resolving types like `Self::Item` or
295 /// `T::Item` and helps to avoid cycle errors (see e.g. #35237).
296 pub fn transitive_bounds_that_define_assoc_type<'tcx>(
297     tcx: TyCtxt<'tcx>,
298     bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
299     assoc_name: Ident,
300 ) -> impl Iterator<Item = ty::PolyTraitRef<'tcx>> {
301     let mut stack: Vec<_> = bounds.collect();
302     let mut visited = FxIndexSet::default();
303
304     std::iter::from_fn(move || {
305         while let Some(trait_ref) = stack.pop() {
306             let anon_trait_ref = tcx.anonymize_late_bound_regions(trait_ref);
307             if visited.insert(anon_trait_ref) {
308                 let super_predicates = tcx.super_predicates_that_define_assoc_type((
309                     trait_ref.def_id(),
310                     Some(assoc_name),
311                 ));
312                 for (super_predicate, _) in super_predicates.predicates {
313                     let subst_predicate = super_predicate.subst_supertrait(tcx, &trait_ref);
314                     if let Some(binder) = subst_predicate.to_opt_poly_trait_ref() {
315                         stack.push(binder.value);
316                     }
317                 }
318
319                 return Some(trait_ref);
320             }
321         }
322
323         return None;
324     })
325 }
326
327 ///////////////////////////////////////////////////////////////////////////
328 // Other
329 ///////////////////////////////////////////////////////////////////////////
330
331 /// A filter around an iterator of predicates that makes it yield up
332 /// just trait references.
333 pub struct FilterToTraits<I> {
334     base_iterator: I,
335 }
336
337 impl<I> FilterToTraits<I> {
338     fn new(base: I) -> FilterToTraits<I> {
339         FilterToTraits { base_iterator: base }
340     }
341 }
342
343 impl<'tcx, I: Iterator<Item = PredicateObligation<'tcx>>> Iterator for FilterToTraits<I> {
344     type Item = ty::PolyTraitRef<'tcx>;
345
346     fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
347         while let Some(obligation) = self.base_iterator.next() {
348             if let Some(data) = obligation.predicate.to_opt_poly_trait_ref() {
349                 return Some(data.value);
350             }
351         }
352         None
353     }
354
355     fn size_hint(&self) -> (usize, Option<usize>) {
356         let (_, upper) = self.base_iterator.size_hint();
357         (0, upper)
358     }
359 }