rustc_middle/mir/interpret/
value.rs1use std::fmt;
2use std::num::NonZero;
3
4use either::{Either, Left, Right};
5use rustc_abi::{HasDataLayout, Size};
6use rustc_apfloat::Float;
7use rustc_apfloat::ieee::{Double, Half, Quad, Single};
8use rustc_macros::{StableHash, TyDecodable, TyEncodable};
9use rustc_span::bug;
10
11use super::{
12 AllocId, CtfeProvenance, InterpResult, Pointer, PointerArithmetic, Provenance, interp_ok,
13};
14use crate::ty::ScalarInt;
15
16#[derive(#[automatically_derived]
impl<Prov: ::core::clone::Clone> ::core::clone::Clone for Scalar<Prov> {
#[inline]
fn clone(&self) -> Self {
match self {
Self::Int(__self_0) =>
Self::Int(::core::clone::Clone::clone(__self_0)),
Self::Ptr(__self_0, __self_1) =>
Self::Ptr(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
}
}
}Clone, #[automatically_derived]
impl<Prov: ::core::marker::Copy> ::core::marker::Copy for Scalar<Prov> { }Copy, #[automatically_derived]
impl<Prov: ::core::cmp::Eq> ::core::cmp::Eq for Scalar<Prov> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ScalarInt>;
let _: ::core::cmp::AssertParamIsEq<Pointer<Prov>>;
let _: ::core::cmp::AssertParamIsEq<NonZero<u8>>;
}
}Eq, #[automatically_derived]
impl<Prov: ::core::cmp::PartialEq> ::core::marker::StructuralPartialEq for
Scalar<Prov> {
}
#[automatically_derived]
impl<Prov: ::core::cmp::PartialEq> ::core::cmp::PartialEq for Scalar<Prov> {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Int(__self_0), Self::Int(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Ptr(__self_0, __self_1), Self::Ptr(__arg1_0, __arg1_1))
=> __self_0 == __arg1_0 && __self_1 == __arg1_1,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, const _: () =
{
impl<'tcx, Prov, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
::rustc_serialize::Encodable<__E> for Scalar<Prov> where
Pointer<Prov>: ::rustc_serialize::Encodable<__E> {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
Scalar::Int(ref __binding_0) => { 0usize }
Scalar::Ptr(ref __binding_0, ref __binding_1) => { 1usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
Scalar::Int(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
Scalar::Ptr(ref __binding_0, ref __binding_1) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
}
}
};TyEncodable, const _: () =
{
impl<'tcx, Prov, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
::rustc_serialize::Decodable<__D> for Scalar<Prov> where
Pointer<Prov>: ::rustc_serialize::Decodable<__D> {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => {
Scalar::Int(::rustc_serialize::Decodable::decode(__decoder))
}
1usize => {
Scalar::Ptr(::rustc_serialize::Decodable::decode(__decoder),
::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Scalar`, expected 0..2, actual {0}",
n));
}
}
}
}
};TyDecodable, #[automatically_derived]
impl<Prov: ::core::hash::Hash> ::core::hash::Hash for Scalar<Prov> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state);
match self {
Self::Int(__self_0) => ::core::hash::Hash::hash(__self_0, state),
Self::Ptr(__self_0, __self_1) => {
::core::hash::Hash::hash(__self_0, state);
::core::hash::Hash::hash(__self_1, state)
}
}
}
}Hash)]
24#[derive(const _: () =
{
impl<Prov> ::rustc_data_structures::stable_hash::StableHash for
Scalar<Prov> where
Prov: ::rustc_data_structures::stable_hash::StableHash {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
Scalar::Int(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
Scalar::Ptr(ref __binding_0, ref __binding_1) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
25pub enum Scalar<Prov = CtfeProvenance> {
26 Int(ScalarInt),
28
29 Ptr(Pointer<Prov>, NonZero<u8>),
35}
36
37#[cfg(target_pointer_width = "64")]
38const _: [(); 24] = [(); ::std::mem::size_of::<Scalar>()];rustc_data_structures::static_assert_size!(Scalar, 24);
39
40impl<Prov: Provenance> fmt::Debug for Scalar<Prov> {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 match self {
45 Scalar::Ptr(ptr, _size) => f.write_fmt(format_args!("{0:?}", ptr))write!(f, "{ptr:?}"),
46 Scalar::Int(int) => f.write_fmt(format_args!("{0:?}", int))write!(f, "{int:?}"),
47 }
48 }
49}
50
51impl<Prov: Provenance> fmt::Display for Scalar<Prov> {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 match self {
54 Scalar::Ptr(ptr, _size) => f.write_fmt(format_args!("pointer to {0:?}", ptr))write!(f, "pointer to {ptr:?}"),
55 Scalar::Int(int) => f.write_fmt(format_args!("{0}", int))write!(f, "{int}"),
56 }
57 }
58}
59
60impl<Prov: Provenance> fmt::LowerHex for Scalar<Prov> {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 match self {
63 Scalar::Ptr(ptr, _size) => f.write_fmt(format_args!("pointer to {0:?}", ptr))write!(f, "pointer to {ptr:?}"),
64 Scalar::Int(int) => f.write_fmt(format_args!("{0:#x}", int))write!(f, "{int:#x}"),
65 }
66 }
67}
68
69impl<Prov> From<Half> for Scalar<Prov> {
70 #[inline(always)]
71 fn from(f: Half) -> Self {
72 Scalar::from_f16(f)
73 }
74}
75
76impl<Prov> From<Single> for Scalar<Prov> {
77 #[inline(always)]
78 fn from(f: Single) -> Self {
79 Scalar::from_f32(f)
80 }
81}
82
83impl<Prov> From<Double> for Scalar<Prov> {
84 #[inline(always)]
85 fn from(f: Double) -> Self {
86 Scalar::from_f64(f)
87 }
88}
89
90impl<Prov> From<Quad> for Scalar<Prov> {
91 #[inline(always)]
92 fn from(f: Quad) -> Self {
93 Scalar::from_f128(f)
94 }
95}
96
97impl<Prov> From<ScalarInt> for Scalar<Prov> {
98 #[inline(always)]
99 fn from(ptr: ScalarInt) -> Self {
100 Scalar::Int(ptr)
101 }
102}
103
104impl<Prov> Scalar<Prov> {
105 #[inline(always)]
106 pub fn from_pointer(ptr: Pointer<Prov>, cx: &impl HasDataLayout) -> Self {
107 let ptr_size = u8::try_from(cx.pointer_size().bytes()).ok().and_then(NonZero::new).unwrap();
108 Scalar::Ptr(ptr, ptr_size)
109 }
110
111 pub fn from_maybe_pointer(ptr: Pointer<Option<Prov>>, cx: &impl HasDataLayout) -> Self {
114 match ptr.into_raw_parts() {
115 (Some(prov), offset) => Scalar::from_pointer(Pointer::new(prov, offset), cx),
116 (None, offset) => {
117 Scalar::Int(ScalarInt::try_from_uint(offset.bytes(), cx.pointer_size()).unwrap())
118 }
119 }
120 }
121
122 #[inline]
123 pub fn null_ptr(cx: &impl HasDataLayout) -> Self {
124 Scalar::Int(ScalarInt::null(cx.pointer_size()))
125 }
126
127 #[inline]
128 pub fn from_bool(b: bool) -> Self {
129 Scalar::Int(b.into())
130 }
131
132 #[inline]
133 pub fn from_char(c: char) -> Self {
134 Scalar::Int(c.into())
135 }
136
137 #[inline]
138 pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
139 let i = i.into();
140 ScalarInt::try_from_uint(i, size)
141 .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
format_args!("Unsigned value {0:#x} does not fit in {1} bits", i,
size.bits()), Location::caller())bug!("Unsigned value {:#x} does not fit in {} bits", i, size.bits()))
142 .into()
143 }
144
145 #[inline]
146 pub fn from_u8(i: u8) -> Self {
147 Scalar::Int(i.into())
148 }
149
150 #[inline]
151 pub fn from_u16(i: u16) -> Self {
152 Scalar::Int(i.into())
153 }
154
155 #[inline]
156 pub fn from_u32(i: u32) -> Self {
157 Scalar::Int(i.into())
158 }
159
160 #[inline]
161 pub fn from_u64(i: u64) -> Self {
162 Scalar::Int(i.into())
163 }
164
165 #[inline]
166 pub fn from_u128(i: u128) -> Self {
167 Scalar::Int(i.into())
168 }
169
170 #[inline]
171 pub fn from_target_usize(i: u64, cx: &impl HasDataLayout) -> Self {
172 Self::from_uint(i, cx.data_layout().pointer_offset())
173 }
174
175 #[inline]
176 pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
177 let i = i.into();
178 ScalarInt::try_from_int(i, size)
179 .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
format_args!("Signed value {0:#x} does not fit in {1} bits", i,
size.bits()), Location::caller())bug!("Signed value {:#x} does not fit in {} bits", i, size.bits()))
180 .into()
181 }
182
183 #[inline]
184 pub fn from_i8(i: i8) -> Self {
185 Self::Int(i.into())
186 }
187
188 #[inline]
189 pub fn from_i16(i: i16) -> Self {
190 Self::Int(i.into())
191 }
192
193 #[inline]
194 pub fn from_i32(i: i32) -> Self {
195 Self::Int(i.into())
196 }
197
198 #[inline]
199 pub fn from_i64(i: i64) -> Self {
200 Self::Int(i.into())
201 }
202
203 #[inline]
204 pub fn from_i128(i: i128) -> Self {
205 Self::Int(i.into())
206 }
207
208 #[inline]
209 pub fn from_target_isize(i: i64, cx: &impl HasDataLayout) -> Self {
210 Self::from_int(i, cx.data_layout().pointer_offset())
211 }
212
213 #[inline]
214 pub fn from_f16(f: Half) -> Self {
215 Scalar::Int(f.into())
216 }
217
218 #[inline]
219 pub fn from_f32(f: Single) -> Self {
220 Scalar::Int(f.into())
221 }
222
223 #[inline]
224 pub fn from_f64(f: Double) -> Self {
225 Scalar::Int(f.into())
226 }
227
228 #[inline]
229 pub fn from_f128(f: Quad) -> Self {
230 Scalar::Int(f.into())
231 }
232
233 #[inline]
242 pub fn to_bits_or_ptr_internal(self, expected_size: Size) -> Either<u128, Pointer<Prov>> {
243 match self {
244 Scalar::Int(int) => Left(int.to_bits(expected_size)),
245 Scalar::Ptr(ptr, sz) => {
246 let self_size = u64::from(sz.get());
247 if expected_size.bytes() != self_size {
248 #[cold]
249 fn invalid(expected_size: u64, self_size: u64) -> ! {
250 {
::core::panicking::panic_fmt(format_args!("Scalar pointer has size {0} but expected {1}",
self_size, expected_size));
}panic!("Scalar pointer has size {self_size} but expected {expected_size}")
251 }
252
253 invalid(expected_size.bytes(), self_size)
254 }
255
256 Right(ptr)
257 }
258 }
259 }
260
261 #[inline]
262 pub fn size(self) -> Size {
263 match self {
264 Scalar::Int(int) => int.size(),
265 Scalar::Ptr(_ptr, sz) => Size::from_bytes(sz.get()),
266 }
267 }
268}
269
270impl<'tcx, Prov: Provenance> Scalar<Prov> {
271 pub fn to_pointer(self, cx: &impl HasDataLayout) -> Pointer<Option<Prov>> {
272 match self.to_bits_or_ptr_internal(cx.pointer_size()) {
273 Right(ptr) => ptr.into(),
274 Left(bits) => {
275 let addr = u64::try_from(bits).unwrap();
276 Pointer::without_provenance(addr)
277 }
278 }
279 }
280
281 #[inline]
291 pub fn try_to_scalar_int(self) -> Result<ScalarInt, Scalar<AllocId>> {
292 match self {
293 Scalar::Int(int) => Ok(int),
294 Scalar::Ptr(ptr, sz) => {
295 if Prov::OFFSET_IS_ADDR {
296 Ok(ScalarInt::try_from_uint(ptr.offset.bytes(), Size::from_bytes(sz.get()))
297 .unwrap())
298 } else {
299 let (prov, offset) = ptr.into_raw_parts();
301 Err(Scalar::Ptr(Pointer::new(prov.get_alloc_id().unwrap(), offset), sz))
303 }
304 }
305 }
306 }
307
308 pub fn clear_provenance(&mut self) -> InterpResult<'tcx> {
309 if #[allow(non_exhaustive_omitted_patterns)] match self {
Scalar::Ptr(..) => true,
_ => false,
}matches!(self, Scalar::Ptr(..)) {
310 *self = self.to_scalar_int()?.into();
311 }
312 interp_ok(())
313 }
314
315 #[inline(always)]
316 pub fn to_scalar_int(self) -> InterpResult<'tcx, ScalarInt> {
317 self.try_to_scalar_int().map_err(|_| crate::mir::interpret::InterpErrorKind::Unsupported(crate::mir::interpret::UnsupportedOpInfo::ReadPointerAsInt(None))err_unsup!(ReadPointerAsInt(None))).into()
318 }
319
320 #[inline(always)]
321 #[cfg_attr(debug_assertions, track_caller)] pub fn assert_scalar_int(self) -> ScalarInt {
323 self.try_to_scalar_int().expect("got a pointer where a ScalarInt was expected")
324 }
325
326 #[inline]
329 pub fn to_bits(self, target_size: Size) -> InterpResult<'tcx, u128> {
330 {
match (&(target_size.bytes()), &(0)) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("you should never look at the bits of a ZST")));
}
}
}
};assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST");
331 interp_ok(self.to_scalar_int()?.to_bits(target_size))
332 }
333
334 pub fn to_bool(self) -> InterpResult<'tcx, bool> {
335 let val = self.to_u8()?;
336 match val {
337 0 => interp_ok(false),
338 1 => interp_ok(true),
339 _ => do yeet crate::mir::interpret::InterpErrorKind::UndefinedBehavior(crate::mir::interpret::UndefinedBehaviorInfo::InvalidBool(val))throw_ub!(InvalidBool(val)),
340 }
341 }
342
343 pub fn to_char(self) -> InterpResult<'tcx, char> {
344 let val = self.to_u32()?;
345 match std::char::from_u32(val) {
346 Some(c) => interp_ok(c),
347 None => do yeet crate::mir::interpret::InterpErrorKind::UndefinedBehavior(crate::mir::interpret::UndefinedBehaviorInfo::InvalidChar(val))throw_ub!(InvalidChar(val)),
348 }
349 }
350
351 #[inline]
354 pub fn to_uint(self, size: Size) -> InterpResult<'tcx, u128> {
355 self.to_bits(size)
356 }
357
358 pub fn to_u8(self) -> InterpResult<'tcx, u8> {
360 self.to_uint(Size::from_bits(8)).map(|v| u8::try_from(v).unwrap())
361 }
362
363 pub fn to_u16(self) -> InterpResult<'tcx, u16> {
365 self.to_uint(Size::from_bits(16)).map(|v| u16::try_from(v).unwrap())
366 }
367
368 pub fn to_u32(self) -> InterpResult<'tcx, u32> {
370 self.to_uint(Size::from_bits(32)).map(|v| u32::try_from(v).unwrap())
371 }
372
373 pub fn to_u64(self) -> InterpResult<'tcx, u64> {
375 self.to_uint(Size::from_bits(64)).map(|v| u64::try_from(v).unwrap())
376 }
377
378 pub fn to_u128(self) -> InterpResult<'tcx, u128> {
380 self.to_uint(Size::from_bits(128))
381 }
382
383 pub fn to_target_usize(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
386 let b = self.to_uint(cx.data_layout().pointer_size())?;
387 interp_ok(u64::try_from(b).unwrap())
388 }
389
390 #[inline]
393 pub fn to_int(self, size: Size) -> InterpResult<'tcx, i128> {
394 let b = self.to_bits(size)?;
395 interp_ok(size.sign_extend(b))
396 }
397
398 pub fn to_i8(self) -> InterpResult<'tcx, i8> {
400 self.to_int(Size::from_bits(8)).map(|v| i8::try_from(v).unwrap())
401 }
402
403 pub fn to_i16(self) -> InterpResult<'tcx, i16> {
405 self.to_int(Size::from_bits(16)).map(|v| i16::try_from(v).unwrap())
406 }
407
408 pub fn to_i32(self) -> InterpResult<'tcx, i32> {
410 self.to_int(Size::from_bits(32)).map(|v| i32::try_from(v).unwrap())
411 }
412
413 pub fn to_i64(self) -> InterpResult<'tcx, i64> {
415 self.to_int(Size::from_bits(64)).map(|v| i64::try_from(v).unwrap())
416 }
417
418 pub fn to_i128(self) -> InterpResult<'tcx, i128> {
420 self.to_int(Size::from_bits(128))
421 }
422
423 pub fn to_target_isize(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, i64> {
426 let b = self.to_int(cx.data_layout().pointer_size())?;
427 interp_ok(i64::try_from(b).unwrap())
428 }
429
430 #[inline]
431 pub fn to_float<F: Float>(self) -> InterpResult<'tcx, F> {
432 interp_ok(F::from_bits(self.to_bits(Size::from_bits(F::BITS))?))
434 }
435
436 #[inline]
437 pub fn to_f16(self) -> InterpResult<'tcx, Half> {
438 self.to_float()
439 }
440
441 #[inline]
442 pub fn to_f32(self) -> InterpResult<'tcx, Single> {
443 self.to_float()
444 }
445
446 #[inline]
447 pub fn to_f64(self) -> InterpResult<'tcx, Double> {
448 self.to_float()
449 }
450
451 #[inline]
452 pub fn to_f128(self) -> InterpResult<'tcx, Quad> {
453 self.to_float()
454 }
455}