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