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> {
13 let kind = pred.kind();
14 let new = match kind {
15 &ty::PredicateKind::Trait(ref data, constness) => {
16 ty::PredicateKind::Trait(tcx.anonymize_late_bound_regions(data), constness)
19 ty::PredicateKind::RegionOutlives(data) => {
20 ty::PredicateKind::RegionOutlives(tcx.anonymize_late_bound_regions(data))
23 ty::PredicateKind::TypeOutlives(data) => {
24 ty::PredicateKind::TypeOutlives(tcx.anonymize_late_bound_regions(data))
27 ty::PredicateKind::Projection(data) => {
28 ty::PredicateKind::Projection(tcx.anonymize_late_bound_regions(data))
31 &ty::PredicateKind::WellFormed(data) => ty::PredicateKind::WellFormed(data),
33 &ty::PredicateKind::ObjectSafe(data) => ty::PredicateKind::ObjectSafe(data),
35 &ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
36 ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind)
39 ty::PredicateKind::Subtype(data) => {
40 ty::PredicateKind::Subtype(tcx.anonymize_late_bound_regions(data))
43 &ty::PredicateKind::ConstEvaluatable(def_id, substs) => {
44 ty::PredicateKind::ConstEvaluatable(def_id, substs)
47 ty::PredicateKind::ConstEquate(c1, c2) => ty::PredicateKind::ConstEquate(c1, c2),
50 if new != *kind { new.to_predicate(tcx) } else { pred }
53 struct PredicateSet<'tcx> {
55 set: FxHashSet<ty::Predicate<'tcx>>,
58 impl PredicateSet<'tcx> {
59 fn new(tcx: TyCtxt<'tcx>) -> Self {
60 Self { tcx, set: Default::default() }
63 fn insert(&mut self, pred: ty::Predicate<'tcx>) -> bool {
64 // We have to be careful here because we want
66 // for<'a> Foo<&'a int>
70 // for<'b> Foo<&'b int>
72 // to be considered equivalent. So normalize all late-bound
73 // regions before we throw things into the underlying set.
74 self.set.insert(anonymize_predicate(self.tcx, pred))
78 impl Extend<ty::Predicate<'tcx>> for PredicateSet<'tcx> {
79 fn extend<I: IntoIterator<Item = ty::Predicate<'tcx>>>(&mut self, iter: I) {
85 fn extend_one(&mut self, pred: ty::Predicate<'tcx>) {
89 fn extend_reserve(&mut self, additional: usize) {
90 Extend::<ty::Predicate<'tcx>>::extend_reserve(&mut self.set, additional);
94 ///////////////////////////////////////////////////////////////////////////
95 // `Elaboration` iterator
96 ///////////////////////////////////////////////////////////////////////////
98 /// "Elaboration" is the process of identifying all the predicates that
99 /// are implied by a source predicate. Currently, this basically means
100 /// walking the "supertraits" and other similar assumptions. For example,
101 /// if we know that `T: Ord`, the elaborator would deduce that `T: PartialOrd`
102 /// holds as well. Similarly, if we have `trait Foo: 'static`, and we know that
103 /// `T: Foo`, then we know that `T: 'static`.
104 pub struct Elaborator<'tcx> {
105 stack: Vec<PredicateObligation<'tcx>>,
106 visited: PredicateSet<'tcx>,
109 pub fn elaborate_trait_ref<'tcx>(
111 trait_ref: ty::PolyTraitRef<'tcx>,
112 ) -> Elaborator<'tcx> {
113 elaborate_predicates(tcx, std::iter::once(trait_ref.without_const().to_predicate(tcx)))
116 pub fn elaborate_trait_refs<'tcx>(
118 trait_refs: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
119 ) -> Elaborator<'tcx> {
120 let predicates = trait_refs.map(|trait_ref| trait_ref.without_const().to_predicate(tcx));
121 elaborate_predicates(tcx, predicates)
124 pub fn elaborate_predicates<'tcx>(
126 predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
127 ) -> Elaborator<'tcx> {
128 let obligations = predicates.map(|predicate| predicate_obligation(predicate, None)).collect();
129 elaborate_obligations(tcx, obligations)
132 pub fn elaborate_obligations<'tcx>(
134 mut obligations: Vec<PredicateObligation<'tcx>>,
135 ) -> Elaborator<'tcx> {
136 let mut visited = PredicateSet::new(tcx);
137 obligations.retain(|obligation| visited.insert(obligation.predicate));
138 Elaborator { stack: obligations, visited }
141 fn predicate_obligation<'tcx>(
142 predicate: ty::Predicate<'tcx>,
144 ) -> PredicateObligation<'tcx> {
145 let cause = if let Some(span) = span {
146 ObligationCause::dummy_with_span(span)
148 ObligationCause::dummy()
151 Obligation { cause, param_env: ty::ParamEnv::empty(), recursion_depth: 0, predicate }
154 impl Elaborator<'tcx> {
155 pub fn filter_to_traits(self) -> FilterToTraits<Self> {
156 FilterToTraits::new(self)
159 fn elaborate(&mut self, obligation: &PredicateObligation<'tcx>) {
160 let tcx = self.visited.tcx;
161 match obligation.predicate.kind() {
162 ty::PredicateKind::Trait(ref data, _) => {
163 // Get predicates declared on the trait.
164 let predicates = tcx.super_predicates_of(data.def_id());
166 let obligations = predicates.predicates.iter().map(|(pred, span)| {
167 predicate_obligation(
168 pred.subst_supertrait(tcx, &data.to_poly_trait_ref()),
172 debug!("super_predicates: data={:?}", data);
174 // Only keep those bounds that we haven't already seen.
175 // This is necessary to prevent infinite recursion in some
176 // cases. One common case is when people define
177 // `trait Sized: Sized { }` rather than `trait Sized { }`.
178 let visited = &mut self.visited;
179 let obligations = obligations.filter(|o| visited.insert(o.predicate));
181 self.stack.extend(obligations);
183 ty::PredicateKind::WellFormed(..) => {
184 // Currently, we do not elaborate WF predicates,
185 // although we easily could.
187 ty::PredicateKind::ObjectSafe(..) => {
188 // Currently, we do not elaborate object-safe
191 ty::PredicateKind::Subtype(..) => {
192 // Currently, we do not "elaborate" predicates like `X <: Y`,
193 // though conceivably we might.
195 ty::PredicateKind::Projection(..) => {
196 // Nothing to elaborate in a projection predicate.
198 ty::PredicateKind::ClosureKind(..) => {
199 // Nothing to elaborate when waiting for a closure's kind to be inferred.
201 ty::PredicateKind::ConstEvaluatable(..) => {
202 // Currently, we do not elaborate const-evaluatable
205 ty::PredicateKind::ConstEquate(..) => {
206 // Currently, we do not elaborate const-equate
209 ty::PredicateKind::RegionOutlives(..) => {
210 // Nothing to elaborate from `'a: 'b`.
212 ty::PredicateKind::TypeOutlives(ref data) => {
213 // We know that `T: 'a` for some type `T`. We can
214 // often elaborate this. For example, if we know that
215 // `[U]: 'a`, that implies that `U: 'a`. Similarly, if
216 // we know `&'a U: 'b`, then we know that `'a: 'b` and
219 // We can basically ignore bound regions here. So for
220 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
223 // Ignore `for<'a> T: 'a` -- we might in the future
224 // consider this as evidence that `T: 'static`, but
225 // I'm a bit wary of such constructions and so for now
226 // I want to be conservative. --nmatsakis
227 let ty_max = data.skip_binder().0;
228 let r_min = data.skip_binder().1;
229 if r_min.is_late_bound() {
233 let visited = &mut self.visited;
234 let mut components = smallvec![];
235 tcx.push_outlives_components(ty_max, &mut components);
239 .filter_map(|component| match component {
240 Component::Region(r) => {
241 if r.is_late_bound() {
244 Some(ty::PredicateKind::RegionOutlives(ty::Binder::dummy(
245 ty::OutlivesPredicate(r, r_min),
250 Component::Param(p) => {
251 let ty = tcx.mk_ty_param(p.index, p.name);
252 Some(ty::PredicateKind::TypeOutlives(ty::Binder::dummy(
253 ty::OutlivesPredicate(ty, r_min),
257 Component::UnresolvedInferenceVariable(_) => None,
259 Component::Projection(_) | Component::EscapingProjection(_) => {
260 // We can probably do more here. This
261 // corresponds to a case like `<T as
266 .map(|predicate_kind| predicate_kind.to_predicate(tcx))
267 .filter(|&predicate| visited.insert(predicate))
268 .map(|predicate| predicate_obligation(predicate, None)),
275 impl Iterator for Elaborator<'tcx> {
276 type Item = PredicateObligation<'tcx>;
278 fn size_hint(&self) -> (usize, Option<usize>) {
279 (self.stack.len(), None)
282 fn next(&mut self) -> Option<Self::Item> {
283 // Extract next item from top-most stack frame, if any.
284 if let Some(obligation) = self.stack.pop() {
285 self.elaborate(&obligation);
293 ///////////////////////////////////////////////////////////////////////////
294 // Supertrait iterator
295 ///////////////////////////////////////////////////////////////////////////
297 pub type Supertraits<'tcx> = FilterToTraits<Elaborator<'tcx>>;
299 pub fn supertraits<'tcx>(
301 trait_ref: ty::PolyTraitRef<'tcx>,
302 ) -> Supertraits<'tcx> {
303 elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
306 pub fn transitive_bounds<'tcx>(
308 bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
309 ) -> Supertraits<'tcx> {
310 elaborate_trait_refs(tcx, bounds).filter_to_traits()
313 ///////////////////////////////////////////////////////////////////////////
315 ///////////////////////////////////////////////////////////////////////////
317 /// A filter around an iterator of predicates that makes it yield up
318 /// just trait references.
319 pub struct FilterToTraits<I> {
323 impl<I> FilterToTraits<I> {
324 fn new(base: I) -> FilterToTraits<I> {
325 FilterToTraits { base_iterator: base }
329 impl<'tcx, I: Iterator<Item = PredicateObligation<'tcx>>> Iterator for FilterToTraits<I> {
330 type Item = ty::PolyTraitRef<'tcx>;
332 fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
333 while let Some(obligation) = self.base_iterator.next() {
334 if let ty::PredicateKind::Trait(data, _) = obligation.predicate.kind() {
335 return Some(data.to_poly_trait_ref());
341 fn size_hint(&self) -> (usize, Option<usize>) {
342 let (_, upper) = self.base_iterator.size_hint();