1 use smallvec::smallvec;
3 use crate::infer::outlives::components::{push_outlives_components, Component};
4 use crate::traits::{Obligation, ObligationCause, PredicateObligation};
5 use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
6 use rustc_middle::ty::{self, ToPredicate, TyCtxt, WithConstness};
7 use rustc_span::symbol::Ident;
9 pub fn anonymize_predicate<'tcx>(
11 pred: ty::Predicate<'tcx>,
12 ) -> ty::Predicate<'tcx> {
13 let new = tcx.anonymize_late_bound_regions(pred.kind());
14 tcx.reuse_or_mk_predicate(pred, new)
17 pub struct PredicateSet<'tcx> {
19 set: FxHashSet<ty::Predicate<'tcx>>,
22 impl PredicateSet<'tcx> {
23 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
24 Self { tcx, set: Default::default() }
27 pub fn insert(&mut self, pred: ty::Predicate<'tcx>) -> bool {
28 // We have to be careful here because we want
30 // for<'a> Foo<&'a i32>
34 // for<'b> Foo<&'b i32>
36 // to be considered equivalent. So normalize all late-bound
37 // regions before we throw things into the underlying set.
38 self.set.insert(anonymize_predicate(self.tcx, pred))
42 impl Extend<ty::Predicate<'tcx>> for PredicateSet<'tcx> {
43 fn extend<I: IntoIterator<Item = ty::Predicate<'tcx>>>(&mut self, iter: I) {
49 fn extend_one(&mut self, pred: ty::Predicate<'tcx>) {
53 fn extend_reserve(&mut self, additional: usize) {
54 Extend::<ty::Predicate<'tcx>>::extend_reserve(&mut self.set, additional);
58 ///////////////////////////////////////////////////////////////////////////
59 // `Elaboration` iterator
60 ///////////////////////////////////////////////////////////////////////////
62 /// "Elaboration" is the process of identifying all the predicates that
63 /// are implied by a source predicate. Currently, this basically means
64 /// walking the "supertraits" and other similar assumptions. For example,
65 /// if we know that `T: Ord`, the elaborator would deduce that `T: PartialOrd`
66 /// holds as well. Similarly, if we have `trait Foo: 'static`, and we know that
67 /// `T: Foo`, then we know that `T: 'static`.
68 pub struct Elaborator<'tcx> {
69 stack: Vec<PredicateObligation<'tcx>>,
70 visited: PredicateSet<'tcx>,
73 pub fn elaborate_trait_ref<'tcx>(
75 trait_ref: ty::PolyTraitRef<'tcx>,
76 ) -> Elaborator<'tcx> {
77 elaborate_predicates(tcx, std::iter::once(trait_ref.without_const().to_predicate(tcx)))
80 pub fn elaborate_trait_refs<'tcx>(
82 trait_refs: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
83 ) -> Elaborator<'tcx> {
84 let predicates = trait_refs.map(|trait_ref| trait_ref.without_const().to_predicate(tcx));
85 elaborate_predicates(tcx, predicates)
88 pub fn elaborate_predicates<'tcx>(
90 predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
91 ) -> Elaborator<'tcx> {
92 let obligations = predicates
94 predicate_obligation(predicate, ty::ParamEnv::empty(), ObligationCause::dummy())
97 elaborate_obligations(tcx, obligations)
100 pub fn elaborate_obligations<'tcx>(
102 mut obligations: Vec<PredicateObligation<'tcx>>,
103 ) -> Elaborator<'tcx> {
104 let mut visited = PredicateSet::new(tcx);
105 obligations.retain(|obligation| visited.insert(obligation.predicate));
106 Elaborator { stack: obligations, visited }
109 fn predicate_obligation<'tcx>(
110 predicate: ty::Predicate<'tcx>,
111 param_env: ty::ParamEnv<'tcx>,
112 cause: ObligationCause<'tcx>,
113 ) -> PredicateObligation<'tcx> {
114 Obligation { cause, param_env, recursion_depth: 0, predicate }
117 impl Elaborator<'tcx> {
118 pub fn filter_to_traits(self) -> FilterToTraits<Self> {
119 FilterToTraits::new(self)
122 fn elaborate(&mut self, obligation: &PredicateObligation<'tcx>) {
123 let tcx = self.visited.tcx;
125 let bound_predicate = obligation.predicate.kind();
126 match bound_predicate.skip_binder() {
127 ty::PredicateKind::Trait(data) => {
128 // Get predicates declared on the trait.
129 let predicates = tcx.super_predicates_of(data.def_id());
131 let obligations = predicates.predicates.iter().map(|&(pred, _)| {
132 predicate_obligation(
133 pred.subst_supertrait(tcx, &bound_predicate.rebind(data.trait_ref)),
134 obligation.param_env,
135 obligation.cause.clone(),
138 debug!("super_predicates: data={:?}", data);
140 // Only keep those bounds that we haven't already seen.
141 // This is necessary to prevent infinite recursion in some
142 // cases. One common case is when people define
143 // `trait Sized: Sized { }` rather than `trait Sized { }`.
144 let visited = &mut self.visited;
145 let obligations = obligations.filter(|o| visited.insert(o.predicate));
147 self.stack.extend(obligations);
149 ty::PredicateKind::WellFormed(..) => {
150 // Currently, we do not elaborate WF predicates,
151 // although we easily could.
153 ty::PredicateKind::ObjectSafe(..) => {
154 // Currently, we do not elaborate object-safe
157 ty::PredicateKind::Subtype(..) => {
158 // Currently, we do not "elaborate" predicates like `X <: Y`,
159 // though conceivably we might.
161 ty::PredicateKind::Coerce(..) => {
162 // Currently, we do not "elaborate" predicates like `X -> Y`,
163 // though conceivably we might.
165 ty::PredicateKind::Projection(..) => {
166 // Nothing to elaborate in a projection predicate.
168 ty::PredicateKind::ClosureKind(..) => {
169 // Nothing to elaborate when waiting for a closure's kind to be inferred.
171 ty::PredicateKind::ConstEvaluatable(..) => {
172 // Currently, we do not elaborate const-evaluatable
175 ty::PredicateKind::ConstEquate(..) => {
176 // Currently, we do not elaborate const-equate
179 ty::PredicateKind::RegionOutlives(..) => {
180 // Nothing to elaborate from `'a: 'b`.
182 ty::PredicateKind::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 push_outlives_components(tcx, ty_max, &mut components);
207 .filter_map(|component| match component {
208 Component::Region(r) => {
209 if r.is_late_bound() {
212 Some(ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(
218 Component::Param(p) => {
219 let ty = tcx.mk_ty_param(p.index, p.name);
220 Some(ty::PredicateKind::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(ty::Binder::dummy)
235 .map(|predicate_kind| predicate_kind.to_predicate(tcx))
236 .filter(|&predicate| visited.insert(predicate))
238 predicate_obligation(
240 obligation.param_env,
241 obligation.cause.clone(),
246 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
247 // Nothing to elaborate
253 impl Iterator for Elaborator<'tcx> {
254 type Item = PredicateObligation<'tcx>;
256 fn size_hint(&self) -> (usize, Option<usize>) {
257 (self.stack.len(), None)
260 fn next(&mut self) -> Option<Self::Item> {
261 // Extract next item from top-most stack frame, if any.
262 if let Some(obligation) = self.stack.pop() {
263 self.elaborate(&obligation);
271 ///////////////////////////////////////////////////////////////////////////
272 // Supertrait iterator
273 ///////////////////////////////////////////////////////////////////////////
275 pub type Supertraits<'tcx> = FilterToTraits<Elaborator<'tcx>>;
277 pub fn supertraits<'tcx>(
279 trait_ref: ty::PolyTraitRef<'tcx>,
280 ) -> Supertraits<'tcx> {
281 elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
284 pub fn transitive_bounds<'tcx>(
286 bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
287 ) -> Supertraits<'tcx> {
288 elaborate_trait_refs(tcx, bounds).filter_to_traits()
291 /// A specialized variant of `elaborate_trait_refs` that only elaborates trait references that may
292 /// define the given associated type `assoc_name`. It uses the
293 /// `super_predicates_that_define_assoc_type` query to avoid enumerating super-predicates that
294 /// aren't related to `assoc_item`. This is used when resolving types like `Self::Item` or
295 /// `T::Item` and helps to avoid cycle errors (see e.g. #35237).
296 pub fn transitive_bounds_that_define_assoc_type<'tcx>(
298 bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
300 ) -> impl Iterator<Item = ty::PolyTraitRef<'tcx>> {
301 let mut stack: Vec<_> = bounds.collect();
302 let mut visited = FxIndexSet::default();
304 std::iter::from_fn(move || {
305 while let Some(trait_ref) = stack.pop() {
306 let anon_trait_ref = tcx.anonymize_late_bound_regions(trait_ref);
307 if visited.insert(anon_trait_ref) {
308 let super_predicates = tcx.super_predicates_that_define_assoc_type((
312 for (super_predicate, _) in super_predicates.predicates {
313 let subst_predicate = super_predicate.subst_supertrait(tcx, &trait_ref);
314 if let Some(binder) = subst_predicate.to_opt_poly_trait_ref() {
315 stack.push(binder.value);
319 return Some(trait_ref);
327 ///////////////////////////////////////////////////////////////////////////
329 ///////////////////////////////////////////////////////////////////////////
331 /// A filter around an iterator of predicates that makes it yield up
332 /// just trait references.
333 pub struct FilterToTraits<I> {
337 impl<I> FilterToTraits<I> {
338 fn new(base: I) -> FilterToTraits<I> {
339 FilterToTraits { base_iterator: base }
343 impl<'tcx, I: Iterator<Item = PredicateObligation<'tcx>>> Iterator for FilterToTraits<I> {
344 type Item = ty::PolyTraitRef<'tcx>;
346 fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
347 while let Some(obligation) = self.base_iterator.next() {
348 if let Some(data) = obligation.predicate.to_opt_poly_trait_ref() {
349 return Some(data.value);
355 fn size_hint(&self) -> (usize, Option<usize>) {
356 let (_, upper) = self.base_iterator.size_hint();