Mike Burr - log

[rust] Obviating `unsafe`

The [Rustonomicon]https://doc.rust-lang.org/nomicon/) mentions "contracts the compiler can't check". I think I know what this means. And there's a lot of "the user of this function must carefully read the docs and then..."

I wonder what path(s) exist for getting rid of, maybe even piece-wise, maybe in some targeted way (popular, buggy ffi first) that we can formalize this "contract".

It's all bits, so I think the answer is "definitely yes, but".

What if we have code that is unsafe but only in threaded applications? There are lots of things we could do to cleanly handle that now, but what if we could add that idea to "the unsafe interface"?

Instead of just

unsafe { }

we could have, first stab mind you...

unsafe-if cfg!(threaded) { }

Meaning, "this block is unsafe if threading, otherwise it is safe" (it gets compiled either way).

Yes, we could do macros and such. Maybe that's what to do.

"[C]ontracts the compiler can't check" implies the existence of contracts.

What if we implemented this contract-checker in the other language and provided it to the compiler. Stated broadly like that, I can imagine circumstances where this won't work. For one, Rust needs to be able to compile the target language (if it is checking for compilabilaty).

If we are worried about runtime, we could implement this checker somehow in the other language and use it at runtime, returning a Result, maybe. Since we have access to whatever memory and since we can presumably locate it, the "contract checker" part could be written in Rust: It just know what good bit patterns look like.

Could foreign code somehow be annotated with lifetime and/or ownership information and then evaluated by rust before compilationnnn? Yikes.