]> git.lizzy.rs Git - rust.git/blob - src/test/ui/consts/const-float-bits-reject-conv.rs
Add test for presence of read more links
[rust.git] / src / test / ui / consts / const-float-bits-reject-conv.rs
1 // compile-flags: -Zmir-opt-level=0
2 // error-pattern: cannot use f32::to_bits on a NaN
3 #![feature(const_float_bits_conv)]
4 #![feature(const_float_classify)]
5
6 // Don't promote
7 const fn nop<T>(x: T) -> T { x }
8
9 macro_rules! const_assert {
10     ($a:expr) => {
11         {
12             const _: () = assert!($a);
13             assert!(nop($a));
14         }
15     };
16     ($a:expr, $b:expr) => {
17         {
18             const _: () = assert!($a == $b);
19             assert_eq!(nop($a), nop($b));
20         }
21     };
22 }
23
24 fn f32() {
25     // Check that NaNs roundtrip their bits regardless of signalingness
26     // 0xA is 0b1010; 0x5 is 0b0101 -- so these two together clobbers all the mantissa bits
27     // ...actually, let's just check that these break. :D
28     const MASKED_NAN1: u32 = f32::NAN.to_bits() ^ 0x002A_AAAA;
29     //~^ inside
30     const MASKED_NAN2: u32 = f32::NAN.to_bits() ^ 0x0055_5555;
31     //~^ inside
32
33     // The rest of the code is dead because the constants already fail to evaluate.
34
35     const_assert!(f32::from_bits(MASKED_NAN1).is_nan());
36     const_assert!(f32::from_bits(MASKED_NAN1).is_nan());
37
38     // LLVM does not guarantee that loads and stores of NaNs preserve their exact bit pattern.
39     // In practice, this seems to only cause a problem on x86, since the most widely used calling
40     // convention mandates that floating point values are returned on the x87 FPU stack. See #73328.
41     // However, during CTFE we still preserve bit patterns (though that is not a guarantee).
42     const_assert!(f32::from_bits(MASKED_NAN1).to_bits(), MASKED_NAN1);
43     const_assert!(f32::from_bits(MASKED_NAN2).to_bits(), MASKED_NAN2);
44 }
45
46 fn f64() {
47     // Check that NaNs roundtrip their bits regardless of signalingness
48     // 0xA is 0b1010; 0x5 is 0b0101 -- so these two together clobbers all the mantissa bits
49     // ...actually, let's just check that these break. :D
50     const MASKED_NAN1: u64 = f64::NAN.to_bits() ^ 0x000A_AAAA_AAAA_AAAA;
51     //~^ inside
52     const MASKED_NAN2: u64 = f64::NAN.to_bits() ^ 0x0005_5555_5555_5555;
53     //~^ inside
54
55     // The rest of the code is dead because the constants already fail to evaluate.
56
57     const_assert!(f64::from_bits(MASKED_NAN1).is_nan());
58     const_assert!(f64::from_bits(MASKED_NAN1).is_nan());
59
60     // See comment above.
61     const_assert!(f64::from_bits(MASKED_NAN1).to_bits(), MASKED_NAN1);
62     const_assert!(f64::from_bits(MASKED_NAN2).to_bits(), MASKED_NAN2);
63 }
64
65 fn main() {
66     f32();
67     f64();
68 }