Garbage collection is contrarian
4 months ago
- #rust
- #lifetimes
- #garbage-collection
- The Nova JavaScript engine models garbage collection using Rust's borrow checker, ensuring unrooted handles are not kept past garbage collection safepoints.
- The current model is criticized for turning code into a 'soup' of bind and unbind calls, with some calling it worse than C++.
- The author initially assumed the model was correct, but limitations led to exploring contravariant lifetimes for garbage collected handles.
- Garbage collected handles on the heap should have a 'static lifetime, while those on the stack should have a 'local lifetime, shorter than 'static.
- The current covariant lifetime model in Nova prevents safe rooting of local handles into the heap, requiring unsafe Rust workarounds.
- Contravariant lifetimes allow shortening the lifetime of a handle from the heap to a local lifetime, aligning with garbage collection semantics.
- Contravariant references act as 'sinks' where values can be written but not safely read without additional proof, complicating safe API design.
- The proposed contravariant handle model would simplify Nova's code by removing many unbind/bind calls, improving ergonomics.
- Contravariant references may have broader applications in self-referential data structures, though their safe use in Rust requires further exploration.
- Feedback highlighted that a fully safe representation of unrooted handles is possible using invariance, as demonstrated by gc-arena.