-
Notifications
You must be signed in to change notification settings - Fork 13.9k
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 fnfunctions insideconst fnfunctions inside anunsafe { ... }block. - Calling
const unsafe fnfunctions insideconst unsafe fnfunctions.
Non-exhaustive lists of things that don't become allowed with #![feature(min_const_unsafe_fn)]:
-
Callingconst unsafe fnfunctions directly inside otherconst unsafe fnfunctions.
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 fnandfn. 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::transmuteor other functions that can't be written asconst unsafe fnin 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]
unionfield access insideconst fn#51909. -
Casting raw pointers to integers
-
Taking references to fields of packed structs
-
accessing
extern statics
Things to be done before stabilizing:
- Implement the
min_const_unsafe_fnfeature gate. (Allow callingconst unsafe fninconst fnbehind 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.