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