Description
This is a tracking issue for the RFC "Const functions and inherent methods" (rust-lang/rfcs#911).
This issue only tracks a subset of the proposal in 911 that we are (hopefully) comfortable with stabilizing. To opt into the minimal subset, use #![feature(min_const_unsafe_fn)]
. To use the more expansive feature set, you can continue using #![feature(const_fn)]
and other associated feature gates.
Currently, while you can write unsafe {}
inside a const fn
/ unsafe const fn
, it is not possible to actually possible to call any unsafe operations inside the block. This makes it impossible to implement safe const fn
abstractions such as Vec::new
. This issue builds upon #53555 by allowing you to use unsafe
operations inside const fn
so that we can make more abstractions const fn
.
Exhaustive list of features supported in const fn
with #![feature(min_const_unsafe_fn)]
:
- Constructing types (e.g.
NonZero
) with#[rustc_layout_scalar_valid_range_start]
becomesunsafe
. This is an internal bug-fix that has no user facing consequences. A motivation is given in Tracking issue for unsafe operations in const fn #55607 (comment) and in Tracking issue for unsafe operations in const fn #55607 (comment). - Calling
const unsafe fn
functions insideconst fn
functions inside anunsafe { ... }
block. - Calling
const unsafe fn
functions insideconst unsafe fn
functions.
Non-exhaustive lists of things that don't become allowed with #![feature(min_const_unsafe_fn)]
:
-
Callingconst unsafe fn
functions directly inside otherconst unsafe fn
functions.
For example:const unsafe fn foo() {} const unsafe fn foo() { bar(); // <-- ERROR! You must write `unsafe { bar(); }`. }
We impose this restriction because @RalfJung has noted that this is not a good thing inunsafe fn
andfn
. Thus, for now, we want to avoid making the situation worse inconst unsafe fn
. We can lift the restriction later if we want to.EDIT: This restriction has been removed.
-
Calling
ptr::read
,mem::transmute
or other functions that can't be written asconst unsafe fn
in user code (see discussion below...). -
Defererencing raw pointers; Tracked in [tracking issue] dereferencing raw pointers inside constants (const_raw_ptr_deref) #51911.
-
Union field accesses; Tracked in [tracking issue]
union
field access insideconst fn
#51909. -
Casting raw pointers to integers
-
Taking references to fields of packed structs
-
accessing
extern static
s
Things to be done before stabilizing:
- Implement the
min_const_unsafe_fn
feature gate. (Allow callingconst unsafe fn
inconst fn
behind a feature gate #55635) - Ensure that the above restrictions apply.
- Adjust documentation (see instructions on forge)
- Stabilization PR (see instructions on forge)
Unresolved questions:
None.
Vocabulary:
cc #24111.