Skip to content

unsafe blocks do not apply to array length expressions they contain #72359

Open
@ecstatic-morse

Description

@ecstatic-morse

The following example fails to compile on the latest nightly.

#![feature(core_intrinsics)]
#![feature(const_int_unchecked_arith)]

fn main() {
    let _ = unsafe { [0i32; std::intrinsics::unchecked_add(4, 2)] };
}

Output:

warning: unnecessary `unsafe` block
 --> src/main.rs:5:13
  |
5 |     let _ = unsafe { [0i32; std::intrinsics::unchecked_add(4, 2)] };
  |             ^^^^^^ unnecessary `unsafe` block
  |
  = note: `#[warn(unused_unsafe)]` on by default

error[E0133]: call to unsafe function is unsafe and requires unsafe function or block
 --> src/main.rs:5:29
  |
5 |     let _ = unsafe { [0i32; std::intrinsics::unchecked_add(4, 2)] };
  |                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ call to unsafe function
  |
  = note: consult the function's documentation for information on how to avoid undefined behavior

error: aborting due to previous error; 1 warning emitted

I would have expected this to compile successfully, but it seems that unsafe is not applied to array length expressions. The nightly features are only needed because there are no stable const unsafe functions. A user-defined const unsafe fn runs into the same error on stable.

This arose from discussion in rust-lang/rfcs#2920.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-arrayArea: `[T; N]`A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)C-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions