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