4 ms·
Very interesting. I'm curious how you solved the following interaction, which touches on both Rust's borrow checker and a classic footgun for GC'd languages: Y
by ridiculous_fish 4y ago
Very interesting. I'm curious how you solved the following interaction, which touches on both Rust's borrow checker and a classic footgun for GC'd languages:
You have a GCPtr to some cell on the heap, and you want to dereference the pointer to modify the cell. But the GC also needs to dereference the cell, e.g. to update object references after moving. So while a GCPtr is dereferenced, you must never trigger a collection, which means no allocation. If you do, you violate Rust's "only one &mut" rule, and also risk a dangling pointer. How do you enforce this?
One way you could enforce this is to require a shared reference to the GC to dereference any GCPtr. Instead of `cell.count += 1` you would write `cell.deref(gc).count += 1`. This works but is verbose.
Another way you could enforce it is dynamically, by setting a value in a cell whenever it is dereferenced; but this incurs a runtime cost.
How does Sphinx solve this?
- celeritascelery 4y agoNot OP, but I recently wrote about solving this problem in my interpreter[1]. Essentially using a combination of LCell (compile time interior mutability) and taking a shared reference to the GC as you suggest. [1] https://coredumped.dev/2022/04/11/implementing-a-safe-garbage-collector-in-rust/ https://coredumped.dev/2022/04/11/implementing-a-safe-garbag...
- harpiaharpyja 4y agoIt works for Sphinx because the scope of the GC is restricted to Sphinx code. The Sphinx language runtime itself is typical Rust code - no GC used. So it is fairly straightforward to ensure that GCPtrs are never dereferenced during a collection cycle. Essentially, collection only ever happens between instructions. If we were writing a GC for general Rust code then this and other issues around ensuring values are rooted would become much bigger problems. For example, the rust-gc crate has to deal with these. Just to be safe I took a page out of rust-gc's book and implemented a guard to ensure that the runtime will at least panic if I make a mistake and that happens.