Get the latest tech news
Crafting Interpreters with Rust: On Garbage Collection
I became interested in implementing programming languages a few years ago and discovered [Crafting Interpreters](https://craftinginterpreters.com/) by Bob Nystrom. At the time, I had experience with Rust and decided to use it to follow the book. Albeit, being a noob, I managed to implement a fully functional bytecode interpreter that supported every feature of the Lox language as described. However, my implementation suffered memory leaks due to reference counting. Back then, I didn't fully grasp Rust to design and implement a proper garbage collector (GC)! Now that I have more confidence in the language, I decided to revisit the project and improve its memory management scheme.
The resulting type Rc<RefCell<T>> provides exactly what we need, a shared mutable reference to a heap-allocated value that gets free automatically when it’s no longer referenced. However, there’s no way for a Lox program to specify to the VM that it wants to use a weak pointer, and we don’t even want to expose such functionality due to the high-level nature of the language. An intriguing approach I want to try at some point is utilizing Pin<T> and carefully weaving the lifetime of rooted objects through our program to prove they’re safe for access.
Or read this on Hacker News