]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/consts.rs
Rollup merge of #104487 - klensy:ntapi, r=Mark-Simulacrum
[rust.git] / compiler / rustc_middle / src / ty / consts.rs
1 use crate::mir::interpret::LitToConstInput;
2 use crate::mir::ConstantKind;
3 use crate::ty::{self, DefIdTree, InternalSubsts, ParamEnv, ParamEnvAnd, Ty, TyCtxt};
4 use rustc_data_structures::intern::Interned;
5 use rustc_hir as hir;
6 use rustc_hir::def_id::{DefId, LocalDefId};
7 use rustc_macros::HashStable;
8 use std::fmt;
9
10 mod int;
11 mod kind;
12 mod valtree;
13
14 pub use int::*;
15 pub use kind::*;
16 pub use valtree::*;
17
18 /// Use this rather than `ConstS`, whenever possible.
19 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
20 #[rustc_pass_by_value]
21 pub struct Const<'tcx>(pub Interned<'tcx, ConstS<'tcx>>);
22
23 impl<'tcx> fmt::Debug for Const<'tcx> {
24     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25         // This reflects what `Const` looked liked before `Interned` was
26         // introduced. We print it like this to avoid having to update expected
27         // output in a lot of tests.
28         write!(f, "Const {{ ty: {:?}, kind: {:?} }}", self.ty(), self.kind())
29     }
30 }
31
32 /// Typed constant value.
33 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, TyEncodable, TyDecodable)]
34 pub struct ConstS<'tcx> {
35     pub ty: Ty<'tcx>,
36     pub kind: ConstKind<'tcx>,
37 }
38
39 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
40 static_assert_size!(ConstS<'_>, 40);
41
42 impl<'tcx> Const<'tcx> {
43     #[inline]
44     pub fn ty(self) -> Ty<'tcx> {
45         self.0.ty
46     }
47
48     #[inline]
49     pub fn kind(self) -> ConstKind<'tcx> {
50         self.0.kind
51     }
52
53     /// Literals and const generic parameters are eagerly converted to a constant, everything else
54     /// becomes `Unevaluated`.
55     pub fn from_anon_const(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
56         Self::from_opt_const_arg_anon_const(tcx, ty::WithOptConstParam::unknown(def_id))
57     }
58
59     #[instrument(skip(tcx), level = "debug")]
60     pub fn from_opt_const_arg_anon_const(
61         tcx: TyCtxt<'tcx>,
62         def: ty::WithOptConstParam<LocalDefId>,
63     ) -> Self {
64         let body_id = match tcx.hir().get_by_def_id(def.did) {
65             hir::Node::AnonConst(ac) => ac.body,
66             _ => span_bug!(
67                 tcx.def_span(def.did.to_def_id()),
68                 "from_anon_const can only process anonymous constants"
69             ),
70         };
71
72         let expr = &tcx.hir().body(body_id).value;
73         debug!(?expr);
74
75         let ty = tcx.type_of(def.def_id_for_type_of());
76
77         match Self::try_eval_lit_or_param(tcx, ty, expr) {
78             Some(v) => v,
79             None => tcx.mk_const(
80                 ty::ConstKind::Unevaluated(ty::UnevaluatedConst {
81                     def: def.to_global(),
82                     substs: InternalSubsts::identity_for_item(tcx, def.did.to_def_id()),
83                 }),
84                 ty,
85             ),
86         }
87     }
88
89     #[instrument(skip(tcx), level = "debug")]
90     fn try_eval_lit_or_param(
91         tcx: TyCtxt<'tcx>,
92         ty: Ty<'tcx>,
93         expr: &'tcx hir::Expr<'tcx>,
94     ) -> Option<Self> {
95         // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
96         // currently have to be wrapped in curly brackets, so it's necessary to special-case.
97         let expr = match &expr.kind {
98             hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
99                 block.expr.as_ref().unwrap()
100             }
101             _ => expr,
102         };
103
104         let lit_input = match expr.kind {
105             hir::ExprKind::Lit(ref lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: false }),
106             hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => match expr.kind {
107                 hir::ExprKind::Lit(ref lit) => {
108                     Some(LitToConstInput { lit: &lit.node, ty, neg: true })
109                 }
110                 _ => None,
111             },
112             _ => None,
113         };
114
115         if let Some(lit_input) = lit_input {
116             // If an error occurred, ignore that it's a literal and leave reporting the error up to
117             // mir.
118             match tcx.at(expr.span).lit_to_const(lit_input) {
119                 Ok(c) => return Some(c),
120                 Err(e) => {
121                     tcx.sess.delay_span_bug(
122                         expr.span,
123                         &format!("Const::from_anon_const: couldn't lit_to_const {:?}", e),
124                     );
125                 }
126             }
127         }
128
129         use hir::{def::DefKind::ConstParam, def::Res, ExprKind, Path, QPath};
130         match expr.kind {
131             ExprKind::Path(QPath::Resolved(_, &Path { res: Res::Def(ConstParam, def_id), .. })) => {
132                 // Find the name and index of the const parameter by indexing the generics of
133                 // the parent item and construct a `ParamConst`.
134                 let item_def_id = tcx.parent(def_id);
135                 let generics = tcx.generics_of(item_def_id);
136                 let index = generics.param_def_id_to_index[&def_id];
137                 let name = tcx.item_name(def_id);
138                 Some(tcx.mk_const(ty::ConstKind::Param(ty::ParamConst::new(index, name)), ty))
139             }
140             _ => None,
141         }
142     }
143
144     /// Interns the given value as a constant.
145     #[inline]
146     pub fn from_value(tcx: TyCtxt<'tcx>, val: ty::ValTree<'tcx>, ty: Ty<'tcx>) -> Self {
147         tcx.mk_const(ConstKind::Value(val), ty)
148     }
149
150     /// Panics if self.kind != ty::ConstKind::Value
151     pub fn to_valtree(self) -> ty::ValTree<'tcx> {
152         match self.kind() {
153             ty::ConstKind::Value(valtree) => valtree,
154             _ => bug!("expected ConstKind::Value, got {:?}", self.kind()),
155         }
156     }
157
158     pub fn from_scalar_int(tcx: TyCtxt<'tcx>, i: ScalarInt, ty: Ty<'tcx>) -> Self {
159         let valtree = ty::ValTree::from_scalar_int(i);
160         Self::from_value(tcx, valtree, ty)
161     }
162
163     #[inline]
164     /// Creates a constant with the given integer value and interns it.
165     pub fn from_bits(tcx: TyCtxt<'tcx>, bits: u128, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> Self {
166         let size = tcx
167             .layout_of(ty)
168             .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
169             .size;
170         Self::from_scalar_int(tcx, ScalarInt::try_from_uint(bits, size).unwrap(), ty.value)
171     }
172
173     #[inline]
174     /// Creates an interned zst constant.
175     pub fn zero_sized(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Self {
176         let valtree = ty::ValTree::zst();
177         Self::from_value(tcx, valtree, ty)
178     }
179
180     #[inline]
181     /// Creates an interned bool constant.
182     pub fn from_bool(tcx: TyCtxt<'tcx>, v: bool) -> Self {
183         Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool))
184     }
185
186     #[inline]
187     /// Creates an interned usize constant.
188     pub fn from_usize(tcx: TyCtxt<'tcx>, n: u64) -> Self {
189         Self::from_bits(tcx, n as u128, ParamEnv::empty().and(tcx.types.usize))
190     }
191
192     #[inline]
193     /// Attempts to evaluate the given constant to bits. Can fail to evaluate in the presence of
194     /// generics (or erroneous code) or if the value can't be represented as bits (e.g. because it
195     /// contains const generic parameters or pointers).
196     pub fn try_eval_bits(
197         self,
198         tcx: TyCtxt<'tcx>,
199         param_env: ParamEnv<'tcx>,
200         ty: Ty<'tcx>,
201     ) -> Option<u128> {
202         assert_eq!(self.ty(), ty);
203         let size = tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
204         // if `ty` does not depend on generic parameters, use an empty param_env
205         self.kind().eval(tcx, param_env).try_to_bits(size)
206     }
207
208     #[inline]
209     pub fn try_eval_bool(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<bool> {
210         self.kind().eval(tcx, param_env).try_to_bool()
211     }
212
213     #[inline]
214     pub fn try_eval_usize(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<u64> {
215         self.kind().eval(tcx, param_env).try_to_machine_usize(tcx)
216     }
217
218     #[inline]
219     /// Tries to evaluate the constant if it is `Unevaluated`. If that doesn't succeed, return the
220     /// unevaluated constant.
221     pub fn eval(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Const<'tcx> {
222         if let Some(val) = self.kind().try_eval_for_typeck(tcx, param_env) {
223             match val {
224                 Ok(val) => Const::from_value(tcx, val, self.ty()),
225                 Err(guar) => tcx.const_error_with_guaranteed(self.ty(), guar),
226             }
227         } else {
228             // Either the constant isn't evaluatable or ValTree creation failed.
229             self
230         }
231     }
232
233     #[inline]
234     /// Tries to evaluate the constant if it is `Unevaluated` and creates a ConstValue if the
235     /// evaluation succeeds. If it doesn't succeed, returns the unevaluated constant.
236     pub fn eval_for_mir(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> ConstantKind<'tcx> {
237         if let Some(val) = self.kind().try_eval_for_mir(tcx, param_env) {
238             match val {
239                 Ok(const_val) => ConstantKind::from_value(const_val, self.ty()),
240                 Err(guar) => ConstantKind::Ty(tcx.const_error_with_guaranteed(self.ty(), guar)),
241             }
242         } else {
243             ConstantKind::Ty(self)
244         }
245     }
246
247     #[inline]
248     /// Panics if the value cannot be evaluated or doesn't contain a valid integer of the given type.
249     pub fn eval_bits(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, ty: Ty<'tcx>) -> u128 {
250         self.try_eval_bits(tcx, param_env, ty)
251             .unwrap_or_else(|| bug!("expected bits of {:#?}, got {:#?}", ty, self))
252     }
253
254     #[inline]
255     /// Panics if the value cannot be evaluated or doesn't contain a valid `usize`.
256     pub fn eval_usize(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> u64 {
257         self.try_eval_usize(tcx, param_env)
258             .unwrap_or_else(|| bug!("expected usize, got {:#?}", self))
259     }
260
261     pub fn is_ct_infer(self) -> bool {
262         matches!(self.kind(), ty::ConstKind::Infer(_))
263     }
264 }
265
266 pub fn const_param_default<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Const<'tcx> {
267     let default_def_id = match tcx.hir().get_by_def_id(def_id.expect_local()) {
268         hir::Node::GenericParam(hir::GenericParam {
269             kind: hir::GenericParamKind::Const { default: Some(ac), .. },
270             ..
271         }) => ac.def_id,
272         _ => span_bug!(
273             tcx.def_span(def_id),
274             "`const_param_default` expected a generic parameter with a constant"
275         ),
276     };
277     Const::from_anon_const(tcx, default_def_id)
278 }