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::Atom(_) => pred,
22 struct PredicateSet<'tcx> {
24 set: FxHashSet<ty::Predicate<'tcx>>,
27 impl PredicateSet<'tcx> {
28 fn new(tcx: TyCtxt<'tcx>) -> Self {
29 Self { tcx, set: Default::default() }
32 fn insert(&mut self, pred: ty::Predicate<'tcx>) -> bool {
33 // We have to be careful here because we want
35 // for<'a> Foo<&'a i32>
39 // for<'b> Foo<&'b i32>
41 // to be considered equivalent. So normalize all late-bound
42 // regions before we throw things into the underlying set.
43 self.set.insert(anonymize_predicate(self.tcx, pred))
47 impl Extend<ty::Predicate<'tcx>> for PredicateSet<'tcx> {
48 fn extend<I: IntoIterator<Item = ty::Predicate<'tcx>>>(&mut self, iter: I) {
54 fn extend_one(&mut self, pred: ty::Predicate<'tcx>) {
58 fn extend_reserve(&mut self, additional: usize) {
59 Extend::<ty::Predicate<'tcx>>::extend_reserve(&mut self.set, additional);
63 ///////////////////////////////////////////////////////////////////////////
64 // `Elaboration` iterator
65 ///////////////////////////////////////////////////////////////////////////
67 /// "Elaboration" is the process of identifying all the predicates that
68 /// are implied by a source predicate. Currently, this basically means
69 /// walking the "supertraits" and other similar assumptions. For example,
70 /// if we know that `T: Ord`, the elaborator would deduce that `T: PartialOrd`
71 /// holds as well. Similarly, if we have `trait Foo: 'static`, and we know that
72 /// `T: Foo`, then we know that `T: 'static`.
73 pub struct Elaborator<'tcx> {
74 stack: Vec<PredicateObligation<'tcx>>,
75 visited: PredicateSet<'tcx>,
78 pub fn elaborate_trait_ref<'tcx>(
80 trait_ref: ty::PolyTraitRef<'tcx>,
81 ) -> Elaborator<'tcx> {
82 elaborate_predicates(tcx, std::iter::once(trait_ref.without_const().to_predicate(tcx)))
85 pub fn elaborate_trait_refs<'tcx>(
87 trait_refs: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
88 ) -> Elaborator<'tcx> {
89 let predicates = trait_refs.map(|trait_ref| trait_ref.without_const().to_predicate(tcx));
90 elaborate_predicates(tcx, predicates)
93 pub fn elaborate_predicates<'tcx>(
95 predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
96 ) -> Elaborator<'tcx> {
97 let obligations = predicates.map(|predicate| predicate_obligation(predicate, None)).collect();
98 elaborate_obligations(tcx, obligations)
101 pub fn elaborate_obligations<'tcx>(
103 mut obligations: Vec<PredicateObligation<'tcx>>,
104 ) -> Elaborator<'tcx> {
105 let mut visited = PredicateSet::new(tcx);
106 obligations.retain(|obligation| visited.insert(obligation.predicate));
107 Elaborator { stack: obligations, visited }
110 fn predicate_obligation<'tcx>(
111 predicate: ty::Predicate<'tcx>,
113 ) -> PredicateObligation<'tcx> {
114 let cause = if let Some(span) = span {
115 ObligationCause::dummy_with_span(span)
117 ObligationCause::dummy()
120 Obligation { cause, param_env: ty::ParamEnv::empty(), recursion_depth: 0, predicate }
123 impl Elaborator<'tcx> {
124 pub fn filter_to_traits(self) -> FilterToTraits<Self> {
125 FilterToTraits::new(self)
128 fn elaborate(&mut self, obligation: &PredicateObligation<'tcx>) {
129 let tcx = self.visited.tcx;
131 match obligation.predicate.skip_binders() {
132 ty::PredicateAtom::Trait(data, _) => {
133 // Get predicates declared on the trait.
134 let predicates = tcx.super_predicates_of(data.def_id());
136 let obligations = predicates.predicates.iter().map(|&(pred, span)| {
137 predicate_obligation(
138 pred.subst_supertrait(tcx, &ty::Binder::bind(data.trait_ref)),
142 debug!("super_predicates: data={:?}", data);
144 // Only keep those bounds that we haven't already seen.
145 // This is necessary to prevent infinite recursion in some
146 // cases. One common case is when people define
147 // `trait Sized: Sized { }` rather than `trait Sized { }`.
148 let visited = &mut self.visited;
149 let obligations = obligations.filter(|o| visited.insert(o.predicate));
151 self.stack.extend(obligations);
153 ty::PredicateAtom::WellFormed(..) => {
154 // Currently, we do not elaborate WF predicates,
155 // although we easily could.
157 ty::PredicateAtom::ObjectSafe(..) => {
158 // Currently, we do not elaborate object-safe
161 ty::PredicateAtom::Subtype(..) => {
162 // Currently, we do not "elaborate" predicates like `X <: Y`,
163 // though conceivably we might.
165 ty::PredicateAtom::Projection(..) => {
166 // Nothing to elaborate in a projection predicate.
168 ty::PredicateAtom::ClosureKind(..) => {
169 // Nothing to elaborate when waiting for a closure's kind to be inferred.
171 ty::PredicateAtom::ConstEvaluatable(..) => {
172 // Currently, we do not elaborate const-evaluatable
175 ty::PredicateAtom::ConstEquate(..) => {
176 // Currently, we do not elaborate const-equate
179 ty::PredicateAtom::RegionOutlives(..) => {
180 // Nothing to elaborate from `'a: 'b`.
182 ty::PredicateAtom::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
189 // We can basically ignore bound regions here. So for
190 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
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() {
201 let visited = &mut self.visited;
202 let mut components = smallvec![];
203 tcx.push_outlives_components(ty_max, &mut components);
207 .filter_map(|component| match component {
208 Component::Region(r) => {
209 if r.is_late_bound() {
212 Some(ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(
218 Component::Param(p) => {
219 let ty = tcx.mk_ty_param(p.index, p.name);
220 Some(ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(
225 Component::UnresolvedInferenceVariable(_) => None,
227 Component::Projection(_) | Component::EscapingProjection(_) => {
228 // We can probably do more here. This
229 // corresponds to a case like `<T as
234 .map(|predicate_kind| predicate_kind.to_predicate(tcx))
235 .filter(|&predicate| visited.insert(predicate))
236 .map(|predicate| predicate_obligation(predicate, None)),
243 impl Iterator for Elaborator<'tcx> {
244 type Item = PredicateObligation<'tcx>;
246 fn size_hint(&self) -> (usize, Option<usize>) {
247 (self.stack.len(), None)
250 fn next(&mut self) -> Option<Self::Item> {
251 // Extract next item from top-most stack frame, if any.
252 if let Some(obligation) = self.stack.pop() {
253 self.elaborate(&obligation);
261 ///////////////////////////////////////////////////////////////////////////
262 // Supertrait iterator
263 ///////////////////////////////////////////////////////////////////////////
265 pub type Supertraits<'tcx> = FilterToTraits<Elaborator<'tcx>>;
267 pub fn supertraits<'tcx>(
269 trait_ref: ty::PolyTraitRef<'tcx>,
270 ) -> Supertraits<'tcx> {
271 elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
274 pub fn transitive_bounds<'tcx>(
276 bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
277 ) -> Supertraits<'tcx> {
278 elaborate_trait_refs(tcx, bounds).filter_to_traits()
281 ///////////////////////////////////////////////////////////////////////////
283 ///////////////////////////////////////////////////////////////////////////
285 /// A filter around an iterator of predicates that makes it yield up
286 /// just trait references.
287 pub struct FilterToTraits<I> {
291 impl<I> FilterToTraits<I> {
292 fn new(base: I) -> FilterToTraits<I> {
293 FilterToTraits { base_iterator: base }
297 impl<'tcx, I: Iterator<Item = PredicateObligation<'tcx>>> Iterator for FilterToTraits<I> {
298 type Item = ty::PolyTraitRef<'tcx>;
300 fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
301 while let Some(obligation) = self.base_iterator.next() {
302 if let Some(data) = obligation.predicate.to_opt_poly_trait_ref() {
309 fn size_hint(&self) -> (usize, Option<usize>) {
310 let (_, upper) = self.base_iterator.size_hint();