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