Skip to content

RA thinks unsafe is unnecessary on unsafe match arms when the match is incomplete (missing arms) #15514

Closed
@sam0x17

Description

@sam0x17

rust-analyzer version: 0.3.1631-standalone

rustc version: rustc 1.72.0 (5680fa18f 2023-08-23)

When you have an incomplete match statement (i.e. not covering all pattern variants) and one or more of the arms has unsafe code inside of unsafe { .. } blocks, Rust Analyzer will incorrectly put warnings on each unsafe keyword saying the unsafe block is unnecessary.

This was quite confusing, as when I encountered this, although I was aware my match statement was incomplete and I was in the process of filling in the missing variants, I actually removed the unsafe blocks due to these warnings because I thought "oh, I must be inside an unsafe fn", only to find that once I filled in the missing variants, it wanted the unsafe blocks back.

This toy example reproduces it:

enum MyEnum {
    Red,
    Blue,
    Purple,
    Gray,
    Orange,
}

fn my_fn(input: MyEnum) -> u32 {
    let bytes1 = [1u8, 2u8, 3u8, 4u8];
    let bytes2 = [1u8, 3u8, 3u8, 4u8];
    let bytes3 = [1u8, 2u8, 0u8, 4u8];
    let bytes4 = [1u8, 7u8, 3u8, 4u8];
    match input {
        MyEnum::Red => unsafe { core::mem::transmute_copy(&bytes1) },
        MyEnum::Blue => unsafe { core::mem::transmute_copy(&bytes2) },
        MyEnum::Purple => unsafe { core::mem::transmute_copy(&bytes3) },
        MyEnum::Gray => unsafe { core::mem::transmute_copy(&bytes4) },
    }
}

image

Once you fill in the missing MyEnum::Orange variant, everything will compile and the warnings disappear.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions