1 use smallvec::smallvec;
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};
9 pub fn anonymize_predicate<'tcx>(
11 pred: ty::Predicate<'tcx>,
12 ) -> ty::Predicate<'tcx> {
13 let kind = pred.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 }
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,
32 struct PredicateSet<'tcx> {
34 set: FxHashSet<ty::Predicate<'tcx>>,
37 impl PredicateSet<'tcx> {
38 fn new(tcx: TyCtxt<'tcx>) -> Self {
39 Self { tcx, set: Default::default() }
42 fn insert(&mut self, pred: ty::Predicate<'tcx>) -> bool {
43 // We have to be careful here because we want
45 // for<'a> Foo<&'a i32>
49 // for<'b> Foo<&'b i32>
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))
57 impl Extend<ty::Predicate<'tcx>> for PredicateSet<'tcx> {
58 fn extend<I: IntoIterator<Item = ty::Predicate<'tcx>>>(&mut self, iter: I) {
64 fn extend_one(&mut self, pred: ty::Predicate<'tcx>) {
68 fn extend_reserve(&mut self, additional: usize) {
69 Extend::<ty::Predicate<'tcx>>::extend_reserve(&mut self.set, additional);
73 ///////////////////////////////////////////////////////////////////////////
74 // `Elaboration` iterator
75 ///////////////////////////////////////////////////////////////////////////
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>,
88 pub fn elaborate_trait_ref<'tcx>(
90 trait_ref: ty::PolyTraitRef<'tcx>,
91 ) -> Elaborator<'tcx> {
92 elaborate_predicates(tcx, std::iter::once(trait_ref.without_const().to_predicate(tcx)))
95 pub fn elaborate_trait_refs<'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)
103 pub fn elaborate_predicates<'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)
111 pub fn elaborate_obligations<'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 }
120 fn predicate_obligation<'tcx>(
121 predicate: ty::Predicate<'tcx>,
123 ) -> PredicateObligation<'tcx> {
124 let cause = if let Some(span) = span {
125 ObligationCause::dummy_with_span(span)
127 ObligationCause::dummy()
130 Obligation { cause, param_env: ty::ParamEnv::empty(), recursion_depth: 0, predicate }
133 impl Elaborator<'tcx> {
134 pub fn filter_to_traits(self) -> FilterToTraits<Self> {
135 FilterToTraits::new(self)
138 fn elaborate(&mut self, obligation: &PredicateObligation<'tcx>) {
139 let tcx = self.visited.tcx;
141 match obligation.predicate.ignore_quantifiers().skip_binder().kind() {
142 ty::PredicateKind::ForAll(_) => {
143 bug!("unexpected predicate: {:?}", obligation.predicate)
145 ty::PredicateKind::Trait(data, _) => {
146 // Get predicates declared on the trait.
147 let predicates = tcx.super_predicates_of(data.def_id());
149 let obligations = predicates.predicates.iter().map(|&(pred, span)| {
150 predicate_obligation(
151 pred.subst_supertrait(tcx, &ty::Binder::bind(data.trait_ref)),
155 debug!("super_predicates: data={:?}", data);
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));
164 self.stack.extend(obligations);
166 ty::PredicateKind::WellFormed(..) => {
167 // Currently, we do not elaborate WF predicates,
168 // although we easily could.
170 ty::PredicateKind::ObjectSafe(..) => {
171 // Currently, we do not elaborate object-safe
174 ty::PredicateKind::Subtype(..) => {
175 // Currently, we do not "elaborate" predicates like `X <: Y`,
176 // though conceivably we might.
178 ty::PredicateKind::Projection(..) => {
179 // Nothing to elaborate in a projection predicate.
181 ty::PredicateKind::ClosureKind(..) => {
182 // Nothing to elaborate when waiting for a closure's kind to be inferred.
184 ty::PredicateKind::ConstEvaluatable(..) => {
185 // Currently, we do not elaborate const-evaluatable
188 ty::PredicateKind::ConstEquate(..) => {
189 // Currently, we do not elaborate const-equate
192 ty::PredicateKind::RegionOutlives(..) => {
193 // Nothing to elaborate from `'a: 'b`.
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
202 // We can basically ignore bound regions here. So for
203 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
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() {
214 let visited = &mut self.visited;
215 let mut components = smallvec![];
216 tcx.push_outlives_components(ty_max, &mut components);
220 .filter_map(|component| match component {
221 Component::Region(r) => {
222 if r.is_late_bound() {
225 Some(ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(
231 Component::Param(p) => {
232 let ty = tcx.mk_ty_param(p.index, p.name);
233 Some(ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(
238 Component::UnresolvedInferenceVariable(_) => None,
240 Component::Projection(_) | Component::EscapingProjection(_) => {
241 // We can probably do more here. This
242 // corresponds to a case like `<T as
247 .map(|predicate_kind| predicate_kind.to_predicate(tcx))
248 .filter(|&predicate| visited.insert(predicate))
249 .map(|predicate| predicate_obligation(predicate, None)),
256 impl Iterator for Elaborator<'tcx> {
257 type Item = PredicateObligation<'tcx>;
259 fn size_hint(&self) -> (usize, Option<usize>) {
260 (self.stack.len(), None)
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);
274 ///////////////////////////////////////////////////////////////////////////
275 // Supertrait iterator
276 ///////////////////////////////////////////////////////////////////////////
278 pub type Supertraits<'tcx> = FilterToTraits<Elaborator<'tcx>>;
280 pub fn supertraits<'tcx>(
282 trait_ref: ty::PolyTraitRef<'tcx>,
283 ) -> Supertraits<'tcx> {
284 elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
287 pub fn transitive_bounds<'tcx>(
289 bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
290 ) -> Supertraits<'tcx> {
291 elaborate_trait_refs(tcx, bounds).filter_to_traits()
294 ///////////////////////////////////////////////////////////////////////////
296 ///////////////////////////////////////////////////////////////////////////
298 /// A filter around an iterator of predicates that makes it yield up
299 /// just trait references.
300 pub struct FilterToTraits<I> {
304 impl<I> FilterToTraits<I> {
305 fn new(base: I) -> FilterToTraits<I> {
306 FilterToTraits { base_iterator: base }
310 impl<'tcx, I: Iterator<Item = PredicateObligation<'tcx>>> Iterator for FilterToTraits<I> {
311 type Item = ty::PolyTraitRef<'tcx>;
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() {
322 fn size_hint(&self) -> (usize, Option<usize>) {
323 let (_, upper) = self.base_iterator.size_hint();