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