]> git.lizzy.rs Git - rust.git/blob - tests/ui/consts/invalid-union.rs
Rollup merge of #107058 - clubby789:eqeq-homoglyph, r=wesleywiser
[rust.git] / tests / ui / consts / invalid-union.rs
1 // Check that constants with interior mutability inside unions are rejected
2 // during validation.
3 //
4 // Note that this test case relies on undefined behaviour to construct a
5 // constant with interior mutability that is "invisible" to the static checks.
6 // If for some reason this approach no longer works, it is should be fine to
7 // remove the test case.
8 //
9 // build-fail
10 // stderr-per-bitwidth
11 #![feature(const_mut_refs)]
12
13 use std::cell::Cell;
14 use std::mem::ManuallyDrop;
15
16 #[repr(C)]
17 struct S {
18     x: u32,
19     y: E,
20 }
21
22 #[repr(u32)]
23 enum E {
24     A,
25     B(U)
26 }
27
28 union U {
29     cell: ManuallyDrop<Cell<u32>>,
30 }
31
32 const C: S = {
33     let s = S { x: 0, y: E::A };
34     // Go through an &u32 reference which is definitely not allowed to mutate anything.
35     let p = &s.x as *const u32 as *mut u32;
36     // Change enum tag to E::B.
37     unsafe { *p.add(1) = 1 };
38     s
39 };
40
41 fn main() { //~ ERROR it is undefined behavior to use this value
42     // FIXME the span here is wrong, sould be pointing at the line below, not above.
43     let _: &'static _ = &C;
44 }