Skip to main content

rustc_type_ir/sty/
consts.rs

1use std::fmt;
2
3use derive_where::derive_where;
4use rustc_ast_ir::visit::VisitorResult;
5#[cfg(feature = "nightly")]
6use rustc_macros::StableHash_NoContext;
7use rustc_type_ir_macros::{GenericTypeVisitable, Lift_Generic};
8
9use crate::inherent::*;
10use crate::intern::Interned;
11use crate::relate::{Relate, RelateResult, TypeRelation};
12use crate::walk::TypeWalker;
13use crate::{
14    AliasConst, BoundConst, BoundVar, BoundVarIndexKind, ConstKind, ConstVid, DebruijnIndex,
15    FallibleTypeFolder, Flags, InferConst, Interner, IsRigid, PlaceholderConst, TypeFlags,
16    TypeFoldable, TypeFolder, TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitor,
17    ValTreeKind,
18};
19
20#[automatically_derived]
impl<I: Interner> ::core::clone::Clone for Const<I> where I: Interner {
    #[inline]
    fn clone(&self) -> Self { *self }
}
#[automatically_derived]
impl<I: Interner> ::core::marker::Copy for Const<I> where I: Interner { }
#[automatically_derived]
impl<I: Interner> ::core::cmp::PartialEq for Const<I> where I: Interner {
    #[inline]
    fn eq(&self, __other: &Self) -> ::core::primitive::bool {
        match (self, __other) {
            (Const(ref __field_0), Const(ref __other_field_0)) =>
                true &&
                    ::core::cmp::PartialEq::eq(__field_0, __other_field_0),
        }
    }
}
const _: () =
    {
        trait DeriveWhereAssertEq {
            fn assert(&self);
        }
        impl<I: Interner> DeriveWhereAssertEq for Const<I> where I: Interner {
            fn assert(&self) {
                struct __AssertEq<__T: ::core::cmp::Eq +
                    ?::core::marker::Sized>(::core::marker::PhantomData<__T>);
                let _: __AssertEq<I::InternedConstKind>;
            }
        }
    };
#[automatically_derived]
impl<I: Interner> ::core::cmp::Eq for Const<I> where I: Interner { }
#[automatically_derived]
impl<I: Interner> ::core::hash::Hash for Const<I> where I: Interner {
    fn hash<__H: ::core::hash::Hasher>(&self, __state: &mut __H) {
        match self {
            Const(ref __field_0) => {
                ::core::hash::Hash::hash(__field_0, __state);
            }
        }
    }
}#[derive_where(Clone, Copy, PartialEq, Eq, Hash; I: Interner)]
21#[cfg_attr(feature = "nightly", derive(const _: () =
    {
        impl<I: Interner> ::rustc_data_structures::stable_hash::StableHash for
            Const<I> where
            I::InternedConstKind: ::rustc_data_structures::stable_hash::StableHash
            {
            #[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 {
                    Const(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash_NoContext))]
22#[cfg_attr(
23    feature = "nightly",
24    cfg_attr(bootstrap, rustc_pass_by_value),
25    cfg_attr(not(bootstrap), lint::pass_by_value)
26)]
27#[derive(const _: () =
    {
        unsafe impl<I: Interner, __V>
            ::rustc_type_ir::GenericTypeVisitable<__V> for Const<I> where
            I::InternedConstKind: ::rustc_type_ir::GenericTypeVisitable<__V> {
            fn generic_visit_with(&self, __visitor: &mut __V) {
                match *self {
                    Const(ref __binding_0) => {
                        {
                            ::rustc_type_ir::GenericTypeVisitable::<__V>::generic_visit_with(__binding_0,
                                __visitor);
                        }
                    }
                }
            }
        }
    };GenericTypeVisitable, const _: () =
    {
        impl<I: Interner, J> ::rustc_type_ir::lift::Lift<J> for Const<I> where
            J: Interner, I: ::rustc_type_ir::LiftInto<J> {
            type Lifted = Const<J>;
            fn lift_to_interner(self, interner: J) -> Self::Lifted {
                match self {
                    Const(__binding_0) => {
                        Const(__binding_0.lift_to_interner(interner))
                    }
                }
            }
        }
    };Lift_Generic)]
