Skip to content

An unsafe const fn being used to compute an array length or const generic is incorrectly described as being an "item". #133441

Open
@theemathas

Description

Code

const unsafe fn foo() -> usize { 1 }

fn main() {
    unsafe {
        let _x = [0; foo()];
    }
}

Current output

Compiling playground v0.0.1 (/playground)
warning: unnecessary `unsafe` block
 --> src/main.rs:4:5
  |
4 |     unsafe {
  |     ^^^^^^ unnecessary `unsafe` block
  |
  = note: `#[warn(unused_unsafe)]` on by default

error[E0133]: call to unsafe function `foo` is unsafe and requires unsafe function or block
 --> src/main.rs:5:22
  |
4 |     unsafe {
  |     ------ items do not inherit unsafety from separate enclosing items
5 |         let _x = [0; foo()];
  |                      ^^^^^ call to unsafe function
  |
  = note: consult the function's documentation for information on how to avoid undefined behavior

For more information about this error, try `rustc --explain E0133`.
warning: `playground` (bin "playground") generated 1 warning
error: could not compile `playground` (bin "playground") due to 1 previous error; 1 warning emitted

Desired output

Say something other than "items do not inherit unsafety from separate enclosing items"

Rationale and extra context

Given that unsafe blocks apply "through" closures, I find it a bit weird that it doesn't apply through array lengths or const generics. Maybe this is fine, but at the very least, the error message should not describe the problem as being about "items", since there aren't any relevant items in sight.

Other cases

Other similar cases with similar errors:

const unsafe fn foo() -> usize { 1 }

fn main() {
    unsafe {
        <[i32; foo()]>::default();
    }
}
const unsafe fn foo() -> usize { 1 }

fn lol<const N: usize>() {}

fn main() {
    unsafe {
        lol::<{foo()}>();
    }
}
const unsafe fn foo() -> usize { 1 }

struct Thing<const N: usize>;

fn main() {
    unsafe {
        let _x: Thing<{foo()}>;
    }
}

Rust Version

Reproducible on the playground with stable rust version 1.82.0, and nightly rust version `1.85.0-nightly (2024-11-22 a47555110cf09b3ed598)`

Anything else?

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsI-lang-nominatedNominated for discussion during a lang team meeting.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team, which will review and decide on the PR/issue.T-typesRelevant to the types 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