Skip to content

Commit

Permalink
Auto merge of #79621 - usbalbin:constier_maybe_uninit, r=RalfJung
Browse files Browse the repository at this point in the history
Constier maybe uninit

I was playing around trying to make `[T; N]::zip()` in #79451 be `const fn`. One of the things I bumped into was `MaybeUninit::assume_init`. Is there any reason for the intrinsic `assert_inhabited<T>()` and therefore `MaybeUninit::assume_init` not being `const`?

---

I have as best as I could tried to follow the instruction in [library/core/src/intrinsics.rs](https://github.com/rust-lang/rust/blob/master/library/core/src/intrinsics.rs#L11). I have no idea what I am doing but it seems to compile after some slight changes after the copy paste. Is this anywhere near how this should be done?

Also any ideas for name of the feature gate? I guess `const_maybe_assume_init` is quite misleading since I have added some more methods. Should I add test? If so what should be tested?
  • Loading branch information
bors committed Dec 10, 2020
2 parents e413d89 + 0775271 commit 39b841d
Show file tree
Hide file tree
Showing 12 changed files with 87 additions and 14 deletions.
2 changes: 2 additions & 0 deletions compiler/rustc_mir/src/const_eval/error.rs
Expand Up @@ -20,6 +20,7 @@ pub enum ConstEvalErrKind {
ModifiedGlobal,
AssertFailure(AssertKind<ConstInt>),
Panic { msg: Symbol, line: u32, col: u32, file: Symbol },
Abort(String),
}

// The errors become `MachineStop` with plain strings when being raised.
Expand All @@ -46,6 +47,7 @@ impl fmt::Display for ConstEvalErrKind {
Panic { msg, line, col, file } => {
write!(f, "the evaluated program panicked at '{}', {}:{}:{}", msg, file, line, col)
}
Abort(ref msg) => write!(f, "{}", msg),
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_mir/src/const_eval/machine.rs
Expand Up @@ -384,6 +384,10 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir,
Err(ConstEvalErrKind::AssertFailure(err).into())
}

fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
Err(ConstEvalErrKind::Abort(msg).into())
}

fn ptr_to_int(_mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer) -> InterpResult<'tcx, u64> {
Err(ConstEvalErrKind::NeedsRfc("pointer-to-integer cast".to_string()).into())
}
Expand Down
12 changes: 11 additions & 1 deletion compiler/rustc_mir/src/interpret/intrinsics.rs
Expand Up @@ -126,7 +126,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
None => match intrinsic_name {
sym::transmute => throw_ub_format!("transmuting to uninhabited type"),
sym::unreachable => throw_ub!(Unreachable),
sym::abort => M::abort(self)?,
sym::abort => M::abort(self, "the program aborted execution".to_owned())?,
// Unsupported diverging intrinsic.
_ => return Ok(false),
},
Expand Down Expand Up @@ -407,6 +407,16 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
sym::transmute => {
self.copy_op_transmute(args[0], dest)?;
}
sym::assert_inhabited => {
let ty = instance.substs.type_at(0);
let layout = self.layout_of(ty)?;

if layout.abi.is_uninhabited() {
// The run-time intrinsic panics just to get a good backtrace; here we abort
// since there is no problem showing a backtrace even for aborts.
M::abort(self, format!("attempted to instantiate uninhabited type `{}`", ty))?;
}
}
sym::simd_insert => {
let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
let elem = args[2];
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir/src/interpret/machine.rs
Expand Up @@ -176,7 +176,7 @@ pub trait Machine<'mir, 'tcx>: Sized {
) -> InterpResult<'tcx>;

/// Called to evaluate `Abort` MIR terminator.
fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx, !> {
fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, _msg: String) -> InterpResult<'tcx, !> {
throw_unsup_format!("aborting execution is not supported")
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir/src/interpret/terminator.rs
Expand Up @@ -110,7 +110,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
}

Abort => {
M::abort(self)?;
M::abort(self, "the program aborted execution".to_owned())?;
}

