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