Just curious: how hard would it be to write an interpreter for Rust?

Note that I don't mean a cargo run-like compile-execute like cargo script, nor a Rust-like interpreted language, but rather a full-featured interpreter for today's Rust that behaves as closely as possible to the today's rustc compilation products. There's no real point in doing this, I'm just thinking out of curiosity.
I think it might be difficult, because for a language like Rust that places a high value on the "do more at compile time" philosophy, some of complex compile time features might be hard to implement, or might be implemented in a way that doesn't look like an "interpreter" at all, but at most similar to today's bytecode/VM languages.

If you don't bother doing any type-checking or borrow-checking,you can actually make an interpreter for a complex language pretty quickly, especially for low-performance cases. Semantically speaking, you don't have to do anything at "compile" time if all you care about is preserving the output of already-correct programs (and can let wacky garbage happen for malformed ones).

I seem to have missed that miri is an interpreter!
BTW the textbook-style definitions of "compiler" and "interpreter" have become so blurred today that they sometimes don't even tell any difference.

1 Like

But it's already working on a kind of IR (as the name implies), not source code.

Lifetimes don't need to be implemented in a Rust interpreter, because they don't exist at runtime at all.

But what if they did?

What if variables in the interpreter carried around their status with them? A record of who owns them, their mutability, who has borrowed them, mutably or not, when the go out of scope or otherwise get "terminated". What if the interpreter used that record of a variables status for checking aliasing violations as it ran?

Any reason why not?

Might be horrible slow, but hey, it's an interpreter. Might perform better than a garbage collector.

Miri implements most (if not all) of that. The emphasis is on "don't need to", because this reaction of mine was an answer to OP's assumption that an interpreter would be hard to implement because of lifetimes.

Very few practical interpreters, for any language, work directly on source code, or even on the syntax tree. They usually have some kind of validation and pre-processing before execution begins — it's just not nearly as elaborate as an optimizing compiler.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.