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> {
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)
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,
31 struct PredicateSet<'tcx> {
33 set: FxHashSet<ty::Predicate<'tcx>>,
36 impl PredicateSet<'tcx> {
37 fn new(tcx: TyCtxt<'tcx>) -> Self {
38 Self { tcx, set: Default::default() }
41 fn insert(&mut self, pred: ty::Predicate<'tcx>) -> bool {
42 // We have to be careful here because we want
44 // for<'a> Foo<&'a i32>
48 // for<'b> Foo<&'b i32>
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))
56 impl Extend<ty::Predicate<'tcx>> for PredicateSet<'tcx> {
57 fn extend<I: IntoIterator<Item = ty::Predicate<'tcx>>>(&mut self, iter: I) {
63 fn extend_one(&mut self, pred: ty::Predicate<'tcx>) {
67 fn extend_reserve(&mut self, additional: usize) {
68 Extend::<ty::Predicate<'tcx>>::extend_reserve(&mut self.set, additional);
72 ///////////////////////////////////////////////////////////////////////////
73 // `Elaboration` iterator
74 ///////////////////////////////////////////////////////////////////////////
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>,
87 pub fn elaborate_trait_ref<'tcx>(
89 trait_ref: ty::PolyTraitRef<'tcx>,
90 ) -> Elaborator<'tcx> {
91 elaborate_predicates(tcx, std::iter::once(trait_ref.without_const().to_predicate(tcx)))
94 pub fn elaborate_trait_refs<'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)
102 pub fn elaborate_predicates<'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)
110 pub fn elaborate_obligations<'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 }
119 fn predicate_obligation<'tcx>(
120 predicate: ty::Predicate<'tcx>,
122 ) -> PredicateObligation<'tcx> {
123 let cause = if let Some(span) = span {
124 ObligationCause::dummy_with_span(span)
126 ObligationCause::dummy()
129 Obligation { cause, param_env: ty::ParamEnv::empty(), recursion_depth: 0, predicate }
132 impl Elaborator<'tcx> {
133 pub fn filter_to_traits(self) -> FilterToTraits<Self> {
134 FilterToTraits::new(self)
137 fn elaborate(&mut self, obligation: &PredicateObligation<'tcx>) {
138 let tcx = self.visited.tcx;
140 match obligation.predicate.ignore_quantifiers().skip_binder().kind() {
141 ty::PredicateKind::ForAll(_) => {
142 bug!("unexpected predicate: {:?}", obligation.predicate)
144 ty::PredicateKind::Trait(data, _) => {
145 // Get predicates declared on the trait.
146 let predicates = tcx.super_predicates_of(data.def_id());
148 let obligations = predicates.predicates.iter().map(|&(pred, span)| {
149 predicate_obligation(
150 pred.subst_supertrait(tcx, &ty::Binder::bind(data.trait_ref)),
154 debug!("super_predicates: data={:?}", data);
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));
163 self.stack.extend(obligations);
165 ty::PredicateKind::WellFormed(..) => {
166 // Currently, we do not elaborate WF predicates,
167 // although we easily could.
169 ty::PredicateKind::ObjectSafe(..) => {
170 // Currently, we do not elaborate object-safe
173 ty::PredicateKind::Subtype(..) => {
174 // Currently, we do not "elaborate" predicates like `X <: Y`,
175 // though conceivably we might.
177 ty::PredicateKind::Projection(..) => {
178 // Nothing to elaborate in a projection predicate.
180 ty::PredicateKind::ClosureKind(..) => {
181 // Nothing to elaborate when waiting for a closure's kind to be inferred.
183 ty::PredicateKind::ConstEvaluatable(..) => {
184 // Currently, we do not elaborate const-evaluatable
187 ty::PredicateKind::ConstEquate(..) => {
188 // Currently, we do not elaborate const-equate
191 ty::PredicateKind::RegionOutlives(..) => {
192 // Nothing to elaborate from `'a: 'b`.
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
201 // We can basically ignore bound regions here. So for
202 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
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() {
213 let visited = &mut self.visited;
214 let mut components = smallvec![];
215 tcx.push_outlives_components(ty_max, &mut components);
219 .filter_map(|component| match component {
220 Component::Region(r) => {
221 if r.is_late_bound() {
224 Some(ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(
230 Component::Param(p) => {
231 let ty = tcx.mk_ty_param(p.index, p.name);
232 Some(ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(
237 Component::UnresolvedInferenceVariable(_) => None,
239 Component::Projection(_) | Component::EscapingProjection(_) => {
240 // We can probably do more here. This
241 // corresponds to a case like `<T as
246 .map(|predicate_kind| predicate_kind.to_predicate(tcx))
247 .filter(|&predicate| visited.insert(predicate))
248 .map(|predicate| predicate_obligation(predicate, None)),
255 impl Iterator for Elaborator<'tcx> {
256 type Item = PredicateObligation<'tcx>;
258 fn size_hint(&self) -> (usize, Option<usize>) {
259 (self.stack.len(), None)
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);
273 ///////////////////////////////////////////////////////////////////////////
274 // Supertrait iterator
275 ///////////////////////////////////////////////////////////////////////////
277 pub type Supertraits<'tcx> = FilterToTraits<Elaborator<'tcx>>;
279 pub fn supertraits<'tcx>(
281 trait_ref: ty::PolyTraitRef<'tcx>,
282 ) -> Supertraits<'tcx> {
283 elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
286 pub fn transitive_bounds<'tcx>(
288 bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
289 ) -> Supertraits<'tcx> {
290 elaborate_trait_refs(tcx, bounds).filter_to_traits()
293 ///////////////////////////////////////////////////////////////////////////
295 ///////////////////////////////////////////////////////////////////////////
297 /// A filter around an iterator of predicates that makes it yield up
298 /// just trait references.
299 pub struct FilterToTraits<I> {
303 impl<I> FilterToTraits<I> {
304 fn new(base: I) -> FilterToTraits<I> {
305 FilterToTraits { base_iterator: base }
309 impl<'tcx, I: Iterator<Item = PredicateObligation<'tcx>>> Iterator for FilterToTraits<I> {
310 type Item = ty::PolyTraitRef<'tcx>;
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() {
321 fn size_hint(&self) -> (usize, Option<usize>) {
322 let (_, upper) = self.base_iterator.size_hint();