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, ToPolyTraitRef, ToPredicate, TyCtxt, WithConstness};
9 pub fn anonymize_predicate<'tcx>(
11 pred: &ty::Predicate<'tcx>,
12 ) -> ty::Predicate<'tcx> {
14 ty::PredicateKind::Trait(ref data, constness) => {
15 ty::PredicateKind::Trait(tcx.anonymize_late_bound_regions(data), constness)
18 ty::PredicateKind::RegionOutlives(ref data) => {
19 ty::PredicateKind::RegionOutlives(tcx.anonymize_late_bound_regions(data))
22 ty::PredicateKind::TypeOutlives(ref data) => {
23 ty::PredicateKind::TypeOutlives(tcx.anonymize_late_bound_regions(data))
26 ty::PredicateKind::Projection(ref data) => {
27 ty::PredicateKind::Projection(tcx.anonymize_late_bound_regions(data))
30 ty::PredicateKind::WellFormed(data) => ty::PredicateKind::WellFormed(data),
32 ty::PredicateKind::ObjectSafe(data) => ty::PredicateKind::ObjectSafe(data),
34 ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
35 ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind)
38 ty::PredicateKind::Subtype(ref data) => {
39 ty::PredicateKind::Subtype(tcx.anonymize_late_bound_regions(data))
42 ty::PredicateKind::ConstEvaluatable(def_id, substs) => {
43 ty::PredicateKind::ConstEvaluatable(def_id, substs)
46 ty::PredicateKind::ConstEquate(c1, c2) => ty::Predicate::ConstEquate(c1, c2),
50 struct PredicateSet<'tcx> {
52 set: FxHashSet<ty::Predicate<'tcx>>,
55 impl PredicateSet<'tcx> {
56 fn new(tcx: TyCtxt<'tcx>) -> Self {
57 Self { tcx, set: Default::default() }
60 fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {
61 // We have to be careful here because we want
63 // for<'a> Foo<&'a int>
67 // for<'b> Foo<&'b int>
69 // to be considered equivalent. So normalize all late-bound
70 // regions before we throw things into the underlying set.
71 self.set.insert(anonymize_predicate(self.tcx, pred))
75 impl<T: AsRef<ty::Predicate<'tcx>>> Extend<T> for PredicateSet<'tcx> {
76 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
78 self.insert(pred.as_ref());
83 ///////////////////////////////////////////////////////////////////////////
84 // `Elaboration` iterator
85 ///////////////////////////////////////////////////////////////////////////
87 /// "Elaboration" is the process of identifying all the predicates that
88 /// are implied by a source predicate. Currently, this basically means
89 /// walking the "supertraits" and other similar assumptions. For example,
90 /// if we know that `T: Ord`, the elaborator would deduce that `T: PartialOrd`
91 /// holds as well. Similarly, if we have `trait Foo: 'static`, and we know that
92 /// `T: Foo`, then we know that `T: 'static`.
93 pub struct Elaborator<'tcx> {
94 stack: Vec<PredicateObligation<'tcx>>,
95 visited: PredicateSet<'tcx>,
98 pub fn elaborate_trait_ref<'tcx>(
100 trait_ref: ty::PolyTraitRef<'tcx>,
101 ) -> Elaborator<'tcx> {
102 elaborate_predicates(tcx, std::iter::once(trait_ref.without_const().to_predicate()))
105 pub fn elaborate_trait_refs<'tcx>(
107 trait_refs: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
108 ) -> Elaborator<'tcx> {
109 let predicates = trait_refs.map(|trait_ref| trait_ref.without_const().to_predicate());
110 elaborate_predicates(tcx, predicates)
113 pub fn elaborate_predicates<'tcx>(
115 predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
116 ) -> Elaborator<'tcx> {
117 let obligations = predicates.map(|predicate| predicate_obligation(predicate, None)).collect();
118 elaborate_obligations(tcx, obligations)
121 pub fn elaborate_obligations<'tcx>(
123 mut obligations: Vec<PredicateObligation<'tcx>>,
124 ) -> Elaborator<'tcx> {
125 let mut visited = PredicateSet::new(tcx);
126 obligations.retain(|obligation| visited.insert(&obligation.predicate));
127 Elaborator { stack: obligations, visited }
130 fn predicate_obligation<'tcx>(
131 predicate: ty::Predicate<'tcx>,
133 ) -> PredicateObligation<'tcx> {
134 let mut cause = ObligationCause::dummy();
135 if let Some(span) = span {
138 Obligation { cause, param_env: ty::ParamEnv::empty(), recursion_depth: 0, predicate }
141 impl Elaborator<'tcx> {
142 pub fn filter_to_traits(self) -> FilterToTraits<Self> {
143 FilterToTraits::new(self)
146 fn elaborate(&mut self, obligation: &PredicateObligation<'tcx>) {
147 let tcx = self.visited.tcx;
148 match obligation.predicate {
149 ty::PredicateKind::Trait(ref data, _) => {
150 // Get predicates declared on the trait.
151 let predicates = tcx.super_predicates_of(data.def_id());
153 let obligations = predicates.predicates.iter().map(|(pred, span)| {
154 predicate_obligation(
155 pred.subst_supertrait(tcx, &data.to_poly_trait_ref()),
159 debug!("super_predicates: data={:?}", data);
161 // Only keep those bounds that we haven't already seen.
162 // This is necessary to prevent infinite recursion in some
163 // cases. One common case is when people define
164 // `trait Sized: Sized { }` rather than `trait Sized { }`.
165 let visited = &mut self.visited;
166 let obligations = obligations.filter(|o| visited.insert(&o.predicate));
168 self.stack.extend(obligations);
170 ty::PredicateKind::WellFormed(..) => {
171 // Currently, we do not elaborate WF predicates,
172 // although we easily could.
174 ty::PredicateKind::ObjectSafe(..) => {
175 // Currently, we do not elaborate object-safe
178 ty::PredicateKind::Subtype(..) => {
179 // Currently, we do not "elaborate" predicates like `X <: Y`,
180 // though conceivably we might.
182 ty::PredicateKind::Projection(..) => {
183 // Nothing to elaborate in a projection predicate.
185 ty::PredicateKind::ClosureKind(..) => {
186 // Nothing to elaborate when waiting for a closure's kind to be inferred.
188 ty::PredicateKind::ConstEvaluatable(..) => {
189 // Currently, we do not elaborate const-evaluatable
192 ty::PredicateKind::ConstEquate(..) => {
193 // Currently, we do not elaborate const-equate
196 ty::PredicateKind::RegionOutlives(..) => {
197 // Nothing to elaborate from `'a: 'b`.
199 ty::PredicateKind::TypeOutlives(ref data) => {
200 // We know that `T: 'a` for some type `T`. We can
201 // often elaborate this. For example, if we know that
202 // `[U]: 'a`, that implies that `U: 'a`. Similarly, if
203 // we know `&'a U: 'b`, then we know that `'a: 'b` and
206 // We can basically ignore bound regions here. So for
207 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
210 // Ignore `for<'a> T: 'a` -- we might in the future
211 // consider this as evidence that `T: 'static`, but
212 // I'm a bit wary of such constructions and so for now
213 // I want to be conservative. --nmatsakis
214 let ty_max = data.skip_binder().0;
215 let r_min = data.skip_binder().1;
216 if r_min.is_late_bound() {
220 let visited = &mut self.visited;
221 let mut components = smallvec![];
222 tcx.push_outlives_components(ty_max, &mut components);
226 .filter_map(|component| match component {
227 Component::Region(r) => {
228 if r.is_late_bound() {
231 Some(ty::PredicateKind::RegionOutlives(ty::Binder::dummy(
232 ty::OutlivesPredicate(r, r_min),
237 Component::Param(p) => {
238 let ty = tcx.mk_ty_param(p.index, p.name);
239 Some(ty::PredicateKind::TypeOutlives(ty::Binder::dummy(
240 ty::OutlivesPredicate(ty, r_min),
244 Component::UnresolvedInferenceVariable(_) => None,
246 Component::Projection(_) | Component::EscapingProjection(_) => {
247 // We can probably do more here. This
248 // corresponds to a case like `<T as
253 .filter(|p| visited.insert(p))
254 .map(|p| predicate_obligation(p, None)),
261 impl Iterator for Elaborator<'tcx> {
262 type Item = PredicateObligation<'tcx>;
264 fn size_hint(&self) -> (usize, Option<usize>) {
265 (self.stack.len(), None)
268 fn next(&mut self) -> Option<Self::Item> {
269 // Extract next item from top-most stack frame, if any.
270 if let Some(obligation) = self.stack.pop() {
271 self.elaborate(&obligation);
279 ///////////////////////////////////////////////////////////////////////////
280 // Supertrait iterator
281 ///////////////////////////////////////////////////////////////////////////
283 pub type Supertraits<'tcx> = FilterToTraits<Elaborator<'tcx>>;
285 pub fn supertraits<'tcx>(
287 trait_ref: ty::PolyTraitRef<'tcx>,
288 ) -> Supertraits<'tcx> {
289 elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
292 pub fn transitive_bounds<'tcx>(
294 bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
295 ) -> Supertraits<'tcx> {
296 elaborate_trait_refs(tcx, bounds).filter_to_traits()
299 ///////////////////////////////////////////////////////////////////////////
301 ///////////////////////////////////////////////////////////////////////////
303 /// A filter around an iterator of predicates that makes it yield up
304 /// just trait references.
305 pub struct FilterToTraits<I> {
309 impl<I> FilterToTraits<I> {
310 fn new(base: I) -> FilterToTraits<I> {
311 FilterToTraits { base_iterator: base }
315 impl<'tcx, I: Iterator<Item = PredicateObligation<'tcx>>> Iterator for FilterToTraits<I> {
316 type Item = ty::PolyTraitRef<'tcx>;
318 fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
319 while let Some(obligation) = self.base_iterator.next() {
320 if let ty::PredicateKind::Trait(data, _) = obligation.predicate {
321 return Some(data.to_poly_trait_ref());
327 fn size_hint(&self) -> (usize, Option<usize>) {
328 let (_, upper) = self.base_iterator.size_hint();