28pub struct Const<I: Interner>(pub I::InternedConstKind);
29
30impl<I: Interner> fmt::Debug for Const<I> {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        // If this is a value, we spend some effort to make it look nice.
33        if let ConstKind::Value(cv) = self.kind() {
34            f.write_fmt(format_args!("{0}", cv))write!(f, "{}", cv)
35        } else {
36            // Fall back to something verbose.
37            f.write_fmt(format_args!("{0:?}", self.kind()))write!(f, "{:?}", self.kind())
38        }
39    }
40}
41
42impl<I: Interner> Const<I> {
43    #[inline]
44    pub fn kind(self) -> ConstKind<I> {
45        *self.0.get()
46    }
47
48    #[inline]
49    pub fn new(interner: I, kind: ConstKind<I>) -> Self {
50        interner.mk_ct_from_kind(kind)
51    }
52
53    #[inline]
54    pub fn new_var(interner: I, infer: ConstVid) -> Self {
55        Self::new(interner, ConstKind::Infer(InferConst::Var(infer)))
56    }
57
58    #[inline]
59    pub fn new_infer(interner: I, infer: InferConst) -> Self {
60        Self::new(interner, ConstKind::Infer(infer))
61    }
62
63    #[inline]
64    pub fn new_bound(interner: I, debruijn: DebruijnIndex, bound_const: BoundConst<I>) -> Self {
65        Self::new(interner, ConstKind::Bound(BoundVarIndexKind::Bound(debruijn), bound_const))
66    }
67
68    #[inline]
69    pub fn new_anon_bound(interner: I, debruijn: DebruijnIndex, var: BoundVar) -> Self {
70        Self::new_bound(interner, debruijn, BoundConst::new(var))
71    }
72
73    #[inline]
74    pub fn new_canonical_bound(interner: I, var: BoundVar) -> Self {
75        Self::new(interner, ConstKind::Bound(BoundVarIndexKind::Canonical, BoundConst::new(var)))
76    }
77
78    #[inline]
79    pub fn new_placeholder(interner: I, placeholder: PlaceholderConst<I>) -> Self {
80        Self::new(interner, ConstKind::Placeholder(placeholder))
81    }
82
83    #[inline]
84    pub fn new_alias(interner: I, is_rigid: IsRigid, alias_const: AliasConst<I>) -> Self {
85        Self::new(interner, ConstKind::Alias(is_rigid, alias_const))
86    }
87
88    #[inline]
89    pub fn new_expr(interner: I, expr: I::ExprConst) -> Self {
90        Const::new(interner, ConstKind::Expr(expr))
91    }
92
93    #[inline]
94    pub fn new_error(interner: I, e: I::ErrorGuaranteed) -> Self {
95        Const::new(interner, ConstKind::Error(e))
96    }
97
98    #[inline]
99    pub fn is_ct_var(self) -> bool {
100        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    ConstKind::Infer(InferConst::Var(_)) => true,
    _ => false,
}matches!(self.kind(), ConstKind::Infer(InferConst::Var(_)))
101    }
102
103    #[inline]
104    pub fn is_ct_error(self) -> bool {
105        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    ConstKind::Error(_) => true,
    _ => false,
}matches!(self.kind(), ConstKind::Error(_))
106    }
107
108    #[inline]
109    pub fn new_param(interner: I, param: I::ParamConst) -> Self {
110        Self::new(interner, ConstKind::Param(param))
111    }
112
113    #[inline]
114    pub fn new_fresh(interner: I, fresh: u32) -> Self {
115        Self::new(interner, ConstKind::Infer(InferConst::Fresh(fresh)))
116    }
117
118    #[track_caller]
119    pub fn new_misc_error(interner: I) -> Self {
120        Self::new_error_with_message(
121            interner,
122            I::Span::dummy(),
123            "ty::ConstKind::Error constructed but no error reported",
124        )
125    }
126
127    #[track_caller]
128    pub fn new_error_with_message(interner: I, span: I::Span, msg: impl ToString) -> Self {
129        let reported = interner.span_delayed_bug(span, msg);
130        Self::new_error(interner, reported)
131    }
132
133    pub fn is_trivially_wf(self) -> bool {
134        match self.kind() {
135            ConstKind::Param(_) | ConstKind::Placeholder(_) | ConstKind::Bound(..) => true,
136            ConstKind::Infer(_)
137            | ConstKind::Alias(..)
138            | ConstKind::Value(_)
139            | ConstKind::Error(_)
140            | ConstKind::Expr(_) => false,
141        }
142    }
143
144    pub fn is_ct_infer(self) -> bool {
145        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    ConstKind::Infer(_) => true,
    _ => false,
}matches!(self.kind(), ConstKind::Infer(_))
146    }
147
148    pub fn ct_vid(self) -> Option<ConstVid> {
149        match self.kind() {
150            ConstKind::Infer(InferConst::Var(vid)) => Some(vid),
151            _ => None,
152        }
153    }
154
155    #[inline]
156    pub fn new_value(interner: I, valtree: I::ValTree, ty: I::Ty) -> Self {
157        Self::new(interner, ConstKind::Value(I::ValueConst::new(ty, valtree)))
158    }
159
160    /// Creates an interned zst constant.
161    #[inline]
162    pub fn zero_sized(interner: I, ty: I::Ty) -> Self {
163        Self::new_value(interner, interner.const_zst(), ty)
164    }
165
166    /// Panics if `self.kind != ty::ConstKind::Value`.
167    pub fn to_value(self) -> I::ValueConst {
168        match self.kind() {
169            ConstKind::Value(cv) => cv,
170            _ => {
    ::core::panicking::panic_fmt(format_args!("expected ConstKind::Value, got {0:?}",
            self.kind()));
}panic!("expected ConstKind::Value, got {:?}", self.kind()),
171        }
172    }
173
174    /// Attempts to convert to a value.
175    ///
176    /// Note that this does not normalize the constant.
177    pub fn try_to_value(self) -> Option<I::ValueConst> {
178        match self.kind() {
179            ConstKind::Value(cv) => Some(cv),
180            _ => None,
181        }
182    }
183
184    /// Converts to a `ValTreeKind::Leaf` value, `panic`'ing
185    /// if this constant is some other kind.
186    ///
187    /// Note that this does not normalize the constant.
188    #[inline]
189    pub fn to_leaf(self) -> I::ScalarInt {
190        self.to_value().valtree().kind().to_leaf()
191    }
192
193    /// Converts to a `ValTreeKind::Branch` value, `panic`'ing
194    /// if this constant is some other kind.
195    ///
196    /// Note that this does not normalize the constant.
197    #[inline]
198    pub fn to_branch(self) -> I::Consts {
199        self.to_value().valtree().kind().to_branch()
200    }
201
202    /// Attempts to convert to a `ValTreeKind::Leaf` value.
203    ///
204    /// Note that this does not normalize the constant.
205    pub fn try_to_leaf(self) -> Option<I::ScalarInt> {
206        self.try_to_value()?.valtree().kind().try_to_leaf()
207    }
208    /// Attempts to convert to a `ValTreeKind::Branch` value.
209    ///
210    /// Note that this does not normalize the constant.
211    pub fn try_to_branch(self) -> Option<I::Consts> {
212        self.try_to_value()?.valtree().kind().try_to_branch()
213    }
214
215    /// Attempts to convert to a `ValTreeKind::Leaf` value.
216    ///
217    /// Note that this does not normalize the constant.
218    pub fn try_to_scalar(self) -> Option<I::Scalar> {
219        self.try_to_leaf().map(|x| x.to_scalar())
220    }
221
222    /// Creates a constant with the given integer value and interns it.
223    #[inline]
224    pub fn from_bits(interner: I, bits: u128, typing_env: I::TypingEnv, ty: I::Ty) -> Self {
225        let size = typing_env.layout_size(interner, ty);
226        let scalar_int = I::ScalarInt::try_from_uint(bits, size).unwrap();
227        let valtree = interner.intern_valtree(ValTreeKind::Leaf(scalar_int));
228        Self::new_value(interner, valtree, ty)
229    }
230
231    #[inline]
232    /// Creates an interned bool constant.
233    pub fn from_bool(interner: I, v: bool) -> Self {
234        let bool_ty = I::Ty::new_bool(interner);
235        Self::from_bits(interner, v as u128, I::TypingEnv::fully_monomorphized(), bool_ty)
236    }
237
238    #[inline]
239    /// Creates an interned usize constant.
240    pub fn from_target_usize(interner: I, n: u64) -> Self {
241        let usize_ty = I::Ty::new_usize(interner);
242        Self::from_bits(interner, n as u128, I::TypingEnv::fully_monomorphized(), usize_ty)
243    }
244
245    /// Convenience method to extract the value of a usize constant,
246    /// useful to get the length of an array type.
247    ///
248    /// Note that this does not evaluate the constant.
249    #[inline]
250    pub fn try_to_target_usize(self, interner: I) -> Option<u64> {
251        self.try_to_value()?.try_to_target_usize(interner)
252    }
253
254    /// Iterator that walks `self` and any types reachable from
255    /// `self`, in depth-first order. Note that just walks the types
256    /// that appear in `self`, it does not descend into the fields of
257    /// structs or variants. For example:
258    ///
259    /// ```text
260    /// isize => { isize }
261    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
262    /// [isize] => { [isize], isize }
263    /// ```
264    pub fn walk(self) -> TypeWalker<I> {
265        TypeWalker::new(self.into())
266    }
267}
268
269impl<I: Interner> Flags for Const<I> {
270    fn flags(&self) -> TypeFlags {
271        self.0.get().flags
272    }
273
274    fn outer_exclusive_binder(&self) -> DebruijnIndex {
275        self.0.get().outer_exclusive_binder
276    }
277}
278
279impl<I: Interner> IntoKind for Const<I> {
280    type Kind = ConstKind<I>;
281
282    fn kind(self) -> Self::Kind {
283        *self.0.get()
284    }
285}
286
287impl<I: Interner> TypeFoldable<I> for Const<I> {
288    fn try_fold_with<F: FallibleTypeFolder<I>>(self, folder: &mut F) -> Result<Self, F::Error> {
289        folder.try_fold_const(self)
290    }
291
292    fn fold_with<F: TypeFolder<I>>(self, folder: &mut F) -> Self {
293        folder.fold_const(self)
294    }
295}
296
297impl<I: Interner> TypeVisitable<I> for Const<I> {
298    fn visit_with<V: TypeVisitor<I>>(&self, visitor: &mut V) -> V::Result {
299        visitor.visit_const(*self)
300    }
301}
302
303impl<I: Interner> TypeSuperFoldable<I> for Const<I> {
304    fn try_super_fold_with<F: FallibleTypeFolder<I>>(
305        self,
306        folder: &mut F,
307    ) -> Result<Self, F::Error> {
308        let kind = match self.kind() {
309            ConstKind::Alias(is_rigid, alias_const) => {
310                ConstKind::Alias(is_rigid, alias_const.try_fold_with(folder)?)
311            }
312            ConstKind::Value(v) => ConstKind::Value(v.try_fold_with(folder)?),
313            ConstKind::Expr(e) => ConstKind::Expr(e.try_fold_with(folder)?),
314
315            ConstKind::Param(_)
316            | ConstKind::Infer(_)
317            | ConstKind::Bound(..)
318            | ConstKind::Placeholder(_)
319            | ConstKind::Error(_) => return Ok(self),
320        };
321        if kind != self.kind() { Ok(Self::new(folder.cx(), kind)) } else { Ok(self) }
322    }
323
324    fn super_fold_with<F: TypeFolder<I>>(self, folder: &mut F) -> Self {
325        let kind = match self.kind() {
326            ConstKind::Alias(is_rigid, alias_const) => {
327                ConstKind::Alias(is_rigid, alias_const.fold_with(folder))
328            }
329            ConstKind::Value(v) => ConstKind::Value(v.fold_with(folder)),
330            ConstKind::Expr(e) => ConstKind::Expr(e.fold_with(folder)),
331
332            ConstKind::Param(_)
333            | ConstKind::Infer(_)
334            | ConstKind::Bound(..)
335            | ConstKind::Placeholder(_)
336            | ConstKind::Error(_) => return self,
337        };
338        if kind != self.kind() { Self::new(folder.cx(), kind) } else { self }
339    }
340}
341
342impl<I: Interner> TypeSuperVisitable<I> for Const<I> {
343    fn super_visit_with<V: TypeVisitor<I>>(&self, visitor: &mut V) -> V::Result {
344        match self.kind() {
345            ConstKind::Alias(_, alias_const) => alias_const.visit_with(visitor),
346            ConstKind::Value(v) => v.visit_with(visitor),
347            ConstKind::Expr(e) => e.visit_with(visitor),
348            ConstKind::Error(e) => e.visit_with(visitor),
349
350            ConstKind::Param(_)
351            | ConstKind::Infer(_)
352            | ConstKind::Bound(..)
353            | ConstKind::Placeholder(_) => V::Result::output(),
354        }
355    }
356}
357
358impl<I: Interner> Relate<I> for Const<I> {
359    fn relate<R: TypeRelation<I>>(relation: &mut R, a: Self, b: Self) -> RelateResult<I, Self> {
360        relation.consts(a, b)
361    }
362}