From cd7204ef394d1e53bb967086186e9b8664d7e268 Mon Sep 17 00:00:00 2001 From: Yuki Okushi Date: Tue, 4 Aug 2020 17:46:10 +0900 Subject: [PATCH] Forbid non-derefable types explicitly in unsizing casts --- src/librustc_mir/transform/qualify_min_const_fn.rs | 10 +++++++++- src/test/ui/consts/unsizing-cast-non-null.rs | 10 ++++++++++ src/test/ui/consts/unsizing-cast-non-null.stderr | 12 ++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 src/test/ui/consts/unsizing-cast-non-null.rs create mode 100644 src/test/ui/consts/unsizing-cast-non-null.stderr diff --git a/src/librustc_mir/transform/qualify_min_const_fn.rs b/src/librustc_mir/transform/qualify_min_const_fn.rs index de7d7f27186f2..34fa840408f79 100644 --- a/src/librustc_mir/transform/qualify_min_const_fn.rs +++ b/src/librustc_mir/transform/qualify_min_const_fn.rs @@ -193,7 +193,15 @@ fn check_rvalue( _, ) => Err((span, "function pointer casts are not allowed in const fn".into())), Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), op, cast_ty) => { - let pointee_ty = cast_ty.builtin_deref(true).unwrap().ty; + let pointee_ty = if let Some(deref_ty) = cast_ty.builtin_deref(true) { + deref_ty.ty + } else { + // We cannot allow this for now. + return Err(( + span, + "unsizing casts are only allowed for references right now".into(), + )); + }; let unsized_ty = tcx.struct_tail_erasing_lifetimes(pointee_ty, tcx.param_env(def_id)); if let ty::Slice(_) | ty::Str = unsized_ty.kind { check_operand(tcx, op, span, def_id, body)?; diff --git a/src/test/ui/consts/unsizing-cast-non-null.rs b/src/test/ui/consts/unsizing-cast-non-null.rs new file mode 100644 index 0000000000000..67d9f6baca5b4 --- /dev/null +++ b/src/test/ui/consts/unsizing-cast-non-null.rs @@ -0,0 +1,10 @@ +// Regression test for #75118. + +use std::ptr::NonNull; + +pub const fn dangling_slice() -> NonNull<[T]> { + NonNull::<[T; 0]>::dangling() + //~^ ERROR: unsizing casts are only allowed for references right now +} + +fn main() {} diff --git a/src/test/ui/consts/unsizing-cast-non-null.stderr b/src/test/ui/consts/unsizing-cast-non-null.stderr new file mode 100644 index 0000000000000..6575355daadd7 --- /dev/null +++ b/src/test/ui/consts/unsizing-cast-non-null.stderr @@ -0,0 +1,12 @@ +error[E0723]: unsizing casts are only allowed for references right now + --> $DIR/unsizing-cast-non-null.rs:6:5 + | +LL | NonNull::<[T; 0]>::dangling() + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #57563 for more information + = help: add `#![feature(const_fn)]` to the crate attributes to enable + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0723`.