rust/src/test/ui/consts/const-eval/ub-ref-ptr.rs

50 lines
2 KiB
Rust
Raw Normal View History

2019-02-22 17:07:13 -05:00
// ignore-tidy-linelength
2019-08-17 13:45:11 +02:00
#![allow(const_err, invalid_value)] // make sure we cannot allow away the errors tested here
2018-06-04 18:32:06 +02:00
use std::mem;
2021-02-16 11:14:34 +01:00
#[repr(C)]
union MaybeUninit<T: Copy> {
uninit: (),
init: T,
}
const UNALIGNED: &u16 = unsafe { mem::transmute(&[0u8; 4]) };
2018-10-01 12:52:47 +02:00
//~^ ERROR it is undefined behavior to use this value
2020-04-16 13:21:23 +02:00
//~| type validation failed: encountered an unaligned reference (required 2 byte alignment but found 1)
2020-03-02 20:52:27 +01:00
const UNALIGNED_BOX: Box<u16> = unsafe { mem::transmute(&[0u8; 4]) };
//~^ ERROR it is undefined behavior to use this value
2020-04-16 13:21:23 +02:00
//~| type validation failed: encountered an unaligned box (required 2 byte alignment but found 1)
2020-03-02 20:52:27 +01:00
const NULL: &u16 = unsafe { mem::transmute(0usize) };
2018-10-01 12:52:47 +02:00
//~^ ERROR it is undefined behavior to use this value
2020-03-02 20:52:27 +01:00
const NULL_BOX: Box<u16> = unsafe { mem::transmute(0usize) };
//~^ ERROR it is undefined behavior to use this value
2019-08-30 09:31:21 +02:00
// It is very important that we reject this: We do promote `&(4 * REF_AS_USIZE)`,
// but that would fail to compile; so we ended up breaking user code that would
// have worked fine had we not promoted.
const REF_AS_USIZE: usize = unsafe { mem::transmute(&0) };
2018-10-01 12:52:47 +02:00
//~^ ERROR it is undefined behavior to use this value
const REF_AS_USIZE_SLICE: &[usize] = &[unsafe { mem::transmute(&0) }];
2018-10-01 12:52:47 +02:00
//~^ ERROR it is undefined behavior to use this value
2020-03-02 20:52:27 +01:00
const REF_AS_USIZE_BOX_SLICE: Box<[usize]> = unsafe { mem::transmute::<&[usize], _>(&[mem::transmute(&0)]) };
//~^ ERROR it is undefined behavior to use this value
const USIZE_AS_REF: &'static u8 = unsafe { mem::transmute(1337usize) };
2018-10-01 12:52:47 +02:00
//~^ ERROR it is undefined behavior to use this value
2018-06-04 18:32:06 +02:00
2020-03-02 20:52:27 +01:00
const USIZE_AS_BOX: Box<u8> = unsafe { mem::transmute(1337usize) };
//~^ ERROR it is undefined behavior to use this value
2021-02-16 11:14:34 +01:00
const UNINIT_PTR: *const i32 = unsafe { MaybeUninit { uninit: () }.init };
//~^ ERROR it is undefined behavior to use this value
const UNINIT_FN_PTR: fn() = unsafe { MaybeUninit { uninit: () }.init };
//~^ ERROR it is undefined behavior to use this value
fn main() {}