// When we encounter Resume, we've finished unwinding
Expand Down
1 change: 1 addition & 0 deletions library/core/src/intrinsics.rs
Expand Up @@ -815,6 +815,7 @@ extern "rust-intrinsic" {
/// This will statically either panic, or do nothing.
///
/// This intrinsic does not have a stable counterpart.
#[rustc_const_unstable(feature = "const_assert_type", issue = "none")]
pub fn assert_inhabited<T>();

/// A guard for unsafe functions that cannot ever be executed if `T` does not permit
Expand Down
4 changes: 4 additions & 0 deletions library/core/src/lib.rs
Expand Up @@ -70,6 +70,7 @@
#![feature(cfg_target_has_atomic)]
#![cfg_attr(not(bootstrap), feature(const_heap))]
#![feature(const_alloc_layout)]
#![feature(const_assert_type)]
#![feature(const_discriminant)]
#![feature(const_cell_into_inner)]
#![feature(const_checked_int_methods)]
Expand All @@ -93,6 +94,7 @@
#![feature(const_ptr_offset)]
#![feature(const_ptr_offset_from)]
#![feature(const_raw_ptr_comparison)]
#![feature(const_raw_ptr_deref)]
#![feature(const_slice_from_raw_parts)]
#![feature(const_slice_ptr_len)]
#![feature(const_size_of_val)]
Expand All @@ -101,6 +103,8 @@
#![feature(const_type_name)]
#![feature(const_likely)]
#![feature(const_unreachable_unchecked)]
#![feature(const_maybe_uninit_assume_init)]
#![feature(const_maybe_uninit_as_ptr)]
#![feature(custom_inner_attributes)]
#![feature(decl_macro)]
#![feature(doc_cfg)]
Expand Down
31 changes: 20 additions & 11 deletions library/core/src/mem/maybe_uninit.rs
Expand Up @@ -314,8 +314,9 @@ impl<T> MaybeUninit<T> {
/// let data = read(&mut buf);
/// ```
#[unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
#[rustc_const_unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
#[inline(always)]
pub fn uninit_array<const LEN: usize>() -> [Self; LEN] {
pub const fn uninit_array<const LEN: usize>() -> [Self; LEN] {
// SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.
unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
}
Expand Down Expand Up @@ -372,8 +373,9 @@ impl<T> MaybeUninit<T> {
/// skip running the destructor. For your convenience, this also returns a mutable
/// reference to the (now safely initialized) contents of `self`.
#[unstable(feature = "maybe_uninit_extra", issue = "63567")]
#[rustc_const_unstable(feature = "maybe_uninit_extra", issue = "63567")]
#[inline(always)]
pub fn write(&mut self, val: T) -> &mut T {
pub const fn write(&mut self, val: T) -> &mut T {
*self = MaybeUninit::new(val);
// SAFETY: We just initialized this value.
unsafe { self.assume_init_mut() }
Expand Down Expand Up @@ -503,9 +505,10 @@ impl<T> MaybeUninit<T> {
/// // `x` had not been initialized yet, so this last line caused undefined behavior. ⚠️
/// ```
#[stable(feature = "maybe_uninit", since = "1.36.0")]
#[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
#[inline(always)]
#[rustc_diagnostic_item = "assume_init"]
pub unsafe fn assume_init(self) -> T {
pub const unsafe fn assume_init(self) -> T {
// SAFETY: the caller must guarantee that `self` is initialized.
// This also means that `self` must be a `value` variant.
unsafe {
Expand Down Expand Up @@ -666,13 +669,14 @@ impl<T> MaybeUninit<T> {
/// }
/// ```
#[unstable(feature = "maybe_uninit_ref", issue = "63568")]
#[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
#[inline(always)]
pub unsafe fn assume_init_ref(&self) -> &T {
pub const unsafe fn assume_init_ref(&self) -> &T {
// SAFETY: the caller must guarantee that `self` is initialized.
// This also means that `self` must be a `value` variant.
unsafe {
intrinsics::assert_inhabited::<T>();
&*self.value
&*self.as_ptr()
}
}

Expand Down Expand Up @@ -788,13 +792,14 @@ impl<T> MaybeUninit<T> {
// to uninitialized data (e.g., in `libcore/fmt/float.rs`). We should make
// a final decision about the rules before stabilization.
#[unstable(feature = "maybe_uninit_ref", issue = "63568")]
#[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
#[inline(always)]
pub unsafe fn assume_init_mut(&mut self) -> &mut T {
pub const unsafe fn assume_init_mut(&mut self) -> &mut T {
// SAFETY: the caller must guarantee that `self` is initialized.
// This also means that `self` must be a `value` variant.
unsafe {
intrinsics::assert_inhabited::<T>();
&mut *self.value
&mut *self.as_mut_ptr()
}
}

Expand All @@ -810,8 +815,9 @@ impl<T> MaybeUninit<T> {
///
/// [`assume_init_ref`]: MaybeUninit::assume_init_ref
#[unstable(feature = "maybe_uninit_slice", issue = "63569")]
#[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
#[inline(always)]
pub unsafe fn slice_assume_init_ref(slice: &[Self]) -> &[T] {
pub const unsafe fn slice_assume_init_ref(slice: &[Self]) -> &[T] {
// SAFETY: casting slice to a `*const [T]` is safe since the caller guarantees that
// `slice` is initialized, and`MaybeUninit` is guaranteed to have the same layout as `T`.
// The pointer obtained is valid since it refers to memory owned by `slice` which is a
Expand All @@ -831,24 +837,27 @@ impl<T> MaybeUninit<T> {
///
/// [`assume_init_mut`]: MaybeUninit::assume_init_mut
#[unstable(feature = "maybe_uninit_slice", issue = "63569")]
#[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
#[inline(always)]
pub unsafe fn slice_assume_init_mut(slice: &mut [Self]) -> &mut [T] {
pub const unsafe fn slice_assume_init_mut(slice: &mut [Self]) -> &mut [T] {
// SAFETY: similar to safety notes for `slice_get_ref`, but we have a
// mutable reference which is also guaranteed to be valid for writes.
unsafe { &mut *(slice as *mut [Self] as *mut [T]) }
}

/// Gets a pointer to the first element of the array.
#[unstable(feature = "maybe_uninit_slice", issue = "63569")]
#[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
#[inline(always)]
pub fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T {
pub const fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T {
this.as_ptr() as *const T
}

/// Gets a mutable pointer to the first element of the array.
#[unstable(feature = "maybe_uninit_slice", issue = "63569")]
#[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
#[inline(always)]
pub fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T {
pub const fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T {
this.as_mut_ptr() as *mut T
}
}
1 change: 1 addition & 0 deletions library/core/tests/lib.rs
Expand Up @@ -11,6 +11,7 @@
#![feature(cfg_target_has_atomic)]
#![feature(const_assume)]
#![feature(const_cell_into_inner)]
#![feature(const_maybe_uninit_assume_init)]
#![feature(core_intrinsics)]
#![feature(core_private_bignum)]
#![feature(core_private_diy_float)]
Expand Down
8 changes: 8 additions & 0 deletions library/core/tests/mem.rs
Expand Up @@ -129,3 +129,11 @@ fn test_discriminant_send_sync() {
is_send_sync::<Discriminant<Regular>>();
is_send_sync::<Discriminant<NotSendSync>>();
}

#[test]
#[cfg(not(bootstrap))]
fn assume_init_good() {
const TRUE: bool = unsafe { MaybeUninit::<bool>::new(true).assume_init() };

assert!(TRUE);
}
13 changes: 13 additions & 0 deletions src/test/ui/assume-type-intrinsics.rs
@@ -0,0 +1,13 @@
// error-pattern: any use of this value will cause an error

#![feature(never_type)]
#![feature(const_maybe_uninit_assume_init)]

#[allow(invalid_value)]
fn main() {
use std::mem::MaybeUninit;

const _BAD: () = unsafe {
MaybeUninit::<!>::uninit().assume_init();
};
}
21 changes: 21 additions & 0 deletions src/test/ui/assume-type-intrinsics.stderr
@@ -0,0 +1,21 @@
error: any use of this value will cause an error
--> $SRC_DIR/core/src/mem/maybe_uninit.rs:LL:COL
|
LL | intrinsics::assert_inhabited::<T>();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| attempted to instantiate uninhabited type `!`
| inside `MaybeUninit::<!>::assume_init` at $SRC_DIR/core/src/mem/maybe_uninit.rs:LL:COL
| inside `_BAD` at $DIR/assume-type-intrinsics.rs:11:9
|
::: $DIR/assume-type-intrinsics.rs:10:5
|
LL | / const _BAD: () = unsafe {
LL | | MaybeUninit::<!>::uninit().assume_init();
LL | | };
| |______-
|
= note: `#[deny(const_err)]` on by default

error: aborting due to previous error

0 comments on commit 39b841d

Please sign in to comment.