rustc_middle/ty/
consts.rs

1use std::borrow::Cow;
2
3use rustc_data_structures::intern::Interned;
4use rustc_error_messages::MultiSpan;
5use rustc_macros::{HashStable, TyDecodable, TyEncodable};
6use rustc_type_ir::walk::TypeWalker;
7use rustc_type_ir::{self as ir, TypeFlags, WithCachedTypeInfo};
8
9use crate::ty::{self, Ty, TyCtxt};
10
11mod int;
12mod kind;
13mod valtree;
14
15pub use int::*;
16pub use kind::*;
17use rustc_span::{DUMMY_SP, ErrorGuaranteed};
18pub use valtree::*;
19
20pub type ConstKind<'tcx> = ir::ConstKind<TyCtxt<'tcx>>;
21pub type UnevaluatedConst<'tcx> = ir::UnevaluatedConst<TyCtxt<'tcx>>;
22
23#[cfg(target_pointer_width = "64")]
24rustc_data_structures::static_assert_size!(ConstKind<'_>, 24);
25
26#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
27#[rustc_pass_by_value]
28pub struct Const<'tcx>(pub(super) Interned<'tcx, WithCachedTypeInfo<ConstKind<'tcx>>>);
29
30impl<'tcx> rustc_type_ir::inherent::IntoKind for Const<'tcx> {
31    type Kind = ConstKind<'tcx>;
32
33    fn kind(self) -> ConstKind<'tcx> {
34        self.kind()
35    }
36}
37
38impl<'tcx> rustc_type_ir::Flags for Const<'tcx> {
39    fn flags(&self) -> TypeFlags {
40        self.0.flags
41    }
42
43    fn outer_exclusive_binder(&self) -> rustc_type_ir::DebruijnIndex {
44        self.0.outer_exclusive_binder
45    }
46}
47
48impl<'tcx> Const<'tcx> {
49    #[inline]
50    pub fn kind(self) -> ConstKind<'tcx> {
51        let a: &ConstKind<'tcx> = self.0.0;
52        *a
53    }
54
55    // FIXME(compiler-errors): Think about removing this.
56    #[inline]
57    pub fn flags(self) -> TypeFlags {
58        self.0.flags
59    }
60
61    // FIXME(compiler-errors): Think about removing this.
62    #[inline]
63    pub fn outer_exclusive_binder(self) -> ty::DebruijnIndex {
64        self.0.outer_exclusive_binder
65    }
66
67    #[inline]
68    pub fn new(tcx: TyCtxt<'tcx>, kind: ty::ConstKind<'tcx>) -> Const<'tcx> {
69        tcx.mk_ct_from_kind(kind)
70    }
71
72    #[inline]
73    pub fn new_param(tcx: TyCtxt<'tcx>, param: ty::ParamConst) -> Const<'tcx> {
74        Const::new(tcx, ty::ConstKind::Param(param))
75    }
76
77    #[inline]
78    pub fn new_var(tcx: TyCtxt<'tcx>, infer: ty::ConstVid) -> Const<'tcx> {
79        Const::new(tcx, ty::ConstKind::Infer(ty::InferConst::Var(infer)))
80    }
81
82    #[inline]
83    pub fn new_fresh(tcx: TyCtxt<'tcx>, fresh: u32) -> Const<'tcx> {
84        Const::new(tcx, ty::ConstKind::Infer(ty::InferConst::Fresh(fresh)))
85    }
86
87    #[inline]
88    pub fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferConst) -> Const<'tcx> {
89        Const::new(tcx, ty::ConstKind::Infer(infer))
90    }
91
92    #[inline]
93    pub fn new_bound(
94        tcx: TyCtxt<'tcx>,
95        debruijn: ty::DebruijnIndex,
96        bound_const: ty::BoundConst,
97    ) -> Const<'tcx> {
98        Const::new(tcx, ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(debruijn), bound_const))
99    }
100
101    #[inline]
102    pub fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: ty::BoundVar) -> Const<'tcx> {
103        Const::new(
104            tcx,
105            ty::ConstKind::Bound(ty::BoundVarIndexKind::Canonical, ty::BoundConst { var }),
106        )
107    }
108
109    #[inline]
110    pub fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderConst) -> Const<'tcx> {
111        Const::new(tcx, ty::ConstKind::Placeholder(placeholder))
112    }
113
114    #[inline]
115    pub fn new_unevaluated(tcx: TyCtxt<'tcx>, uv: ty::UnevaluatedConst<'tcx>) -> Const<'tcx> {
116        tcx.debug_assert_args_compatible(uv.def, uv.args);
117        Const::new(tcx, ty::ConstKind::Unevaluated(uv))
118    }
119
120    #[inline]
121    pub fn new_value(tcx: TyCtxt<'tcx>, valtree: ty::ValTree<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
122        Const::new(tcx, ty::ConstKind::Value(ty::Value { ty, valtree }))
123    }
124
125    #[inline]
126    pub fn new_expr(tcx: TyCtxt<'tcx>, expr: ty::Expr<'tcx>) -> Const<'tcx> {
127        Const::new(tcx, ty::ConstKind::Expr(expr))
128    }
129
130    #[inline]
131    pub fn new_error(tcx: TyCtxt<'tcx>, e: ty::ErrorGuaranteed) -> Const<'tcx> {
132        Const::new(tcx, ty::ConstKind::Error(e))
133    }
134
135    /// Like [Ty::new_error] but for constants.
136    #[track_caller]
137    pub fn new_misc_error(tcx: TyCtxt<'tcx>) -> Const<'tcx> {
138        Const::new_error_with_message(
139            tcx,
140            DUMMY_SP,
141            "ty::ConstKind::Error constructed but no error reported",
142        )
143    }
144
145    /// Like [Ty::new_error_with_message] but for constants.
146    #[track_caller]
147    pub fn new_error_with_message<S: Into<MultiSpan>>(
148        tcx: TyCtxt<'tcx>,
149        span: S,
150        msg: impl Into<Cow<'static, str>>,
151    ) -> Const<'tcx> {
152        let reported = tcx.dcx().span_delayed_bug(span, msg);
153        Const::new_error(tcx, reported)
154    }
155
156    pub fn is_trivially_wf(self) -> bool {
157        match self.kind() {
158            ty::ConstKind::Param(_) | ty::ConstKind::Placeholder(_) | ty::ConstKind::Bound(..) => {
159                true
160            }
161            ty::ConstKind::Infer(_)
162            | ty::ConstKind::Unevaluated(..)
163            | ty::ConstKind::Value(_)
164            | ty::ConstKind::Error(_)
165            | ty::ConstKind::Expr(_) => false,
166        }
167    }
168}
169
170impl<'tcx> rustc_type_ir::inherent::Const<TyCtxt<'tcx>> for Const<'tcx> {
171    fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferConst) -> Self {
172        Const::new_infer(tcx, infer)
173    }
174
175    fn new_var(tcx: TyCtxt<'tcx>, vid: ty::ConstVid) -> Self {
176        Const::new_var(tcx, vid)
177    }
178
179    fn new_bound(
180        interner: TyCtxt<'tcx>,
181        debruijn: ty::DebruijnIndex,
182        bound_const: ty::BoundConst,
183    ) -> Self {
184        Const::new_bound(interner, debruijn, bound_const)
185    }
186
187    fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self {
188        Const::new_bound(tcx, debruijn, ty::BoundConst { var })
189    }
190
191    fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: rustc_type_ir::BoundVar) -> Self {
192        Const::new_canonical_bound(tcx, var)
193    }
194
195    fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderConst) -> Self {
196        Const::new_placeholder(tcx, placeholder)
197    }
198
199    fn new_unevaluated(interner: TyCtxt<'tcx>, uv: ty::UnevaluatedConst<'tcx>) -> Self {
200        Const::new_unevaluated(interner, uv)
201    }
202
203    fn new_expr(interner: TyCtxt<'tcx>, expr: ty::Expr<'tcx>) -> Self {
204        Const::new_expr(interner, expr)
205    }
206
207    fn new_error(interner: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Self {
208        Const::new_error(interner, guar)
209    }
210}
211
212impl<'tcx> Const<'tcx> {
213    /// Creates a constant with the given integer value and interns it.
214    #[inline]
215    pub fn from_bits(
216        tcx: TyCtxt<'tcx>,
217        bits: u128,
218        typing_env: ty::TypingEnv<'tcx>,
219        ty: Ty<'tcx>,
220    ) -> Self {
221        let size = tcx
222            .layout_of(typing_env.as_query_input(ty))
223            .unwrap_or_else(|e| panic!("could not compute layout for {ty:?}: {e:?}"))
224            .size;
225        ty::Const::new_value(
226            tcx,
227            ty::ValTree::from_scalar_int(tcx, ScalarInt::try_from_uint(bits, size).unwrap()),
228            ty,
229        )
230    }
231
232    #[inline]
233    /// Creates an interned zst constant.
234    pub fn zero_sized(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Self {
235        ty::Const::new_value(tcx, ty::ValTree::zst(tcx), ty)
236    }
237
238    #[inline]
239    /// Creates an interned bool constant.
240    pub fn from_bool(tcx: TyCtxt<'tcx>, v: bool) -> Self {
241        Self::from_bits(tcx, v as u128, ty::TypingEnv::fully_monomorphized(), tcx.types.bool)
242    }
243
244    #[inline]
245    /// Creates an interned usize constant.
246    pub fn from_target_usize(tcx: TyCtxt<'tcx>, n: u64) -> Self {
247        Self::from_bits(tcx, n as u128, ty::TypingEnv::fully_monomorphized(), tcx.types.usize)
248    }
249
250    /// Panics if `self.kind != ty::ConstKind::Value`.
251    pub fn to_value(self) -> ty::Value<'tcx> {
252        match self.kind() {
253            ty::ConstKind::Value(cv) => cv,
254            _ => bug!("expected ConstKind::Value, got {:?}", self.kind()),
255        }
256    }
257
258    /// Attempts to convert to a value.
259    ///
260    /// Note that this does not evaluate the constant.
261    pub fn try_to_value(self) -> Option<ty::Value<'tcx>> {
262        match self.kind() {
263            ty::ConstKind::Value(cv) => Some(cv),
264            _ => None,
265        }
266    }
267
268    /// Convenience method to extract the value of a usize constant,
269    /// useful to get the length of an array type.
270    ///
271    /// Note that this does not evaluate the constant.
272    #[inline]
273    pub fn try_to_target_usize(self, tcx: TyCtxt<'tcx>) -> Option<u64> {
274        self.try_to_value()?.try_to_target_usize(tcx)
275    }
276
277    pub fn is_ct_infer(self) -> bool {
278        matches!(self.kind(), ty::ConstKind::Infer(_))
279    }
280
281    /// Iterator that walks `self` and any types reachable from
282    /// `self`, in depth-first order. Note that just walks the types
283    /// that appear in `self`, it does not descend into the fields of
284    /// structs or variants. For example:
285    ///
286    /// ```text
287    /// isize => { isize }
288    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
289    /// [isize] => { [isize], isize }
290    /// ```
291    pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
292        TypeWalker::new(self.into())
293    }
294}
295
296#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable, HashStable)]
297pub enum AnonConstKind {
298    /// `feature(generic_const_exprs)` anon consts are allowed to use arbitrary generic parameters in scope
299    GCE,
300    /// stable `min_const_generics` anon consts are not allowed to use any generic parameters
301    MCG,
302    /// anon consts used as the length of a repeat expr are syntactically allowed to use generic parameters
303    /// but must not depend on the actual instantiation. See #76200 for more information
304    RepeatExprCount,
305    /// anon consts outside of the type system, e.g. enum discriminants
306    NonTypeSystem,
307}