Skip to content

Add a lint for calling any safe functions at all within an unsafe block #14287

Closed
@bstrie

Description

@bstrie

In today's Rust we warn if your unsafe block contains no unsafe code whatsoever:

fn main() {
    unsafe {
        std::io::println("Hello?");
    }
}
un.rs:2:5: 4:6 warning: unnecessary `unsafe` block, #[warn(unused_unsafe)] on by default
un.rs:2     unsafe {
un.rs:3         std::io::println("Hello?");
un.rs:4     }

This is really great. However, the following program produces no warning:

fn main() {
    let x = &["One", "Two", "Three"];
    unsafe {
        std::io::println(*x.unsafe_ref(0));
    }
}

...despite the fact that std::io::println is not an unsafe function. In the interest of reducing the scope of unsafe code, I propose a lint that would warn on the above program. And yes, satisfying it would require uglifying the code like so:

fn main() {
    let x = &["One", "Two", "Three"];
    let y;
    unsafe {
        y = *x.unsafe_ref(0);
    }
    std::io::println(y);
}

...but who ever said that we had an obligation to make unsafe code pretty?


As an alternative, if people find the above proposal to be too extreme, then I would ask them to consider a weaker lint that merely warned if an entire statement within an unsafe block contained no unsafe code. This weaker lint would warn on the following program which compiles without warning today:

fn main() {
    let x = &["One", "Two", "Three"];
    unsafe {
        std::io::println("Hello?");  // warn on this line, if you want a weaker lint
        std::io::println(*x.unsafe_ref(0));
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions