]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/consts/int.rs
Rollup merge of #101330 - wkordalski:hashset-drain-doc, r=jyn514
[rust.git] / compiler / rustc_middle / src / ty / consts / int.rs
1 use rustc_apfloat::ieee::{Double, Single};
2 use rustc_apfloat::Float;
3 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
4 use rustc_target::abi::Size;
5 use std::convert::{TryFrom, TryInto};
6 use std::fmt;
7 use std::num::NonZeroU8;
8
9 use crate::ty::TyCtxt;
10
11 #[derive(Copy, Clone)]
12 /// A type for representing any integer. Only used for printing.
13 pub struct ConstInt {
14     /// The "untyped" variant of `ConstInt`.
15     int: ScalarInt,
16     /// Whether the value is of a signed integer type.
17     signed: bool,
18     /// Whether the value is a `usize` or `isize` type.
19     is_ptr_sized_integral: bool,
20 }
21
22 impl ConstInt {
23     pub fn new(int: ScalarInt, signed: bool, is_ptr_sized_integral: bool) -> Self {
24         Self { int, signed, is_ptr_sized_integral }
25     }
26 }
27
28 impl std::fmt::Debug for ConstInt {
29     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30         let Self { int, signed, is_ptr_sized_integral } = *self;
31         let size = int.size().bytes();
32         let raw = int.data;
33         if signed {
34             let bit_size = size * 8;
35             let min = 1u128 << (bit_size - 1);
36             let max = min - 1;
37             if raw == min {
38                 match (size, is_ptr_sized_integral) {
39                     (_, true) => write!(fmt, "isize::MIN"),
40                     (1, _) => write!(fmt, "i8::MIN"),
41                     (2, _) => write!(fmt, "i16::MIN"),
42                     (4, _) => write!(fmt, "i32::MIN"),
43                     (8, _) => write!(fmt, "i64::MIN"),
44                     (16, _) => write!(fmt, "i128::MIN"),
45                     _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed),
46                 }
47             } else if raw == max {
48                 match (size, is_ptr_sized_integral) {
49                     (_, true) => write!(fmt, "isize::MAX"),
50                     (1, _) => write!(fmt, "i8::MAX"),
51                     (2, _) => write!(fmt, "i16::MAX"),
52                     (4, _) => write!(fmt, "i32::MAX"),
53                     (8, _) => write!(fmt, "i64::MAX"),
54                     (16, _) => write!(fmt, "i128::MAX"),
55                     _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed),
56                 }
57             } else {
58                 match size {
59                     1 => write!(fmt, "{}", raw as i8)?,
60                     2 => write!(fmt, "{}", raw as i16)?,
61                     4 => write!(fmt, "{}", raw as i32)?,
62                     8 => write!(fmt, "{}", raw as i64)?,
63                     16 => write!(fmt, "{}", raw as i128)?,
64                     _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed),
65                 }
66                 if fmt.alternate() {
67                     match (size, is_ptr_sized_integral) {
68                         (_, true) => write!(fmt, "_isize")?,
69                         (1, _) => write!(fmt, "_i8")?,
70                         (2, _) => write!(fmt, "_i16")?,
71                         (4, _) => write!(fmt, "_i32")?,
72                         (8, _) => write!(fmt, "_i64")?,
73                         (16, _) => write!(fmt, "_i128")?,
74                         _ => bug!(),
75                     }
76                 }
77                 Ok(())
78             }
79         } else {
80             let max = Size::from_bytes(size).truncate(u128::MAX);
81             if raw == max {
82                 match (size, is_ptr_sized_integral) {
83                     (_, true) => write!(fmt, "usize::MAX"),
84                     (1, _) => write!(fmt, "u8::MAX"),
85                     (2, _) => write!(fmt, "u16::MAX"),
86                     (4, _) => write!(fmt, "u32::MAX"),
87                     (8, _) => write!(fmt, "u64::MAX"),
88                     (16, _) => write!(fmt, "u128::MAX"),
89                     _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed),
90                 }
91             } else {
92                 match size {
93                     1 => write!(fmt, "{}", raw as u8)?,
94                     2 => write!(fmt, "{}", raw as u16)?,
95                     4 => write!(fmt, "{}", raw as u32)?,
96                     8 => write!(fmt, "{}", raw as u64)?,
97                     16 => write!(fmt, "{}", raw as u128)?,
98                     _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed),
99                 }
100                 if fmt.alternate() {
101                     match (size, is_ptr_sized_integral) {
102                         (_, true) => write!(fmt, "_usize")?,
103                         (1, _) => write!(fmt, "_u8")?,
104                         (2, _) => write!(fmt, "_u16")?,
105                         (4, _) => write!(fmt, "_u32")?,
106                         (8, _) => write!(fmt, "_u64")?,
107                         (16, _) => write!(fmt, "_u128")?,
108                         _ => bug!(),
109                     }
110                 }
111                 Ok(())
112             }
113         }
114     }
115 }
116
117 /// The raw bytes of a simple value.
118 ///
119 /// This is a packed struct in order to allow this type to be optimally embedded in enums
120 /// (like Scalar).
121 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
122 #[repr(packed)]
123 pub struct ScalarInt {
124     /// The first `size` bytes of `data` are the value.
125     /// Do not try to read less or more bytes than that. The remaining bytes must be 0.
126     data: u128,
127     size: NonZeroU8,
128 }
129
130 // Cannot derive these, as the derives take references to the fields, and we
131 // can't take references to fields of packed structs.
132 impl<CTX> crate::ty::HashStable<CTX> for ScalarInt {
133     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut crate::ty::StableHasher) {
134         // Using a block `{self.data}` here to force a copy instead of using `self.data`
135         // directly, because `hash_stable` takes `&self` and would thus borrow `self.data`.
136         // Since `Self` is a packed struct, that would create a possibly unaligned reference,
137         // which is UB.
138         { self.data }.hash_stable(hcx, hasher);
139         self.size.get().hash_stable(hcx, hasher);
140     }
141 }
142
143 impl<S: Encoder> Encodable<S> for ScalarInt {
144     fn encode(&self, s: &mut S) {
145         s.emit_u128(self.data);
146         s.emit_u8(self.size.get());
147     }
148 }
149
150 impl<D: Decoder> Decodable<D> for ScalarInt {
151     fn decode(d: &mut D) -> ScalarInt {
152         ScalarInt { data: d.read_u128(), size: NonZeroU8::new(d.read_u8()).unwrap() }
153     }
154 }
155
156 impl ScalarInt {
157     pub const TRUE: ScalarInt = ScalarInt { data: 1_u128, size: NonZeroU8::new(1).unwrap() };
158
159     pub const FALSE: ScalarInt = ScalarInt { data: 0_u128, size: NonZeroU8::new(1).unwrap() };
160
161     #[inline]
162     pub fn size(self) -> Size {
163         Size::from_bytes(self.size.get())
164     }
165
166     /// Make sure the `data` fits in `size`.
167     /// This is guaranteed by all constructors here, but having had this check saved us from
168     /// bugs many times in the past, so keeping it around is definitely worth it.
169     #[inline(always)]
170     fn check_data(self) {
171         // Using a block `{self.data}` here to force a copy instead of using `self.data`
172         // directly, because `debug_assert_eq` takes references to its arguments and formatting
173         // arguments and would thus borrow `self.data`. Since `Self`
174         // is a packed struct, that would create a possibly unaligned reference, which
175         // is UB.
176         debug_assert_eq!(
177             self.size().truncate(self.data),
178             { self.data },
179             "Scalar value {:#x} exceeds size of {} bytes",
180             { self.data },
181             self.size
182         );
183     }
184
185     #[inline]
186     pub fn null(size: Size) -> Self {
187         Self { data: 0, size: NonZeroU8::new(size.bytes() as u8).unwrap() }
188     }
189
190     #[inline]
191     pub fn is_null(self) -> bool {
192         self.data == 0
193     }
194
195     #[inline]
196     pub fn try_from_uint(i: impl Into<u128>, size: Size) -> Option<Self> {
197         let data = i.into();
198         if size.truncate(data) == data {
199             Some(Self { data, size: NonZeroU8::new(size.bytes() as u8).unwrap() })
200         } else {
201             None
202         }
203     }
204
205     #[inline]
206     pub fn try_from_int(i: impl Into<i128>, size: Size) -> Option<Self> {
207         let i = i.into();
208         // `into` performed sign extension, we have to truncate
209         let truncated = size.truncate(i as u128);
210         if size.sign_extend(truncated) as i128 == i {
211             Some(Self { data: truncated, size: NonZeroU8::new(size.bytes() as u8).unwrap() })
212         } else {
213             None
214         }
215     }
216
217     #[inline]
218     pub fn assert_bits(self, target_size: Size) -> u128 {
219         self.to_bits(target_size).unwrap_or_else(|size| {
220             bug!("expected int of size {}, but got size {}", target_size.bytes(), size.bytes())
221         })
222     }
223
224     #[inline]
225     pub fn to_bits(self, target_size: Size) -> Result<u128, Size> {
226         assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST");
227         if target_size.bytes() == u64::from(self.size.get()) {
228             self.check_data();
229             Ok(self.data)
230         } else {
231             Err(self.size())
232         }
233     }
234
235     #[inline]
236     pub fn try_to_machine_usize<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Result<u64, Size> {
237         Ok(self.to_bits(tcx.data_layout.pointer_size)? as u64)
238     }
239
240     /// Tries to convert the `ScalarInt` to an unsigned integer of the given size.
241     /// Fails if the size of the `ScalarInt` is unequal to `size` and returns the
242     /// `ScalarInt`s size in that case.
243     #[inline]
244     pub fn try_to_uint(self, size: Size) -> Result<u128, Size> {
245         self.to_bits(size)
246     }
247
248     // Tries to convert the `ScalarInt` to `u8`. Fails if the `size` of the `ScalarInt`
249     // in not equal to `Size { raw: 1 }` and returns the `size` value of the `ScalarInt` in
250     // that case.
251     #[inline]
252     pub fn try_to_u8(self) -> Result<u8, Size> {
253         self.to_bits(Size::from_bits(8)).map(|v| u8::try_from(v).unwrap())
254     }
255
256     /// Tries to convert the `ScalarInt` to `u16`. Fails if the size of the `ScalarInt`
257     /// in not equal to `Size { raw: 2 }` and returns the `size` value of the `ScalarInt` in
258     /// that case.
259     #[inline]
260     pub fn try_to_u16(self) -> Result<u16, Size> {
261         self.to_bits(Size::from_bits(16)).map(|v| u16::try_from(v).unwrap())
262     }
263
264     /// Tries to convert the `ScalarInt` to `u32`. Fails if the `size` of the `ScalarInt`
265     /// in not equal to `Size { raw: 4 }` and returns the `size` value of the `ScalarInt` in
266     /// that case.
267     #[inline]
268     pub fn try_to_u32(self) -> Result<u32, Size> {
269         self.to_bits(Size::from_bits(32)).map(|v| u32::try_from(v).unwrap())
270     }
271
272     /// Tries to convert the `ScalarInt` to `u64`. Fails if the `size` of the `ScalarInt`
273     /// in not equal to `Size { raw: 8 }` and returns the `size` value of the `ScalarInt` in
274     /// that case.
275     #[inline]
276     pub fn try_to_u64(self) -> Result<u64, Size> {
277         self.to_bits(Size::from_bits(64)).map(|v| u64::try_from(v).unwrap())
278     }
279
280     /// Tries to convert the `ScalarInt` to `u128`. Fails if the `size` of the `ScalarInt`
281     /// in not equal to `Size { raw: 16 }` and returns the `size` value of the `ScalarInt` in
282     /// that case.
283     #[inline]
284     pub fn try_to_u128(self) -> Result<u128, Size> {
285         self.to_bits(Size::from_bits(128))
286     }
287
288     /// Tries to convert the `ScalarInt` to a signed integer of the given size.
289     /// Fails if the size of the `ScalarInt` is unequal to `size` and returns the
290     /// `ScalarInt`s size in that case.
291     #[inline]
292     pub fn try_to_int(self, size: Size) -> Result<i128, Size> {
293         let b = self.to_bits(size)?;
294         Ok(size.sign_extend(b) as i128)
295     }
296
297     /// Tries to convert the `ScalarInt` to i8.
298     /// Fails if the size of the `ScalarInt` is unequal to `Size { raw: 1 }`
299     /// and returns the `ScalarInt`s size in that case.
300     pub fn try_to_i8(self) -> Result<i8, Size> {
301         self.try_to_int(Size::from_bits(8)).map(|v| i8::try_from(v).unwrap())
302     }
303
304     /// Tries to convert the `ScalarInt` to i16.
305     /// Fails if the size of the `ScalarInt` is unequal to `Size { raw: 2 }`
306     /// and returns the `ScalarInt`s size in that case.
307     pub fn try_to_i16(self) -> Result<i16, Size> {
308         self.try_to_int(Size::from_bits(16)).map(|v| i16::try_from(v).unwrap())
309     }
310
311     /// Tries to convert the `ScalarInt` to i32.
312     /// Fails if the size of the `ScalarInt` is unequal to `Size { raw: 4 }`
313     /// and returns the `ScalarInt`s size in that case.
314     pub fn try_to_i32(self) -> Result<i32, Size> {
315         self.try_to_int(Size::from_bits(32)).map(|v| i32::try_from(v).unwrap())
316     }
317
318     /// Tries to convert the `ScalarInt` to i64.
319     /// Fails if the size of the `ScalarInt` is unequal to `Size { raw: 8 }`
320     /// and returns the `ScalarInt`s size in that case.
321     pub fn try_to_i64(self) -> Result<i64, Size> {
322         self.try_to_int(Size::from_bits(64)).map(|v| i64::try_from(v).unwrap())
323     }
324
325     /// Tries to convert the `ScalarInt` to i128.
326     /// Fails if the size of the `ScalarInt` is unequal to `Size { raw: 16 }`
327     /// and returns the `ScalarInt`s size in that case.
328     pub fn try_to_i128(self) -> Result<i128, Size> {
329         self.try_to_int(Size::from_bits(128)).map(|v| i128::try_from(v).unwrap())
330     }
331 }
332
333 macro_rules! from {
334     ($($ty:ty),*) => {
335         $(
336             impl From<$ty> for ScalarInt {
337                 #[inline]
338                 fn from(u: $ty) -> Self {
339                     Self {
340                         data: u128::from(u),
341                         size: NonZeroU8::new(std::mem::size_of::<$ty>() as u8).unwrap(),
342                     }
343                 }
344             }
345         )*
346     }
347 }
348
349 macro_rules! try_from {
350     ($($ty:ty),*) => {
351         $(
352             impl TryFrom<ScalarInt> for $ty {
353                 type Error = Size;
354                 #[inline]
355                 fn try_from(int: ScalarInt) -> Result<Self, Size> {
356                     // The `unwrap` cannot fail because to_bits (if it succeeds)
357                     // is guaranteed to return a value that fits into the size.
358                     int.to_bits(Size::from_bytes(std::mem::size_of::<$ty>()))
359                        .map(|u| u.try_into().unwrap())
360                 }
361             }
362         )*
363     }
364 }
365
366 from!(u8, u16, u32, u64, u128, bool);
367 try_from!(u8, u16, u32, u64, u128);
368
369 impl TryFrom<ScalarInt> for bool {
370     type Error = Size;
371     #[inline]
372     fn try_from(int: ScalarInt) -> Result<Self, Size> {
373         int.to_bits(Size::from_bytes(1)).and_then(|u| match u {
374             0 => Ok(false),
375             1 => Ok(true),
376             _ => Err(Size::from_bytes(1)),
377         })
378     }
379 }
380
381 impl From<char> for ScalarInt {
382     #[inline]
383     fn from(c: char) -> Self {
384         Self { data: c as u128, size: NonZeroU8::new(std::mem::size_of::<char>() as u8).unwrap() }
385     }
386 }
387
388 /// Error returned when a conversion from ScalarInt to char fails.
389 #[derive(Debug)]
390 pub struct CharTryFromScalarInt;
391
392 impl TryFrom<ScalarInt> for char {
393     type Error = CharTryFromScalarInt;
394
395     #[inline]
396     fn try_from(int: ScalarInt) -> Result<Self, Self::Error> {
397         let Ok(bits) = int.to_bits(Size::from_bytes(std::mem::size_of::<char>())) else  {
398             return Err(CharTryFromScalarInt);
399         };
400         match char::from_u32(bits.try_into().unwrap()) {
401             Some(c) => Ok(c),
402             None => Err(CharTryFromScalarInt),
403         }
404     }
405 }
406
407 impl From<Single> for ScalarInt {
408     #[inline]
409     fn from(f: Single) -> Self {
410         // We trust apfloat to give us properly truncated data.
411         Self { data: f.to_bits(), size: NonZeroU8::new((Single::BITS / 8) as u8).unwrap() }
412     }
413 }
414
415 impl TryFrom<ScalarInt> for Single {
416     type Error = Size;
417     #[inline]
418     fn try_from(int: ScalarInt) -> Result<Self, Size> {
419         int.to_bits(Size::from_bytes(4)).map(Self::from_bits)
420     }
421 }
422
423 impl From<Double> for ScalarInt {
424     #[inline]
425     fn from(f: Double) -> Self {
426         // We trust apfloat to give us properly truncated data.
427         Self { data: f.to_bits(), size: NonZeroU8::new((Double::BITS / 8) as u8).unwrap() }
428     }
429 }
430
431 impl TryFrom<ScalarInt> for Double {
432     type Error = Size;
433     #[inline]
434     fn try_from(int: ScalarInt) -> Result<Self, Size> {
435         int.to_bits(Size::from_bytes(8)).map(Self::from_bits)
436     }
437 }
438
439 impl fmt::Debug for ScalarInt {
440     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441         // Dispatch to LowerHex below.
442         write!(f, "0x{:x}", self)
443     }
444 }
445
446 impl fmt::LowerHex for ScalarInt {
447     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
448         self.check_data();
449         if f.alternate() {
450             // Like regular ints, alternate flag adds leading `0x`.
451             write!(f, "0x")?;
452         }
453         // Format as hex number wide enough to fit any value of the given `size`.
454         // So data=20, size=1 will be "0x14", but with size=4 it'll be "0x00000014".
455         // Using a block `{self.data}` here to force a copy instead of using `self.data`
456         // directly, because `write!` takes references to its formatting arguments and
457         // would thus borrow `self.data`. Since `Self`
458         // is a packed struct, that would create a possibly unaligned reference, which
459         // is UB.
460         write!(f, "{:01$x}", { self.data }, self.size.get() as usize * 2)
461     }
462 }
463
464 impl fmt::UpperHex for ScalarInt {
465     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466         self.check_data();
467         // Format as hex number wide enough to fit any value of the given `size`.
468         // So data=20, size=1 will be "0x14", but with size=4 it'll be "0x00000014".
469         // Using a block `{self.data}` here to force a copy instead of using `self.data`
470         // directly, because `write!` takes references to its formatting arguments and
471         // would thus borrow `self.data`. Since `Self`
472         // is a packed struct, that would create a possibly unaligned reference, which
473         // is UB.
474         write!(f, "{:01$X}", { self.data }, self.size.get() as usize * 2)
475     }
476 }
477
478 impl fmt::Display for ScalarInt {
479     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480         self.check_data();
481         write!(f, "{}", { self.data })
482     }
483 }