Skip to main content

rustc_middle/ty/
predicate.rs

1use std::cmp::Ordering;
2
3use rustc_data_structures::intern::Interned;
4use rustc_hir::def_id::DefId;
5use rustc_macros::{StableHash, extension};
6use rustc_span::bug;
7use rustc_type_ir as ir;
8
9use crate::ty::{self, EarlyBinder, Ty, TyCtxt, TypeFlags, Upcast, UpcastFrom, WithCachedTypeInfo};
10
11pub type TraitRef<'tcx> = ir::TraitRef<TyCtxt<'tcx>>;
12pub type AliasTerm<'tcx> = ir::AliasTerm<TyCtxt<'tcx>>;
13pub type AliasTermKind<'tcx> = ir::AliasTermKind<TyCtxt<'tcx>>;
14pub type ProjectionClause<'tcx> = ir::ProjectionClause<TyCtxt<'tcx>>;
15pub type ExistentialPredicate<'tcx> = ir::ExistentialPredicate<TyCtxt<'tcx>>;
16pub type ExistentialTraitRef<'tcx> = ir::ExistentialTraitRef<TyCtxt<'tcx>>;
17pub type ExistentialProjection<'tcx> = ir::ExistentialProjection<TyCtxt<'tcx>>;
18pub type TraitClause<'tcx> = ir::TraitClause<TyCtxt<'tcx>>;
19pub type HostEffectClause<'tcx> = ir::HostEffectClause<TyCtxt<'tcx>>;
20pub type ClauseKind<'tcx> = ir::ClauseKind<TyCtxt<'tcx>>;
21pub type PredicateKind<'tcx> = ir::PredicateKind<TyCtxt<'tcx>>;
22pub type NormalizesTo<'tcx> = ir::NormalizesTo<TyCtxt<'tcx>>;
23pub type CoercePredicate<'tcx> = ir::CoercePredicate<TyCtxt<'tcx>>;
24pub type SubtypePredicate<'tcx> = ir::SubtypePredicate<TyCtxt<'tcx>>;
25pub type OutlivesClause<'tcx, T> = ir::OutlivesClause<TyCtxt<'tcx>, T>;
26pub type RegionOutlivesClause<'tcx> = OutlivesClause<'tcx, ty::Region<'tcx>>;
27pub type TypeOutlivesClause<'tcx> = OutlivesClause<'tcx, Ty<'tcx>>;
28pub type ArgOutlivesClause<'tcx> = OutlivesClause<'tcx, ty::GenericArg<'tcx>>;
29pub type RegionEqPredicate<'tcx> = ir::RegionEqPredicate<TyCtxt<'tcx>>;
30pub type RegionConstraint<'tcx> = ir::RegionConstraint<TyCtxt<'tcx>>;
31pub type PolyTraitClause<'tcx> = ty::Binder<'tcx, TraitClause<'tcx>>;
32pub type PolyRegionOutlivesClause<'tcx> = ty::Binder<'tcx, RegionOutlivesClause<'tcx>>;
33pub type PolyTypeOutlivesClause<'tcx> = ty::Binder<'tcx, TypeOutlivesClause<'tcx>>;
34pub type PolySubtypePredicate<'tcx> = ty::Binder<'tcx, SubtypePredicate<'tcx>>;
35pub type PolyCoercePredicate<'tcx> = ty::Binder<'tcx, CoercePredicate<'tcx>>;
36pub type PolyProjectionClause<'tcx> = ty::Binder<'tcx, ProjectionClause<'tcx>>;
37
38/// A statement that can be proven by a trait solver. This includes things that may
39/// show up in where clauses, such as trait predicates and projection predicates,
40/// and also things that are emitted as part of type checking such as `DynCompatible`
41/// predicate which is emitted when a type is coerced to a trait object.
42///
43/// Use this rather than `PredicateKind`, whenever possible.
44#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
    ::core::clone::TrivialClone for Predicate<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for Predicate<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _:
                ::core::clone::AssertParamIsClone<Interned<'tcx,
                WithCachedTypeInfo<ty::Binder<'tcx, PredicateKind<'tcx>>>>>;
        *self
    }
}Clone, #[automatically_derived]impl<'tcx> ::core::marker::Copy for Predicate<'tcx> {
}Copy, #[automatically_derived]impl<'tcx> ::core::marker::StructuralPartialEq for
    Predicate<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::cmp::PartialEq for Predicate<'tcx>
    {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]impl<'tcx> ::core::cmp::Eq for Predicate<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _:
                ::core::cmp::AssertParamIsEq<Interned<'tcx,
                WithCachedTypeInfo<ty::Binder<'tcx, PredicateKind<'tcx>>>>>;
    }
}Eq, #[automatically_derived]impl<'tcx> ::core::hash::Hash for Predicate<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            Predicate<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Predicate(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
45#[cfg_attr(bootstrap, rustc_pass_by_value)]
46#[cfg_attr(not(bootstrap), lint::pass_by_value)]
47pub struct Predicate<'tcx>(
48    pub(super) Interned<'tcx, WithCachedTypeInfo<ty::Binder<'tcx, PredicateKind<'tcx>>>>,
49);
50
51impl<'tcx> rustc_type_ir::inherent::Predicate<TyCtxt<'tcx>> for Predicate<'tcx> {
52    fn as_clause(self) -> Option<ty::Clause<'tcx>> {
53        self.as_clause()
54    }
55}
56
57impl<'tcx> rustc_type_ir::inherent::IntoKind for Predicate<'tcx> {
58    type Kind = ty::Binder<'tcx, ty::PredicateKind<'tcx>>;
59
60    fn kind(self) -> Self::Kind {
61        self.kind()
62    }
63}
64
65impl<'tcx> rustc_type_ir::Flags for Predicate<'tcx> {
66    fn flags(&self) -> TypeFlags {
67        self.0.flags
68    }
69
70    fn outer_exclusive_binder(&self) -> ty::DebruijnIndex {
71        self.0.outer_exclusive_binder
72    }
73}
74
75impl<'tcx> Predicate<'tcx> {
76    /// Gets the inner `ty::Binder<'tcx, PredicateKind<'tcx>>`.
77    #[inline]
78    pub fn kind(self) -> ty::Binder<'tcx, PredicateKind<'tcx>> {
79        self.0.internee
80    }
81
82    /// Flips the polarity of a Predicate.
83    ///
84    /// Given `T: Trait` predicate it returns `T: !Trait` and given `T: !Trait` returns `T: Trait`.
85    pub fn flip_polarity(self, tcx: TyCtxt<'tcx>) -> Option<Predicate<'tcx>> {
86        let kind = self
87            .kind()
88            .map_bound(|kind| match kind {
89                PredicateKind::Clause(ClauseKind::Trait(TraitClause { trait_ref, polarity })) => {
90                    Some(PredicateKind::Clause(ClauseKind::Trait(TraitClause {
91                        trait_ref,
92                        polarity: polarity.flip(),
93                    })))
94                }
95
96                _ => None,
97            })
98            .transpose()?;
99
100        Some(tcx.mk_predicate(kind))
101    }
102
103    /// Whether this projection can be soundly normalized.
104    ///
105    /// Wf predicates must not be normalized, as normalization
106    /// can remove required bounds which would cause us to
107    /// unsoundly accept some programs. See #91068.
108    #[inline]
109    pub fn allow_normalization(self) -> bool {
110        rustc_type_ir::inherent::Predicate::allow_normalization(self)
111    }
112}
113
114impl<'tcx> rustc_errors::IntoDiagArg for Predicate<'tcx> {
115    fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
116        ty::tls::with(|tcx| {
117            let pred = tcx.short_string(tcx.lift(self), path);
118            rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(pred))
119        })
120    }
121}
122
123impl<'tcx> rustc_errors::IntoDiagArg for Clause<'tcx> {
124    fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
125        ty::tls::with(|tcx| {
126            let clause = tcx.short_string(tcx.lift(self), path);
127            rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(clause))
128        })
129    }
130}
131
132/// A subset of predicates which can be assumed by the trait solver. They show up in
133/// an item's where clauses, hence the name `Clause`, and may either be user-written
134/// (such as traits) or may be inserted during lowering.
135#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
    ::core::clone::TrivialClone for Clause<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for Clause<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _:
                ::core::clone::AssertParamIsClone<Interned<'tcx,
                WithCachedTypeInfo<ty::Binder<'tcx, PredicateKind<'tcx>>>>>;
        *self
    }
}Clone, #[automatically_derived]impl<'tcx> ::core::marker::Copy for Clause<'tcx> { }Copy, #[automatically_derived]impl<'tcx> ::core::marker::StructuralPartialEq for
    Clause<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::cmp::PartialEq for Clause<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]impl<'tcx> ::core::cmp::Eq for Clause<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _:
                ::core::cmp::AssertParamIsEq<Interned<'tcx,
                WithCachedTypeInfo<ty::Binder<'tcx, PredicateKind<'tcx>>>>>;
    }
}Eq, #[automatically_derived]impl<'tcx> ::core::hash::Hash for Clause<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            Clause<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Clause(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
136#[cfg_attr(bootstrap, rustc_pass_by_value)]
137#[cfg_attr(not(bootstrap), lint::pass_by_value)]
138pub struct Clause<'tcx>(
139    pub(super) Interned<'tcx, WithCachedTypeInfo<ty::Binder<'tcx, PredicateKind<'tcx>>>>,
140);
141
142impl<'tcx> rustc_type_ir::inherent::Clause<TyCtxt<'tcx>> for Clause<'tcx> {
143    fn as_predicate(self) -> Predicate<'tcx> {
144        self.as_predicate()
145    }
146
147    fn instantiate_supertrait(self, tcx: TyCtxt<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>) -> Self {
148        self.instantiate_supertrait(tcx, trait_ref)
149    }
150}
151
152impl<'tcx> rustc_type_ir::inherent::IntoKind for Clause<'tcx> {
153    type Kind = ty::Binder<'tcx, ClauseKind<'tcx>>;
154
155    fn kind(self) -> Self::Kind {
156        self.kind()
157    }
158}
159
160impl<'tcx> rustc_type_ir::Flags for Clause<'tcx> {
161    fn flags(&self) -> TypeFlags {
162        self.0.flags
163    }
164
165    fn outer_exclusive_binder(&self) -> ty::DebruijnIndex {
166        self.0.outer_exclusive_binder
167    }
168}
169
170impl<'tcx> Clause<'tcx> {
171    pub fn as_predicate(self) -> Predicate<'tcx> {
172        Predicate(self.0)
173    }
174
175    pub fn kind(self) -> ty::Binder<'tcx, ClauseKind<'tcx>> {
176        // Outline the unreachable! call to make the happy path faster.
177        // see: https://github.com/rust-lang/rust/pull/163657#issuecomment-5956974964
178        #[cold]
179        #[inline(never)]
180        fn unreachable_inner() -> ! {
181            ::core::panicking::unreachable_default_msg()unreachable!()
182        }
183
184        self.0.internee.map_bound_no_validate_bound_vars(|kind| match kind {
185            PredicateKind::Clause(clause) => clause,
186            _ => unreachable_inner(),
187        })
188    }
189
190    pub fn as_trait_clause(self) -> Option<ty::Binder<'tcx, TraitClause<'tcx>>> {
191        let clause = self.kind();
192        if let ty::ClauseKind::Trait(trait_clause) = clause.skip_binder() {
193            Some(clause.rebind(trait_clause))
194        } else {
195            None
196        }
197    }
198
199    pub fn as_projection_clause(self) -> Option<ty::Binder<'tcx, ProjectionClause<'tcx>>> {
200        let clause = self.kind();
201        if let ty::ClauseKind::Projection(projection_clause) = clause.skip_binder() {
202            Some(clause.rebind(projection_clause))
203        } else {
204            None
205        }
206    }
207
208    pub fn as_type_outlives_clause(self) -> Option<ty::Binder<'tcx, TypeOutlivesClause<'tcx>>> {
209        let clause = self.kind();
210        if let ty::ClauseKind::TypeOutlives(o) = clause.skip_binder() {
211            Some(clause.rebind(o))
212        } else {
213            None
214        }
215    }
216
217    pub fn as_region_outlives_clause(self) -> Option<ty::Binder<'tcx, RegionOutlivesClause<'tcx>>> {
218        let clause = self.kind();
219        if let ty::ClauseKind::RegionOutlives(o) = clause.skip_binder() {
220            Some(clause.rebind(o))
221        } else {
222            None
223        }
224    }
225}
226
227impl<'tcx> rustc_type_ir::inherent::Clauses<TyCtxt<'tcx>> for ty::Clauses<'tcx> {}
228
229pub trait ExistentialPredicateStableCmpExt<'tcx> {
    #[doc =
    " Compares via an ordering that will not change if modules are reordered or other changes are"]
    #[doc =
    " made to the tree. In particular, this ordering is preserved across incremental compilations."]
    fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self)
    -> Ordering;
}
impl<'tcx> ExistentialPredicateStableCmpExt<'tcx> for
    ExistentialPredicate<'tcx> {
    #[doc =
    " Compares via an ordering that will not change if modules are reordered or other changes are"]
    #[doc =
    " made to the tree. In particular, this ordering is preserved across incremental compilations."]
    fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering {
        match (*self, *other) {
            (ExistentialPredicate::Trait(_), ExistentialPredicate::Trait(_))
                => Ordering::Equal,
            (ExistentialPredicate::Projection(ref a),
                ExistentialPredicate::Projection(ref b)) => {
                tcx.def_path_hash(a.def_id).cmp(&tcx.def_path_hash(b.def_id))
            }
            (ExistentialPredicate::AutoTrait(ref a),
                ExistentialPredicate::AutoTrait(ref b)) => {
                tcx.def_path_hash(*a).cmp(&tcx.def_path_hash(*b))
            }
            (ExistentialPredicate::Trait(_), _) => Ordering::Less,
            (ExistentialPredicate::Projection(_),
                ExistentialPredicate::Trait(_)) => {
                Ordering::Greater
            }
            (ExistentialPredicate::Projection(_), _) => Ordering::Less,
            (ExistentialPredicate::AutoTrait(_), _) => Ordering::Greater,
        }
    }
}#[extension(pub trait ExistentialPredicateStableCmpExt<'tcx>)]
230impl<'tcx> ExistentialPredicate<'tcx> {
231    /// Compares via an ordering that will not change if modules are reordered or other changes are
232    /// made to the tree. In particular, this ordering is preserved across incremental compilations.
233    fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering {
234        match (*self, *other) {
235            (ExistentialPredicate::Trait(_), ExistentialPredicate::Trait(_)) => Ordering::Equal,
236            (ExistentialPredicate::Projection(ref a), ExistentialPredicate::Projection(ref b)) => {
237                tcx.def_path_hash(a.def_id).cmp(&tcx.def_path_hash(b.def_id))
238            }
239            (ExistentialPredicate::AutoTrait(ref a), ExistentialPredicate::AutoTrait(ref b)) => {
240                tcx.def_path_hash(*a).cmp(&tcx.def_path_hash(*b))
241            }
242            (ExistentialPredicate::Trait(_), _) => Ordering::Less,
243            (ExistentialPredicate::Projection(_), ExistentialPredicate::Trait(_)) => {
244                Ordering::Greater
245            }
246            (ExistentialPredicate::Projection(_), _) => Ordering::Less,
247            (ExistentialPredicate::AutoTrait(_), _) => Ordering::Greater,
248        }
249    }
250}
251
252pub type PolyExistentialPredicate<'tcx> = ty::Binder<'tcx, ExistentialPredicate<'tcx>>;
253
254impl<'tcx> rustc_type_ir::inherent::BoundExistentialPredicates<TyCtxt<'tcx>>
255    for &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>
256{
257    fn principal_def_id(self) -> Option<DefId> {
258        self.principal_def_id()
259    }
260
261    fn principal(self) -> Option<ty::PolyExistentialTraitRef<'tcx>> {
262        self.principal()
263    }
264
265    fn auto_traits(self) -> impl IntoIterator<Item = DefId> {
266        self.auto_traits()
267    }
268
269    fn projection_bounds(
270        self,
271    ) -> impl IntoIterator<Item = ty::Binder<'tcx, ExistentialProjection<'tcx>>> {
272        self.projection_bounds()
273    }
274}
275
276impl<'tcx> ty::List<ty::PolyExistentialPredicate<'tcx>> {
277    /// Returns the "principal `DefId`" of this set of existential predicates.
278    ///
279    /// A Rust trait object type consists (in addition to a lifetime bound)
280    /// of a set of trait bounds, which are separated into any number
281    /// of auto-trait bounds, and at most one non-auto-trait bound. The
282    /// non-auto-trait bound is called the "principal" of the trait
283    /// object.
284    ///
285    /// Only the principal can have methods or type parameters (because
286    /// auto traits can have neither of them). This is important, because
287    /// it means the auto traits can be treated as an unordered set (methods
288    /// would force an order for the vtable, while relating traits with
289    /// type parameters without knowing the order to relate them in is
290    /// a rather non-trivial task).
291    ///
292    /// For example, in the trait object `dyn std::fmt::Debug + Sync`, the
293    /// principal bound is `Some(std::fmt::Debug)`, while the auto-trait bounds
294    /// are the set `{Sync}`.
295    ///
296    /// It is also possible to have a "trivial" trait object that
297    /// consists only of auto traits, with no principal - for example,
298    /// `dyn Send + Sync`. In that case, the set of auto-trait bounds
299    /// is `{Send, Sync}`, while there is no principal. These trait objects
300    /// have a "trivial" vtable consisting of just the size, alignment,
301    /// and destructor.
302    pub fn principal(&self) -> Option<ty::Binder<'tcx, ExistentialTraitRef<'tcx>>> {
303        self[0]
304            .map_bound(|this| match this {
305                ExistentialPredicate::Trait(tr) => Some(tr),
306                _ => None,
307            })
308            .transpose()
309    }
310
311    pub fn principal_def_id(&self) -> Option<DefId> {
312        self.principal().map(|trait_ref| trait_ref.skip_binder().def_id)
313    }
314
315    #[inline]
316    pub fn projection_bounds(
317        &self,
318    ) -> impl Iterator<Item = ty::Binder<'tcx, ExistentialProjection<'tcx>>> {
319        self.iter().filter_map(|predicate| {
320            predicate
321                .map_bound(|pred| match pred {
322                    ExistentialPredicate::Projection(projection) => Some(projection),
323                    _ => None,
324                })
325                .transpose()
326        })
327    }
328
329    #[inline]
330    pub fn auto_traits(&self) -> impl Iterator<Item = DefId> {
331        self.iter().filter_map(|predicate| match predicate.skip_binder() {
332            ExistentialPredicate::AutoTrait(did) => Some(did),
333            _ => None,
334        })
335    }
336
337    pub fn without_auto_traits(&self) -> impl Iterator<Item = ty::PolyExistentialPredicate<'tcx>> {
338        self.iter().filter(|predicate| {
339            !#[allow(non_exhaustive_omitted_patterns)] match predicate.as_ref().skip_binder()
    {
    ExistentialPredicate::AutoTrait(_) => true,
    _ => false,
}matches!(predicate.as_ref().skip_binder(), ExistentialPredicate::AutoTrait(_))
340        })
341    }
342}
343
344pub type PolyTraitRef<'tcx> = ty::Binder<'tcx, TraitRef<'tcx>>;
345pub type PolyExistentialTraitRef<'tcx> = ty::Binder<'tcx, ExistentialTraitRef<'tcx>>;
346pub type PolyExistentialProjection<'tcx> = ty::Binder<'tcx, ExistentialProjection<'tcx>>;
347
348impl<'tcx> Clause<'tcx> {
349    /// Performs a instantiation suitable for going from a
350    /// poly-trait-ref to supertraits that must hold if that
351    /// poly-trait-ref holds. This is slightly different from a normal
352    /// instantiation in terms of what happens with bound regions. See
353    /// lengthy comment below for details.
354    pub fn instantiate_supertrait(
355        self,
356        tcx: TyCtxt<'tcx>,
357        trait_ref: ty::PolyTraitRef<'tcx>,
358    ) -> Clause<'tcx> {
359        // The interaction between HRTB and supertraits is not entirely
360        // obvious. Let me walk you (and myself) through an example.
361        //
362        // Let's start with an easy case. Consider two traits:
363        //
364        //     trait Foo<'a>: Bar<'a,'a> { }
365        //     trait Bar<'b,'c> { }
366        //
367        // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
368        // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
369        // knew that `Foo<'x>` (for any 'x) then we also know that
370        // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
371        // normal instantiation.
372        //
373        // In terms of why this is sound, the idea is that whenever there
374        // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
375        // holds. So if there is an impl of `T:Foo<'a>` that applies to
376        // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
377        // `'a`.
378        //
379        // Another example to be careful of is this:
380        //
381        //     trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
382        //     trait Bar1<'b,'c> { }
383        //
384        // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
385        // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
386        // reason is similar to the previous example: any impl of
387        // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`. So
388        // basically we would want to collapse the bound lifetimes from
389        // the input (`trait_ref`) and the supertraits.
390        //
391        // To achieve this in practice is fairly straightforward. Let's
392        // consider the more complicated scenario:
393        //
394        // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
395        //   has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
396        //   where both `'x` and `'b` would have a DB index of 1.
397        //   The instantiation from the input trait-ref is therefore going to be
398        //   `'a => 'x` (where `'x` has a DB index of 1).
399        // - The supertrait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
400        //   early-bound parameter and `'b` is a late-bound parameter with a
401        //   DB index of 1.
402        // - If we replace `'a` with `'x` from the input, it too will have
403        //   a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
404        //   just as we wanted.
405        //
406        // There is only one catch. If we just apply the instantiation `'a
407        // => 'x` to `for<'b> Bar1<'a,'b>`, the instantiation code will
408        // adjust the DB index because we instantiating into a binder (it
409        // tries to be so smart...) resulting in `for<'x> for<'b>
410        // Bar1<'x,'b>` (we have no syntax for this, so use your
411        // imagination). Basically the 'x will have DB index of 2 and 'b
412        // will have DB index of 1. Not quite what we want. So we apply
413        // the instantiation to the *contents* of the trait reference,
414        // rather than the trait reference itself (put another way, the
415        // instantiation code expects equal binding levels in the values
416        // from the instantiation and the value being instantiated into, and
417        // this trick achieves that).
418
419        // Working through the second example:
420        // trait_ref: for<'x> T: Foo1<'^0.0>; args: [T, '^0.0]
421        // predicate: for<'b> Self: Bar1<'a, '^0.0>; args: [Self, 'a, '^0.0]
422        // We want to end up with:
423        //     for<'x, 'b> T: Bar1<'^0.0, '^0.1>
424        // To do this:
425        // 1) We must shift all bound vars in predicate by the length
426        //    of trait ref's bound vars. So, we would end up with predicate like
427        //    Self: Bar1<'a, '^0.1>
428        // 2) We can then apply the trait args to this, ending up with
429        //    T: Bar1<'^0.0, '^0.1>
430        // 3) Finally, to create the final bound vars, we concatenate the bound
431        //    vars of the trait ref with those of the predicate:
432        //    ['x, 'b]
433        let bound_pred = self.kind();
434        let pred_bound_vars = bound_pred.bound_vars();
435        let trait_bound_vars = trait_ref.bound_vars();
436        // 1) Self: Bar1<'a, '^0.0> -> Self: Bar1<'a, '^0.1>
437        let shifted_pred =
438            tcx.shift_bound_var_indices(trait_bound_vars.len(), bound_pred.skip_binder());
439        // 2) Self: Bar1<'a, '^0.1> -> T: Bar1<'^0.0, '^0.1>
440        let new = EarlyBinder::bind(tcx, shifted_pred)
441            .instantiate(tcx, trait_ref.skip_binder().args)
442            .skip_norm_wip();
443        // 3) ['x] + ['b] -> ['x, 'b]
444        let bound_vars =
445            tcx.mk_bound_variable_kinds_from_iter(trait_bound_vars.iter().chain(pred_bound_vars));
446
447        // FIXME: Is it really perf sensitive to use reuse_or_mk_predicate here?
448        tcx.reuse_or_mk_predicate(
449            self.as_predicate(),
450            ty::Binder::bind_with_vars(PredicateKind::Clause(new), bound_vars),
451        )
452        .expect_clause()
453    }
454}
455
456impl<'tcx> UpcastFrom<TyCtxt<'tcx>, PredicateKind<'tcx>> for Predicate<'tcx> {
457    fn upcast_from(from: PredicateKind<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
458        ty::Binder::dummy(from).upcast(tcx)
459    }
460}
461
462impl<'tcx> UpcastFrom<TyCtxt<'tcx>, ty::Binder<'tcx, PredicateKind<'tcx>>> for Predicate<'tcx> {
463    fn upcast_from(from: ty::Binder<'tcx, PredicateKind<'tcx>>, tcx: TyCtxt<'tcx>) -> Self {
464        tcx.mk_predicate(from)
465    }
466}
467
468impl<'tcx> UpcastFrom<TyCtxt<'tcx>, ClauseKind<'tcx>> for Predicate<'tcx> {
469    fn upcast_from(from: ClauseKind<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
470        tcx.mk_predicate(ty::Binder::dummy(PredicateKind::Clause(from)))
471    }
472}
473
474impl<'tcx> UpcastFrom<TyCtxt<'tcx>, ty::Binder<'tcx, ClauseKind<'tcx>>> for Predicate<'tcx> {
475    fn upcast_from(from: ty::Binder<'tcx, ClauseKind<'tcx>>, tcx: TyCtxt<'tcx>) -> Self {
476        tcx.mk_predicate(from.map_bound(PredicateKind::Clause))
477    }
478}
479
480impl<'tcx> UpcastFrom<TyCtxt<'tcx>, Clause<'tcx>> for Predicate<'tcx> {
481    fn upcast_from(from: Clause<'tcx>, _tcx: TyCtxt<'tcx>) -> Self {
482        from.as_predicate()
483    }
484}
485
486impl<'tcx> UpcastFrom<TyCtxt<'tcx>, ClauseKind<'tcx>> for Clause<'tcx> {
487    fn upcast_from(from: ClauseKind<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
488        tcx.mk_predicate(ty::Binder::dummy(PredicateKind::Clause(from))).expect_clause()
489    }
490}
491
492impl<'tcx> UpcastFrom<TyCtxt<'tcx>, ty::Binder<'tcx, ClauseKind<'tcx>>> for Clause<'tcx> {
493    fn upcast_from(from: ty::Binder<'tcx, ClauseKind<'tcx>>, tcx: TyCtxt<'tcx>) -> Self {
494        tcx.mk_predicate(from.map_bound(|clause| PredicateKind::Clause(clause))).expect_clause()
495    }
496}
497
498impl<'tcx> UpcastFrom<TyCtxt<'tcx>, TraitRef<'tcx>> for Predicate<'tcx> {
499    fn upcast_from(from: TraitRef<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
500        ty::Binder::dummy(from).upcast(tcx)
501    }
502}
503
504impl<'tcx> UpcastFrom<TyCtxt<'tcx>, TraitRef<'tcx>> for Clause<'tcx> {
505    fn upcast_from(from: TraitRef<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
506        let p: Predicate<'tcx> = from.upcast(tcx);
507        p.expect_clause()
508    }
509}
510
511impl<'tcx> UpcastFrom<TyCtxt<'tcx>, ty::Binder<'tcx, TraitRef<'tcx>>> for Predicate<'tcx> {
512    fn upcast_from(from: ty::Binder<'tcx, TraitRef<'tcx>>, tcx: TyCtxt<'tcx>) -> Self {
513        let pred: PolyTraitClause<'tcx> = from.upcast(tcx);
514        pred.upcast(tcx)
515    }
516}
517
518impl<'tcx> UpcastFrom<TyCtxt<'tcx>, ty::Binder<'tcx, TraitRef<'tcx>>> for Clause<'tcx> {
519    fn upcast_from(from: ty::Binder<'tcx, TraitRef<'tcx>>, tcx: TyCtxt<'tcx>) -> Self {
520        let pred: PolyTraitClause<'tcx> = from.upcast(tcx);
521        pred.upcast(tcx)
522    }
523}
524
525impl<'tcx> UpcastFrom<TyCtxt<'tcx>, TraitClause<'tcx>> for Predicate<'tcx> {
526    fn upcast_from(from: TraitClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
527        PredicateKind::Clause(ClauseKind::Trait(from)).upcast(tcx)
528    }
529}
530
531impl<'tcx> UpcastFrom<TyCtxt<'tcx>, PolyTraitClause<'tcx>> for Predicate<'tcx> {
532    fn upcast_from(from: PolyTraitClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
533        from.map_bound_no_validate_bound_vars(|p| PredicateKind::Clause(ClauseKind::Trait(p)))
534            .upcast(tcx)
535    }
536}
537
538impl<'tcx> UpcastFrom<TyCtxt<'tcx>, TraitClause<'tcx>> for Clause<'tcx> {
539    fn upcast_from(from: TraitClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
540        let p: Predicate<'tcx> = from.upcast(tcx);
541        p.expect_clause()
542    }
543}
544
545impl<'tcx> UpcastFrom<TyCtxt<'tcx>, PolyTraitClause<'tcx>> for Clause<'tcx> {
546    fn upcast_from(from: PolyTraitClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
547        let p: Predicate<'tcx> = from.upcast(tcx);
548        p.expect_clause()
549    }
550}
551
552impl<'tcx> UpcastFrom<TyCtxt<'tcx>, RegionOutlivesClause<'tcx>> for Predicate<'tcx> {
553    fn upcast_from(from: RegionOutlivesClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
554        ty::Binder::dummy(PredicateKind::Clause(ClauseKind::RegionOutlives(from))).upcast(tcx)
555    }
556}
557
558impl<'tcx> UpcastFrom<TyCtxt<'tcx>, PolyRegionOutlivesClause<'tcx>> for Predicate<'tcx> {
559    fn upcast_from(from: PolyRegionOutlivesClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
560        from.map_bound(|c| PredicateKind::Clause(ClauseKind::RegionOutlives(c))).upcast(tcx)
561    }
562}
563
564impl<'tcx> UpcastFrom<TyCtxt<'tcx>, TypeOutlivesClause<'tcx>> for Predicate<'tcx> {
565    fn upcast_from(from: TypeOutlivesClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
566        ty::Binder::dummy(PredicateKind::Clause(ClauseKind::TypeOutlives(from))).upcast(tcx)
567    }
568}
569
570impl<'tcx> UpcastFrom<TyCtxt<'tcx>, ProjectionClause<'tcx>> for Predicate<'tcx> {
571    fn upcast_from(from: ProjectionClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
572        ty::Binder::dummy(PredicateKind::Clause(ClauseKind::Projection(from))).upcast(tcx)
573    }
574}
575
576impl<'tcx> UpcastFrom<TyCtxt<'tcx>, PolyProjectionClause<'tcx>> for Predicate<'tcx> {
577    fn upcast_from(from: PolyProjectionClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
578        from.map_bound(|p| PredicateKind::Clause(ClauseKind::Projection(p))).upcast(tcx)
579    }
580}
581
582impl<'tcx> UpcastFrom<TyCtxt<'tcx>, ProjectionClause<'tcx>> for Clause<'tcx> {
583    fn upcast_from(from: ProjectionClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
584        let p: Predicate<'tcx> = from.upcast(tcx);
585        p.expect_clause()
586    }
587}
588
589impl<'tcx> UpcastFrom<TyCtxt<'tcx>, PolyProjectionClause<'tcx>> for Clause<'tcx> {
590    fn upcast_from(from: PolyProjectionClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
591        let p: Predicate<'tcx> = from.upcast(tcx);
592        p.expect_clause()
593    }
594}
595
596impl<'tcx> UpcastFrom<TyCtxt<'tcx>, ty::Binder<'tcx, ty::HostEffectClause<'tcx>>>
597    for Predicate<'tcx>
598{
599    fn upcast_from(from: ty::Binder<'tcx, ty::HostEffectClause<'tcx>>, tcx: TyCtxt<'tcx>) -> Self {
600        from.map_bound(ty::ClauseKind::HostEffect).upcast(tcx)
601    }
602}
603
604impl<'tcx> UpcastFrom<TyCtxt<'tcx>, ty::Binder<'tcx, ty::HostEffectClause<'tcx>>> for Clause<'tcx> {
605    fn upcast_from(from: ty::Binder<'tcx, ty::HostEffectClause<'tcx>>, tcx: TyCtxt<'tcx>) -> Self {
606        from.map_bound(ty::ClauseKind::HostEffect).upcast(tcx)
607    }
608}
609
610impl<'tcx> UpcastFrom<TyCtxt<'tcx>, NormalizesTo<'tcx>> for Predicate<'tcx> {
611    fn upcast_from(from: NormalizesTo<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
612        PredicateKind::NormalizesTo(from).upcast(tcx)
613    }
614}
615
616impl<'tcx> Predicate<'tcx> {
617    pub fn as_trait_clause(self) -> Option<PolyTraitClause<'tcx>> {
618        let predicate = self.kind();
619        match predicate.skip_binder() {
620            PredicateKind::Clause(ClauseKind::Trait(t)) => Some(predicate.rebind(t)),
621            _ => None,
622        }
623    }
624
625    pub fn as_projection_clause(self) -> Option<PolyProjectionClause<'tcx>> {
626        let predicate = self.kind();
627        match predicate.skip_binder() {
628            PredicateKind::Clause(ClauseKind::Projection(t)) => Some(predicate.rebind(t)),
629            _ => None,
630        }
631    }
632
633    /// Matches a `PredicateKind::Clause` and turns it into a `Clause`, otherwise returns `None`.
634    pub fn as_clause(self) -> Option<Clause<'tcx>> {
635        match self.kind().skip_binder() {
636            PredicateKind::Clause(..) => Some(self.expect_clause()),
637            _ => None,
638        }
639    }
640
641    /// Assert that the predicate is a clause.
642    pub fn expect_clause(self) -> Clause<'tcx> {
643        match self.kind().skip_binder() {
644            PredicateKind::Clause(..) => Clause(self.0),
645            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("{0} is not a clause", self), Location::caller())bug!("{self} is not a clause"),
646        }
647    }
648}
649
650// Some types are used a lot. Make sure they don't unintentionally get bigger.
651#[cfg(target_pointer_width = "64")]
652mod size_asserts {
653    use rustc_data_structures::static_assert_size;
654
655    use super::*;
656    // tidy-alphabetical-start
657    const _: [(); 40] = [(); ::std::mem::size_of::<PredicateKind<'_>>()];static_assert_size!(PredicateKind<'_>, 40);
658    const _: [(); 48] =
    [(); ::std::mem::size_of::<WithCachedTypeInfo<PredicateKind<'_>>>()];static_assert_size!(WithCachedTypeInfo<PredicateKind<'_>>, 48);
659    // tidy-alphabetical-end
660}