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