Description
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));
}
}