]> git.lizzy.rs Git - rust.git/blob - src/test/ui/const-eval/union-ub-fat-ptr.rs
Sanity-check all constants
[rust.git] / src / test / ui / const-eval / union-ub-fat-ptr.rs
1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #[repr(C)]
12 #[derive(Copy, Clone)]
13 struct SliceRepr {
14     ptr: *const u8,
15     len: usize,
16 }
17
18 #[repr(C)]
19 #[derive(Copy, Clone)]
20 struct BadSliceRepr {
21     ptr: *const u8,
22     len: &'static u8,
23 }
24
25 union SliceTransmute {
26     repr: SliceRepr,
27     bad: BadSliceRepr,
28     slice: &'static [u8],
29     str: &'static str,
30 }
31
32 #[repr(C)]
33 #[derive(Copy, Clone)]
34 struct DynRepr {
35     ptr: *const u8,
36     vtable: *const u8,
37 }
38
39 #[repr(C)]
40 #[derive(Copy, Clone)]
41 struct DynRepr2 {
42     ptr: *const u8,
43     vtable: *const u64,
44 }
45
46 #[repr(C)]
47 #[derive(Copy, Clone)]
48 struct BadDynRepr {
49     ptr: *const u8,
50     vtable: usize,
51 }
52
53 union DynTransmute {
54     repr: DynRepr,
55     repr2: DynRepr2,
56     bad: BadDynRepr,
57     rust: &'static Trait,
58 }
59
60 trait Trait {}
61
62 // OK
63 const A: &str = unsafe { SliceTransmute { repr: SliceRepr { ptr: &42, len: 1 } }.str};
64 // should lint
65 const B: &str = unsafe { SliceTransmute { repr: SliceRepr { ptr: &42, len: 999 } }.str};
66 // bad
67 const C: &str = unsafe { SliceTransmute { bad: BadSliceRepr { ptr: &42, len: &3 } }.str};
68 //~^ ERROR this constant likely exhibits undefined behavior
69
70 // OK
71 const A2: &[u8] = unsafe { SliceTransmute { repr: SliceRepr { ptr: &42, len: 1 } }.slice};
72 // should lint
73 const B2: &[u8] = unsafe { SliceTransmute { repr: SliceRepr { ptr: &42, len: 999 } }.slice};
74 // bad
75 const C2: &[u8] = unsafe { SliceTransmute { bad: BadSliceRepr { ptr: &42, len: &3 } }.slice};
76 //~^ ERROR this constant likely exhibits undefined behavior
77
78 // bad
79 const D: &Trait = unsafe { DynTransmute { repr: DynRepr { ptr: &92, vtable: &3 } }.rust};
80 //~^ ERROR this constant likely exhibits undefined behavior
81 // bad
82 const E: &Trait = unsafe { DynTransmute { repr2: DynRepr2 { ptr: &92, vtable: &3 } }.rust};
83 //~^ ERROR this constant likely exhibits undefined behavior
84 // bad
85 const F: &Trait = unsafe { DynTransmute { bad: BadDynRepr { ptr: &92, vtable: 3 } }.rust};
86 //~^ ERROR this constant likely exhibits undefined behavior
87
88 fn main() {
89 }