]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/traits/util.rs
Merge commit '266e96785ab71834b917bf474f130a6d8fdecd4b' into sync_cg_clif-2022-10-23
[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};
7 use rustc_span::symbol::Ident;
8 use rustc_span::Span;
9
10 pub fn anonymize_predicate<'tcx>(
11     tcx: TyCtxt<'tcx>,
12     pred: ty::Predicate<'tcx>,
13 ) -> ty::Predicate<'tcx> {
14     let new = tcx.anonymize_bound_vars(pred.kind());
15     tcx.reuse_or_mk_predicate(pred, new)
16 }
17
18 pub struct PredicateSet<'tcx> {
19     tcx: TyCtxt<'tcx>,
20     set: FxHashSet<ty::Predicate<'tcx>>,
21 }
22
23 impl<'tcx> PredicateSet<'tcx> {
24     pub fn new(tcx: TyCtxt<'tcx>) -> Self {
25         Self { tcx, set: Default::default() }
26     }
27
28     pub fn insert(&mut self, pred: ty::Predicate<'tcx>) -> bool {
29         // We have to be careful here because we want
30         //
31         //    for<'a> Foo<&'a i32>
32         //
33         // and
34         //
35         //    for<'b> Foo<&'b i32>
36         //
37         // to be considered equivalent. So normalize all late-bound
38         // regions before we throw things into the underlying set.
39         self.set.insert(anonymize_predicate(self.tcx, pred))
40     }
41 }
42
43 impl<'tcx> Extend<ty::Predicate<'tcx>> for PredicateSet<'tcx> {
44     fn extend<I: IntoIterator<Item = ty::Predicate<'tcx>>>(&mut self, iter: I) {
45         for pred in iter {
46             self.insert(pred);
47         }
48     }
49
50     fn extend_one(&mut self, pred: ty::Predicate<'tcx>) {
51         self.insert(pred);
52     }
53
54     fn extend_reserve(&mut self, additional: usize) {
55         Extend::<ty::Predicate<'tcx>>::extend_reserve(&mut self.set, additional);
56     }
57 }
58
59 ///////////////////////////////////////////////////////////////////////////
60 // `Elaboration` iterator
61 ///////////////////////////////////////////////////////////////////////////
62
63 /// "Elaboration" is the process of identifying all the predicates that
64 /// are implied by a source predicate. Currently, this basically means
65 /// walking the "supertraits" and other similar assumptions. For example,
66 /// if we know that `T: Ord`, the elaborator would deduce that `T: PartialOrd`
67 /// holds as well. Similarly, if we have `trait Foo: 'static`, and we know that
68 /// `T: Foo`, then we know that `T: 'static`.
69 pub struct Elaborator<'tcx> {
70     stack: Vec<PredicateObligation<'tcx>>,
71     visited: PredicateSet<'tcx>,
72 }
73
74 pub fn elaborate_trait_ref<'tcx>(
75     tcx: TyCtxt<'tcx>,
76     trait_ref: ty::PolyTraitRef<'tcx>,
77 ) -> Elaborator<'tcx> {
78     elaborate_predicates(tcx, std::iter::once(trait_ref.without_const().to_predicate(tcx)))
79 }
80
81 pub fn elaborate_trait_refs<'tcx>(
82     tcx: TyCtxt<'tcx>,
83     trait_refs: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
84 ) -> Elaborator<'tcx> {
85     let predicates = trait_refs.map(|trait_ref| trait_ref.without_const().to_predicate(tcx));
86     elaborate_predicates(tcx, predicates)
87 }
88
89 pub fn elaborate_predicates<'tcx>(
90     tcx: TyCtxt<'tcx>,
91     predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
92 ) -> Elaborator<'tcx> {
93     let obligations = predicates
94         .map(|predicate| {
95             predicate_obligation(predicate, ty::ParamEnv::empty(), ObligationCause::dummy())
96         })
97         .collect();
98     elaborate_obligations(tcx, obligations)
99 }
100
101 pub fn elaborate_predicates_with_span<'tcx>(
102     tcx: TyCtxt<'tcx>,
103     predicates: impl Iterator<Item = (ty::Predicate<'tcx>, Span)>,
104 ) -> Elaborator<'tcx> {
105     let obligations = predicates
106         .map(|(predicate, span)| {
107             predicate_obligation(
108                 predicate,
109                 ty::ParamEnv::empty(),
110                 ObligationCause::dummy_with_span(span),
111             )
112         })
113         .collect();
114     elaborate_obligations(tcx, obligations)
115 }
116
117 pub fn elaborate_obligations<'tcx>(
118     tcx: TyCtxt<'tcx>,
119     mut obligations: Vec<PredicateObligation<'tcx>>,
120 ) -> Elaborator<'tcx> {
121     let mut visited = PredicateSet::new(tcx);
122     obligations.retain(|obligation| visited.insert(obligation.predicate));
123     Elaborator { stack: obligations, visited }
124 }
125
126 fn predicate_obligation<'tcx>(
127     predicate: ty::Predicate<'tcx>,
128     param_env: ty::ParamEnv<'tcx>,
129     cause: ObligationCause<'tcx>,
130 ) -> PredicateObligation<'tcx> {
131     Obligation { cause, param_env, recursion_depth: 0, predicate }
132 }
133
134 impl<'tcx> Elaborator<'tcx> {
135     pub fn filter_to_traits(self) -> FilterToTraits<Self> {
136         FilterToTraits::new(self)
137     }
138
139     fn elaborate(&mut self, obligation: &PredicateObligation<'tcx>) {
140         let tcx = self.visited.tcx;
141
142         let bound_predicate = obligation.predicate.kind();
143         match bound_predicate.skip_binder() {
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(|&(mut pred, _)| {
149                     // when parent predicate is non-const, elaborate it to non-const predicates.
150                     if data.constness == ty::BoundConstness::NotConst {
151                         pred = pred.without_const(tcx);
152                     }
153
154                     predicate_obligation(
155                         pred.subst_supertrait(tcx, &bound_predicate.rebind(data.trait_ref)),
156                         obligation.param_env,
157                         obligation.cause.clone(),
158                     )
159                 });
160                 debug!(?data, ?obligations, "super_predicates");
161
162                 // Only keep those bounds that we haven't already seen.
163                 // This is necessary to prevent infinite recursion in some
164                 // cases. One common case is when people define
165                 // `trait Sized: Sized { }` rather than `trait Sized { }`.
166                 let visited = &mut self.visited;
167                 let obligations = obligations.filter(|o| visited.insert(o.predicate));
168
169                 self.stack.extend(obligations);
170             }
171             ty::PredicateKind::WellFormed(..) => {
172                 // Currently, we do not elaborate WF predicates,
173                 // although we easily could.
174             }
175             ty::PredicateKind::ObjectSafe(..) => {
176                 // Currently, we do not elaborate object-safe
177                 // predicates.
178             }
179             ty::PredicateKind::Subtype(..) => {
180                 // Currently, we do not "elaborate" predicates like `X <: Y`,
181                 // though conceivably we might.
182             }
183             ty::PredicateKind::Coerce(..) => {
184                 // Currently, we do not "elaborate" predicates like `X -> Y`,
185                 // though conceivably we might.
186             }
187             ty::PredicateKind::Projection(..) => {
188                 // Nothing to elaborate in a projection predicate.
189             }
190             ty::PredicateKind::ClosureKind(..) => {
191                 // Nothing to elaborate when waiting for a closure's kind to be inferred.
192             }
193             ty::PredicateKind::ConstEvaluatable(..) => {
194                 // Currently, we do not elaborate const-evaluatable
195                 // predicates.
196             }
197             ty::PredicateKind::ConstEquate(..) => {
198                 // Currently, we do not elaborate const-equate
199                 // predicates.
200             }
201             ty::PredicateKind::RegionOutlives(..) => {
202                 // Nothing to elaborate from `'a: 'b`.
203             }
204             ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_max, r_min)) => {
205                 // We know that `T: 'a` for some type `T`. We can
206                 // often elaborate this. For example, if we know that
207                 // `[U]: 'a`, that implies that `U: 'a`. Similarly, if
208                 // we know `&'a U: 'b`, then we know that `'a: 'b` and
209                 // `U: 'b`.
210                 //
211                 // We can basically ignore bound regions here. So for
212                 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
213                 // `'a: 'b`.
214
215                 // Ignore `for<'a> T: 'a` -- we might in the future
216                 // consider this as evidence that `T: 'static`, but
217                 // I'm a bit wary of such constructions and so for now
218                 // I want to be conservative. --nmatsakis
219                 if r_min.is_late_bound() {
220                     return;
221                 }
222
223                 let visited = &mut self.visited;
224                 let mut components = smallvec![];
225                 push_outlives_components(tcx, ty_max, &mut components);
226                 self.stack.extend(
227                     components
228                         .into_iter()
229                         .filter_map(|component| match component {
230                             Component::Region(r) => {
231                                 if r.is_late_bound() {
232                                     None
233                                 } else {
234                                     Some(ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(
235                                         r, r_min,
236                                     )))
237                                 }
238                             }
239
240                             Component::Param(p) => {
241                                 let ty = tcx.mk_ty_param(p.index, p.name);
242                                 Some(ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(
243                                     ty, r_min,
244                                 )))
245                             }
246
247                             Component::UnresolvedInferenceVariable(_) => None,
248
249                             Component::Opaque(def_id, substs) => {
250                                 let ty = tcx.mk_opaque(def_id, substs);
251                                 Some(ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(
252                                     ty, r_min,
253                                 )))
254                             }
255
256                             Component::Projection(projection) => {
257                                 // We might end up here if we have `Foo<<Bar as Baz>::Assoc>: 'a`.
258                                 // With this, we can deduce that `<Bar as Baz>::Assoc: 'a`.
259                                 let ty =
260                                     tcx.mk_projection(projection.item_def_id, projection.substs);
261                                 Some(ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(
262                                     ty, r_min,
263                                 )))
264                             }
265
266                             Component::EscapingProjection(_) => {
267                                 // We might be able to do more here, but we don't
268                                 // want to deal with escaping vars right now.
269                                 None
270                             }
271                         })
272                         .map(|predicate_kind| {
273                             bound_predicate.rebind(predicate_kind).to_predicate(tcx)
274                         })
275                         .filter(|&predicate| visited.insert(predicate))
276                         .map(|predicate| {
277                             predicate_obligation(
278                                 predicate,
279                                 obligation.param_env,
280                                 obligation.cause.clone(),
281                             )
282                         }),
283                 );
284             }
285             ty::PredicateKind::TypeWellFormedFromEnv(..) => {
286                 // Nothing to elaborate
287             }
288         }
289     }
290 }
291
292 impl<'tcx> Iterator for Elaborator<'tcx> {
293     type Item = PredicateObligation<'tcx>;
294
295     fn size_hint(&self) -> (usize, Option<usize>) {
296         (self.stack.len(), None)
297     }
298
299     fn next(&mut self) -> Option<Self::Item> {
300         // Extract next item from top-most stack frame, if any.
301         if let Some(obligation) = self.stack.pop() {
302             self.elaborate(&obligation);
303             Some(obligation)
304         } else {
305             None
306         }
307     }
308 }
309
310 ///////////////////////////////////////////////////////////////////////////
311 // Supertrait iterator
312 ///////////////////////////////////////////////////////////////////////////
313
314 pub type Supertraits<'tcx> = FilterToTraits<Elaborator<'tcx>>;
315
316 pub fn supertraits<'tcx>(
317     tcx: TyCtxt<'tcx>,
318     trait_ref: ty::PolyTraitRef<'tcx>,
319 ) -> Supertraits<'tcx> {
320     elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
321 }
322
323 pub fn transitive_bounds<'tcx>(
324     tcx: TyCtxt<'tcx>,
325     bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
326 ) -> Supertraits<'tcx> {
327     elaborate_trait_refs(tcx, bounds).filter_to_traits()
328 }
329
330 /// A specialized variant of `elaborate_trait_refs` that only elaborates trait references that may
331 /// define the given associated type `assoc_name`. It uses the
332 /// `super_predicates_that_define_assoc_type` query to avoid enumerating super-predicates that
333 /// aren't related to `assoc_item`.  This is used when resolving types like `Self::Item` or
334 /// `T::Item` and helps to avoid cycle errors (see e.g. #35237).
335 pub fn transitive_bounds_that_define_assoc_type<'tcx>(
336     tcx: TyCtxt<'tcx>,
337     bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
338     assoc_name: Ident,
339 ) -> impl Iterator<Item = ty::PolyTraitRef<'tcx>> {
340     let mut stack: Vec<_> = bounds.collect();
341     let mut visited = FxIndexSet::default();
342
343     std::iter::from_fn(move || {
344         while let Some(trait_ref) = stack.pop() {
345             let anon_trait_ref = tcx.anonymize_bound_vars(trait_ref);
346             if visited.insert(anon_trait_ref) {
347                 let super_predicates = tcx.super_predicates_that_define_assoc_type((
348                     trait_ref.def_id(),
349                     Some(assoc_name),
350                 ));
351                 for (super_predicate, _) in super_predicates.predicates {
352                     let subst_predicate = super_predicate.subst_supertrait(tcx, &trait_ref);
353                     if let Some(binder) = subst_predicate.to_opt_poly_trait_pred() {
354                         stack.push(binder.map_bound(|t| t.trait_ref));
355                     }
356                 }
357
358                 return Some(trait_ref);
359             }
360         }
361
362         return None;
363     })
364 }
365
366 ///////////////////////////////////////////////////////////////////////////
367 // Other
368 ///////////////////////////////////////////////////////////////////////////
369
370 /// A filter around an iterator of predicates that makes it yield up
371 /// just trait references.
372 pub struct FilterToTraits<I> {
373     base_iterator: I,
374 }
375
376 impl<I> FilterToTraits<I> {
377     fn new(base: I) -> FilterToTraits<I> {
378         FilterToTraits { base_iterator: base }
379     }
380 }
381
382 impl<'tcx, I: Iterator<Item = PredicateObligation<'tcx>>> Iterator for FilterToTraits<I> {
383     type Item = ty::PolyTraitRef<'tcx>;
384
385     fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
386         while let Some(obligation) = self.base_iterator.next() {
387             if let Some(data) = obligation.predicate.to_opt_poly_trait_pred() {
388                 return Some(data.map_bound(|t| t.trait_ref));
389             }
390         }
391         None
392     }
393
394     fn size_hint(&self) -> (usize, Option<usize>) {
395         let (_, upper) = self.base_iterator.size_hint();
396         (0, upper)
397     }
398 }