]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/consts.rs
Rollup merge of #92825 - pierwill:rustc-version-force-rename, r=Mark-Simulacrum
[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 body_id = match tcx.hir().get_by_def_id(def.did) {
46             hir::Node::AnonConst(ac) => ac.body,
47             _ => span_bug!(
48                 tcx.def_span(def.did.to_def_id()),
49                 "from_anon_const can only process anonymous constants"
50             ),
51         };
52
53         let expr = &tcx.hir().body(body_id).value;
54
55         let ty = tcx.type_of(def.def_id_for_type_of());
56
57         match Self::try_eval_lit_or_param(tcx, ty, expr) {
58             Some(v) => v,
59             None => tcx.mk_const(ty::Const {
60                 val: ty::ConstKind::Unevaluated(ty::Unevaluated {
61                     def: def.to_global(),
62                     substs: InternalSubsts::identity_for_item(tcx, def.did.to_def_id()),
63                     promoted: None,
64                 }),
65                 ty,
66             }),
67         }
68     }
69
70     fn try_eval_lit_or_param(
71         tcx: TyCtxt<'tcx>,
72         ty: Ty<'tcx>,
73         expr: &'tcx hir::Expr<'tcx>,
74     ) -> Option<&'tcx Self> {
75         let lit_input = match expr.kind {
76             hir::ExprKind::Lit(ref lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: false }),
77             hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => match expr.kind {
78                 hir::ExprKind::Lit(ref lit) => {
79                     Some(LitToConstInput { lit: &lit.node, ty, neg: true })
80                 }
81                 _ => None,
82             },
83             _ => None,
84         };
85
86         if let Some(lit_input) = lit_input {
87             // If an error occurred, ignore that it's a literal and leave reporting the error up to
88             // mir.
89             if let Ok(c) = tcx.at(expr.span).lit_to_const(lit_input) {
90                 return Some(c);
91             } else {
92                 tcx.sess.delay_span_bug(expr.span, "Const::from_anon_const: couldn't lit_to_const");
93             }
94         }
95
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         use hir::{def::DefKind::ConstParam, def::Res, ExprKind, Path, QPath};
106         match expr.kind {
107             ExprKind::Path(QPath::Resolved(_, &Path { res: Res::Def(ConstParam, def_id), .. })) => {
108                 // Find the name and index of the const parameter by indexing the generics of
109                 // the parent item and construct a `ParamConst`.
110                 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
111                 let item_id = tcx.hir().get_parent_node(hir_id);
112                 let item_def_id = tcx.hir().local_def_id(item_id);
113                 let generics = tcx.generics_of(item_def_id.to_def_id());
114                 let index = generics.param_def_id_to_index[&def_id];
115                 let name = tcx.hir().name(hir_id);
116                 Some(tcx.mk_const(ty::Const {
117                     val: ty::ConstKind::Param(ty::ParamConst::new(index, name)),
118                     ty,
119                 }))
120             }
121             _ => None,
122         }
123     }
124
125     pub fn from_inline_const(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx Self {
126         debug!("Const::from_inline_const(def_id={:?})", def_id);
127
128         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
129
130         let body_id = match tcx.hir().get(hir_id) {
131             hir::Node::AnonConst(ac) => ac.body,
132             _ => span_bug!(
133                 tcx.def_span(def_id.to_def_id()),
134                 "from_inline_const can only process anonymous constants"
135             ),
136         };
137
138         let expr = &tcx.hir().body(body_id).value;
139
140         let ty = tcx.typeck(def_id).node_type(hir_id);
141
142         let ret = match Self::try_eval_lit_or_param(tcx, ty, expr) {
143             Some(v) => v,
144             None => {
145                 let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id());
146                 let parent_substs =
147                     tcx.erase_regions(InternalSubsts::identity_for_item(tcx, typeck_root_def_id));
148                 let substs =
149                     InlineConstSubsts::new(tcx, InlineConstSubstsParts { parent_substs, ty })
150                         .substs;
151                 tcx.mk_const(ty::Const {
152                     val: ty::ConstKind::Unevaluated(ty::Unevaluated {
153                         def: ty::WithOptConstParam::unknown(def_id).to_global(),
154                         substs,
155                         promoted: None,
156                     }),
157                     ty,
158                 })
159             }
160         };
161         debug_assert!(!ret.has_free_regions());
162         ret
163     }
164
165     /// Interns the given value as a constant.
166     #[inline]
167     pub fn from_value(tcx: TyCtxt<'tcx>, val: ConstValue<'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
168         tcx.mk_const(Self { val: ConstKind::Value(val), ty })
169     }
170
171     #[inline]
172     /// Interns the given scalar as a constant.
173     pub fn from_scalar(tcx: TyCtxt<'tcx>, val: Scalar, ty: Ty<'tcx>) -> &'tcx Self {
174         Self::from_value(tcx, ConstValue::Scalar(val), ty)
175     }
176
177     #[inline]
178     /// Creates a constant with the given integer value and interns it.
179     pub fn from_bits(tcx: TyCtxt<'tcx>, bits: u128, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> &'tcx Self {
180         let size = tcx
181             .layout_of(ty)
182             .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
183             .size;
184         Self::from_scalar(tcx, Scalar::from_uint(bits, size), ty.value)
185     }
186
187     #[inline]
188     /// Creates an interned zst constant.
189     pub fn zero_sized(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
190         Self::from_scalar(tcx, Scalar::ZST, ty)
191     }
192
193     #[inline]
194     /// Creates an interned bool constant.
195     pub fn from_bool(tcx: TyCtxt<'tcx>, v: bool) -> &'tcx Self {
196         Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool))
197     }
198
199     #[inline]
200     /// Creates an interned usize constant.
201     pub fn from_usize(tcx: TyCtxt<'tcx>, n: u64) -> &'tcx Self {
202         Self::from_bits(tcx, n as u128, ParamEnv::empty().and(tcx.types.usize))
203     }
204
205     #[inline]
206     /// Attempts to evaluate the given constant to bits. Can fail to evaluate in the presence of
207     /// generics (or erroneous code) or if the value can't be represented as bits (e.g. because it
208     /// contains const generic parameters or pointers).
209     pub fn try_eval_bits(
210         &self,
211         tcx: TyCtxt<'tcx>,
212         param_env: ParamEnv<'tcx>,
213         ty: Ty<'tcx>,
214     ) -> Option<u128> {
215         assert_eq!(self.ty, ty);
216         let size = tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
217         // if `ty` does not depend on generic parameters, use an empty param_env
218         self.val.eval(tcx, param_env).try_to_bits(size)
219     }
220
221     #[inline]
222     pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<bool> {
223         self.val.eval(tcx, param_env).try_to_bool()
224     }
225
226     #[inline]
227     pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<u64> {
228         self.val.eval(tcx, param_env).try_to_machine_usize(tcx)
229     }
230
231     #[inline]
232     /// Tries to evaluate the constant if it is `Unevaluated`. If that doesn't succeed, return the
233     /// unevaluated constant.
234     pub fn eval(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> &Const<'tcx> {
235         if let Some(val) = self.val.try_eval(tcx, param_env) {
236             match val {
237                 Ok(val) => Const::from_value(tcx, val, self.ty),
238                 Err(ErrorReported) => tcx.const_error(self.ty),
239             }
240         } else {
241             self
242         }
243     }
244
245     #[inline]
246     /// Panics if the value cannot be evaluated or doesn't contain a valid integer of the given type.
247     pub fn eval_bits(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, ty: Ty<'tcx>) -> u128 {
248         self.try_eval_bits(tcx, param_env, ty)
249             .unwrap_or_else(|| bug!("expected bits of {:#?}, got {:#?}", ty, self))
250     }
251
252     #[inline]
253     /// Panics if the value cannot be evaluated or doesn't contain a valid `usize`.
254     pub fn eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> u64 {
255         self.try_eval_usize(tcx, param_env)
256             .unwrap_or_else(|| bug!("expected usize, got {:#?}", self))
257     }
258 }
259
260 pub fn const_param_default<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Const<'tcx> {
261     let default_def_id = match tcx.hir().get_by_def_id(def_id.expect_local()) {
262         hir::Node::GenericParam(hir::GenericParam {
263             kind: hir::GenericParamKind::Const { ty: _, default: Some(ac) },
264             ..
265         }) => tcx.hir().local_def_id(ac.hir_id),
266         _ => span_bug!(
267             tcx.def_span(def_id),
268             "`const_param_default` expected a generic parameter with a constant"
269         ),
270     };
271     Const::from_anon_const(tcx, default_def_id)
272 }