1 use smallvec
::smallvec
;
3 use crate::infer
::outlives
::components
::{push_outlives_components, Component}
;
4 use crate::traits
::{self, Obligation, ObligationCause, PredicateObligation}
;
5 use rustc_data_structures
::fx
::{FxHashSet, FxIndexSet}
;
6 use rustc_middle
::ty
::{self, ToPredicate, TyCtxt}
;
7 use rustc_span
::symbol
::Ident
;
10 pub fn anonymize_predicate
<'tcx
>(
12 pred
: ty
::Predicate
<'tcx
>,
13 ) -> ty
::Predicate
<'tcx
> {
14 let new
= tcx
.anonymize_bound_vars(pred
.kind());
15 tcx
.reuse_or_mk_predicate(pred
, new
)
18 pub struct PredicateSet
<'tcx
> {
20 set
: FxHashSet
<ty
::Predicate
<'tcx
>>,
23 impl<'tcx
> PredicateSet
<'tcx
> {
24 pub fn new(tcx
: TyCtxt
<'tcx
>) -> Self {
25 Self { tcx, set: Default::default() }
28 pub fn insert(&mut self, pred
: ty
::Predicate
<'tcx
>) -> bool
{
29 // We have to be careful here because we want
31 // for<'a> Foo<&'a i32>
35 // for<'b> Foo<&'b i32>
37 // to be considered equivalent. So normalize all late-bound
38 // regions before we throw things into the underlying set.
39 self.set
.insert(anonymize_predicate(self.tcx
, pred
))
43 impl<'tcx
> Extend
<ty
::Predicate
<'tcx
>> for PredicateSet
<'tcx
> {
44 fn extend
<I
: IntoIterator
<Item
= ty
::Predicate
<'tcx
>>>(&mut self, iter
: I
) {
50 fn extend_one(&mut self, pred
: ty
::Predicate
<'tcx
>) {
54 fn extend_reserve(&mut self, additional
: usize) {
55 Extend
::<ty
::Predicate
<'tcx
>>::extend_reserve(&mut self.set
, additional
);
59 ///////////////////////////////////////////////////////////////////////////
60 // `Elaboration` iterator
61 ///////////////////////////////////////////////////////////////////////////
63 /// "Elaboration" is the process of identifying all the predicates that
64 /// are implied by a source predicate. Currently, this basically means
65 /// walking the "supertraits" and other similar assumptions. For example,
66 /// if we know that `T: Ord`, the elaborator would deduce that `T: PartialOrd`
67 /// holds as well. Similarly, if we have `trait Foo: 'static`, and we know that
68 /// `T: Foo`, then we know that `T: 'static`.
69 pub struct Elaborator
<'tcx
> {
70 stack
: Vec
<PredicateObligation
<'tcx
>>,
71 visited
: PredicateSet
<'tcx
>,
74 pub fn elaborate_trait_ref
<'tcx
>(
76 trait_ref
: ty
::PolyTraitRef
<'tcx
>,
77 ) -> Elaborator
<'tcx
> {
78 elaborate_predicates(tcx
, std
::iter
::once(trait_ref
.without_const().to_predicate(tcx
)))
81 pub fn elaborate_trait_refs
<'tcx
>(
83 trait_refs
: impl Iterator
<Item
= ty
::PolyTraitRef
<'tcx
>>,
84 ) -> Elaborator
<'tcx
> {
85 let predicates
= trait_refs
.map(|trait_ref
| trait_ref
.without_const().to_predicate(tcx
));
86 elaborate_predicates(tcx
, predicates
)
89 pub fn elaborate_predicates
<'tcx
>(
91 predicates
: impl Iterator
<Item
= ty
::Predicate
<'tcx
>>,
92 ) -> Elaborator
<'tcx
> {
93 let obligations
= predicates
95 predicate_obligation(predicate
, ty
::ParamEnv
::empty(), ObligationCause
::dummy())
98 elaborate_obligations(tcx
, obligations
)
101 pub fn elaborate_predicates_with_span
<'tcx
>(
103 predicates
: impl Iterator
<Item
= (ty
::Predicate
<'tcx
>, Span
)>,
104 ) -> Elaborator
<'tcx
> {
105 let obligations
= predicates
106 .map(|(predicate
, span
)| {
107 predicate_obligation(
109 ty
::ParamEnv
::empty(),
110 ObligationCause
::dummy_with_span(span
),
114 elaborate_obligations(tcx
, obligations
)
117 pub fn elaborate_obligations
<'tcx
>(
119 mut obligations
: Vec
<PredicateObligation
<'tcx
>>,
120 ) -> Elaborator
<'tcx
> {
121 let mut visited
= PredicateSet
::new(tcx
);
122 obligations
.retain(|obligation
| visited
.insert(obligation
.predicate
));
123 Elaborator { stack: obligations, visited }
126 fn predicate_obligation
<'tcx
>(
127 predicate
: ty
::Predicate
<'tcx
>,
128 param_env
: ty
::ParamEnv
<'tcx
>,
129 cause
: ObligationCause
<'tcx
>,
130 ) -> PredicateObligation
<'tcx
> {
131 Obligation { cause, param_env, recursion_depth: 0, predicate }
134 impl<'tcx
> Elaborator
<'tcx
> {
135 pub fn filter_to_traits(self) -> FilterToTraits
<Self> {
136 FilterToTraits
::new(self)
139 fn elaborate(&mut self, obligation
: &PredicateObligation
<'tcx
>) {
140 let tcx
= self.visited
.tcx
;
142 let bound_predicate
= obligation
.predicate
.kind();
143 match bound_predicate
.skip_binder() {
144 ty
::PredicateKind
::Clause(ty
::Clause
::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(|&(mut pred
, span
)| {
149 // when parent predicate is non-const, elaborate it to non-const predicates.
150 if data
.constness
== ty
::BoundConstness
::NotConst
{
151 pred
= pred
.without_const(tcx
);
154 let cause
= obligation
.cause
.clone().derived_cause(
155 bound_predicate
.rebind(data
),
157 traits
::ImplDerivedObligation(Box
::new(
158 traits
::ImplDerivedObligationCause
{
160 impl_def_id
: data
.def_id(),
166 predicate_obligation(
167 pred
.subst_supertrait(tcx
, &bound_predicate
.rebind(data
.trait_ref
)),
168 obligation
.param_env
,
172 debug
!(?data
, ?obligations
, "super_predicates");
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
::Coerce(..) => {
196 // Currently, we do not "elaborate" predicates like `X -> Y`,
197 // though conceivably we might.
199 ty
::PredicateKind
::Clause(ty
::Clause
::Projection(..)) => {
200 // Nothing to elaborate in a projection predicate.
202 ty
::PredicateKind
::ClosureKind(..) => {
203 // Nothing to elaborate when waiting for a closure's kind to be inferred.
205 ty
::PredicateKind
::ConstEvaluatable(..) => {
206 // Currently, we do not elaborate const-evaluatable
209 ty
::PredicateKind
::ConstEquate(..) => {
210 // Currently, we do not elaborate const-equate
213 ty
::PredicateKind
::Clause(ty
::Clause
::RegionOutlives(..)) => {
214 // Nothing to elaborate from `'a: 'b`.
216 ty
::PredicateKind
::Clause(ty
::Clause
::TypeOutlives(ty
::OutlivesPredicate(
220 // We know that `T: 'a` for some type `T`. We can
221 // often elaborate this. For example, if we know that
222 // `[U]: 'a`, that implies that `U: 'a`. Similarly, if
223 // we know `&'a U: 'b`, then we know that `'a: 'b` and
226 // We can basically ignore bound regions here. So for
227 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
230 // Ignore `for<'a> T: 'a` -- we might in the future
231 // consider this as evidence that `T: 'static`, but
232 // I'm a bit wary of such constructions and so for now
233 // I want to be conservative. --nmatsakis
234 if r_min
.is_late_bound() {
238 let visited
= &mut self.visited
;
239 let mut components
= smallvec
![];
240 push_outlives_components(tcx
, ty_max
, &mut components
);
244 .filter_map(|component
| match component
{
245 Component
::Region(r
) => {
246 if r
.is_late_bound() {
249 Some(ty
::PredicateKind
::Clause(ty
::Clause
::RegionOutlives(
250 ty
::OutlivesPredicate(r
, r_min
),
255 Component
::Param(p
) => {
256 let ty
= tcx
.mk_ty_param(p
.index
, p
.name
);
257 Some(ty
::PredicateKind
::Clause(ty
::Clause
::TypeOutlives(
258 ty
::OutlivesPredicate(ty
, r_min
),
262 Component
::UnresolvedInferenceVariable(_
) => None
,
264 Component
::Alias(alias_ty
) => {
265 // We might end up here if we have `Foo<<Bar as Baz>::Assoc>: 'a`.
266 // With this, we can deduce that `<Bar as Baz>::Assoc: 'a`.
267 Some(ty
::PredicateKind
::Clause(ty
::Clause
::TypeOutlives(
268 ty
::OutlivesPredicate(alias_ty
.to_ty(tcx
), r_min
),
272 Component
::EscapingAlias(_
) => {
273 // We might be able to do more here, but we don't
274 // want to deal with escaping vars right now.
278 .map(|predicate_kind
| {
279 bound_predicate
.rebind(predicate_kind
).to_predicate(tcx
)
281 .filter(|&predicate
| visited
.insert(predicate
))
283 predicate_obligation(
285 obligation
.param_env
,
286 obligation
.cause
.clone(),
291 ty
::PredicateKind
::TypeWellFormedFromEnv(..) => {
292 // Nothing to elaborate
294 ty
::PredicateKind
::Ambiguous
=> {}
299 impl<'tcx
> Iterator
for Elaborator
<'tcx
> {
300 type Item
= PredicateObligation
<'tcx
>;
302 fn size_hint(&self) -> (usize, Option
<usize>) {
303 (self.stack
.len(), None
)
306 fn next(&mut self) -> Option
<Self::Item
> {
307 // Extract next item from top-most stack frame, if any.
308 if let Some(obligation
) = self.stack
.pop() {
309 self.elaborate(&obligation
);
317 ///////////////////////////////////////////////////////////////////////////
318 // Supertrait iterator
319 ///////////////////////////////////////////////////////////////////////////
321 pub type Supertraits
<'tcx
> = FilterToTraits
<Elaborator
<'tcx
>>;
323 pub fn supertraits
<'tcx
>(
325 trait_ref
: ty
::PolyTraitRef
<'tcx
>,
326 ) -> Supertraits
<'tcx
> {
327 elaborate_trait_ref(tcx
, trait_ref
).filter_to_traits()
330 pub fn transitive_bounds
<'tcx
>(
332 bounds
: impl Iterator
<Item
= ty
::PolyTraitRef
<'tcx
>>,
333 ) -> Supertraits
<'tcx
> {
334 elaborate_trait_refs(tcx
, bounds
).filter_to_traits()
337 /// A specialized variant of `elaborate_trait_refs` that only elaborates trait references that may
338 /// define the given associated type `assoc_name`. It uses the
339 /// `super_predicates_that_define_assoc_type` query to avoid enumerating super-predicates that
340 /// aren't related to `assoc_item`. This is used when resolving types like `Self::Item` or
341 /// `T::Item` and helps to avoid cycle errors (see e.g. #35237).
342 pub fn transitive_bounds_that_define_assoc_type
<'tcx
>(
344 bounds
: impl Iterator
<Item
= ty
::PolyTraitRef
<'tcx
>>,
346 ) -> impl Iterator
<Item
= ty
::PolyTraitRef
<'tcx
>> {
347 let mut stack
: Vec
<_
> = bounds
.collect();
348 let mut visited
= FxIndexSet
::default();
350 std
::iter
::from_fn(move || {
351 while let Some(trait_ref
) = stack
.pop() {
352 let anon_trait_ref
= tcx
.anonymize_bound_vars(trait_ref
);
353 if visited
.insert(anon_trait_ref
) {
354 let super_predicates
= tcx
.super_predicates_that_define_assoc_type((
358 for (super_predicate
, _
) in super_predicates
.predicates
{
359 let subst_predicate
= super_predicate
.subst_supertrait(tcx
, &trait_ref
);
360 if let Some(binder
) = subst_predicate
.to_opt_poly_trait_pred() {
361 stack
.push(binder
.map_bound(|t
| t
.trait_ref
));
365 return Some(trait_ref
);
373 ///////////////////////////////////////////////////////////////////////////
375 ///////////////////////////////////////////////////////////////////////////
377 /// A filter around an iterator of predicates that makes it yield up
378 /// just trait references.
379 pub struct FilterToTraits
<I
> {
383 impl<I
> FilterToTraits
<I
> {
384 fn new(base
: I
) -> FilterToTraits
<I
> {
385 FilterToTraits { base_iterator: base }
389 impl<'tcx
, I
: Iterator
<Item
= PredicateObligation
<'tcx
>>> Iterator
for FilterToTraits
<I
> {
390 type Item
= ty
::PolyTraitRef
<'tcx
>;
392 fn next(&mut self) -> Option
<ty
::PolyTraitRef
<'tcx
>> {
393 while let Some(obligation
) = self.base_iterator
.next() {
394 if let Some(data
) = obligation
.predicate
.to_opt_poly_trait_pred() {
395 return Some(data
.map_bound(|t
| t
.trait_ref
));
401 fn size_hint(&self) -> (usize, Option
<usize>) {
402 let (_
, upper
) = self.base_iterator
.size_hint();