Introduction
I just want to suggest this here first and discuss it with you before starting to write a full RFC for that.
We all know that there is this little dangerous keyword named unsafe.
Officially unsafe means something like:
I, the programmer who wrote this have looked at every single aspect of this code and I am 120% sure that this is working as it should and will don’t introduce any memory unsafety or similar problems.
After having read this thread, I am sure that there is a whole lot of work before us to get this thinking into peoples minds.
For the lazy ones, the particular code in question is the following (have a look at the lifetimes):
fn fast_str(v: &[u8]) -> &'static str {
let x: &str = unsafe { mem::transmute(v) };
x
}
The Change
Behaviour
What I want is that the Rust compiler itself reminds the programmer to look at what they’ve done and question their own code.
Every time you write an unsafe-block or function, the compiler asks you to:
- read the above definition of
unsafe
- look at the code again
- should probably also print the following checklist
- is there any existing solution
- are your lifetimes correct
- is there a possible memory leak
- is the unsafe even needed
- to be expanded
- write a summary comment for why this
unsafe is needed and what the code within does
- only ask for that if there is no comment there yet
- write the comment directly into the source code
- the checksum of your unsafe block is calculated
- this checksum is written right after the comment inserted in step #3
- if needed, overwrites old checksum
These steps are only gone through if you are either
- missing the comment
- the checksum is missing or has changed
These steps are needed to compile the code.
Result
This has the following consequences:
- new users not used to Rust are immediately introduced in what it does
- new unsafe blocks are not silently introduced
- all unsafe blocks are commented so you can look up what they are actually doing
- encourages people to refrain from using it if possible
- experienced programmers still write comments for those parts
- experienced programmers are encouraged to check their code
- unsafe code is (most likely) not accidentally modified
Heads Up
The programmer does not need to do anything if:
- there is no change of code
Review
This might be a good or a bad idea, I don’t know, so please help me to work this out a bit more so it is enough for an RFC to be proposed.