Learn Rust the Dangerous Way
I’ve had an idea for a while now, of writing a tutorial that works similar to this one, but backwards. I have no time to write the tutorial, but here’s the idea:<p>Behind the scenes, write a short C program, and compile it into LLVM IR through Clang. Present the code first as its LLVM IR representation, then work through how you’d manually <i>decompile</i> it back into C, hopefully giving a result that will compile back to the same LLVM IR.<p>(You’d be teaching some of the fundamentals of compiler theory here, in “reverse order”, but IMHO that’s exactly what you need if you’re to understand where C and Rust really diverge.)<p>Then, walk through the decompilation process again, except this time with Rust semantics, to end up with <i>unsafe</i> Rust that compiles to identical LLVM IR as the C code does.<p>And then, finally, treating the unsafe Rust as the new IR, walk through how you’d decompile that unsafe Rust into safe Rust, introducing each static-analysis compiler pass that Rust does in reverse, adding one feature at a time, until the code is all safe Rust, but can be theoretically partial-compiled into the earlier unsafe-Rust code†, and from there into the same LLVM IR as the other two examples.<p>The idea here is that this tutorial would be a way of “reading history backwards” (ala <a href="https://slatestarcodex.com/2013/04/11/read-history-of-philosophy-backwards/" rel="nofollow">https://slatestarcodex.com/2013/04/11/read-history-of-philos...</a>). I.e., rather than coming into a world with a fully-formed Rust and a fully-formed C, you’d start with a world that only has ASM; and then introduce C into it; and then introduce Rust into it, seeing how each introduction changes what you can do.<p>† It’d be helpful if rustc had a mode where it could emit some sort of “core Rust” IR, that was all unsafe{} and had only the barest types, in the vein of early C++ compilers that emit C, or how the Erlang compiler works. Sadly, I don’t think rustc is architected in a way that’d allow this. (Though, paging steveklabnik to correct me.)