-
Notifications
You must be signed in to change notification settings - Fork 14
feat: implement mark_sweep _branded based on approved API redesign #83
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
shruti2522
wants to merge
9
commits into
boa-dev:main
Choose a base branch
from
shruti2522:prototype-impl
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
a7869b7
feat: implement mark_sweep_branded based on approved API redesign
shruti2522 a62f19e
Merge remote-tracking branch 'upstream/main' into prototype-impl
shruti2522 222a786
fix
shruti2522 974c72b
add ephemeron support
shruti2522 4928a18
replace Tracer with TraceColor
shruti2522 2fbadae
remove pool_entries Vec and allocation_count
shruti2522 f5d3154
implement tri-color marking
shruti2522 a98ad8e
refactor: use PoolPointer, make Ephemeron::key_ptr Option<PoolPointer>
shruti2522 189967b
refactor: move RootNode, Root and RootLink into separate root module
shruti2522 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| **Date**: 2026-04-23 | ||
|
|
||
| ## Changes from API Redesign Proposal | ||
|
|
||
| ### 1. Allocation ID for Weak References (ABA Protection) | ||
|
|
||
| **Added:** | ||
| - `alloc_id: usize` in `GcBox<T>` and `WeakGc<'id, T>` | ||
| - `FREED_ALLOC_ID = usize::MAX` constant | ||
| - Validation check in `WeakGc::upgrade` | ||
|
|
||
| **Why needed:** | ||
| Pool allocators reuse memory slots. Without IDs, a weak pointer could point to the wrong object after the slot is reused. | ||
|
|
||
| **How it works:** | ||
| - Each allocation gets a unique ID | ||
| - Freed slots get ID set to `usize::MAX` | ||
| - `WeakGc::upgrade` checks if IDs match | ||
| - If IDs don't match, slot was reused, return `None` | ||
|
|
||
| **Industry standard:** | ||
| V8 and SpiderMonkey use the same technique. Required for soundness with pool allocators. | ||
|
|
||
| ### 2. Allocation ID Wrap Check | ||
|
|
||
| **Added:** | ||
| ```rust | ||
| assert_ne!(alloc_id, FREED_ALLOC_ID, "..."); | ||
| ``` | ||
|
|
||
| **Why:** | ||
| If the ID counter wraps to `usize::MAX`, weak reference validation breaks. This check prevents silent corruption. | ||
|
|
||
| **Practical impact:** | ||
| Requires 2^64 allocations on 64-bit systems (impossible in practice). | ||
|
|
||
| ### 3. Additional Trace Implementations | ||
|
|
||
| **Added:** | ||
| - `BTreeMap<K, V>` (traces values only) | ||
| - `BTreeSet<T>` (no-op, keys are immutable) | ||
| - 3-tuple and 4-tuple | ||
| - Comments for `Rc<T>`, `Arc<T>`, `Cell<Option<T>>` | ||
|
|
||
| **Why:** | ||
| Needed for real Boa code. Keys in BTree collections are immutable, so they cannot contain `Gc` pointers (which need `&mut self` to trace). | ||
|
|
||
| **Note:** | ||
| `HashMap` and `HashSet` are in `std::collections`, not available in `no_std` builds. | ||
|
|
||
| ### 4. Cell<Option<T>> Requires T: Copy | ||
|
|
||
| **Fixed:** | ||
| ```rust | ||
| impl<T: Copy + Trace> Trace for Cell<Option<T>> | ||
| ``` | ||
|
|
||
| **Why:** | ||
| `self.set(Some(v))` requires moving `v`, which needs `T: Copy`. Without this bound, code fails to compile. | ||
|
|
||
| **Alternative:** | ||
| Use `GcRefCell<T>` for non Copy types. | ||
|
|
||
| ## Design Decisions | ||
|
|
||
| ### Trace::trace uses &mut self | ||
|
|
||
| Follows the proposal exactly. Allows future moving collectors to update internal pointers during tracing. | ||
|
|
||
| **Impact:** | ||
| Collection keys (HashMap, BTreeMap) cannot contain `Gc` pointers because keys are immutable. | ||
|
|
||
| ### collect() uses &self not &mut self | ||
|
|
||
| Both `GcContext::collect` and `MutationContext::collect` use `&self` with interior mutability via `RefCell`. | ||
|
|
||
| **Why:** | ||
| Allows calling `collect()` inside `mutate()` closures without borrow conflicts. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| //! Interior mutability for GC-managed values. | ||
|
|
||
| use crate::collectors::mark_sweep_branded::trace::{Finalize, Trace, Tracer}; | ||
| use core::cell::{Ref, RefCell, RefMut}; | ||
| use core::ops::{Deref, DerefMut}; | ||
|
|
||
| /// A GC-aware wrapper around [`RefCell<T>`]. | ||
| pub struct GcRefCell<T: Trace> { | ||
| inner: RefCell<T>, | ||
| } | ||
|
|
||
| impl<T: Trace> GcRefCell<T> { | ||
| /// Wraps `value` in a new `GcRefCell`. | ||
| pub fn new(value: T) -> Self { | ||
| Self { | ||
| inner: RefCell::new(value), | ||
| } | ||
| } | ||
|
|
||
| /// Acquires a shared borrow of the inner value. | ||
| /// | ||
| /// # Panics | ||
| /// | ||
| /// Panics if the value is currently mutably borrowed. | ||
| pub fn borrow(&self) -> GcRef<'_, T> { | ||
| GcRef(self.inner.borrow()) | ||
| } | ||
|
|
||
| /// Acquires a mutable borrow of the inner value. | ||
| /// | ||
| /// # Panics | ||
| /// | ||
| /// Panics if the value is currently borrowed. | ||
| pub fn borrow_mut(&self) -> GcRefMut<'_, T> { | ||
| GcRefMut(self.inner.borrow_mut()) | ||
| } | ||
| } | ||
|
|
||
| /// A shared borrow guard returned by [`GcRefCell::borrow`]. | ||
| pub struct GcRef<'a, T: Trace>(Ref<'a, T>); | ||
|
|
||
| impl<T: Trace> Deref for GcRef<'_, T> { | ||
| type Target = T; | ||
| fn deref(&self) -> &T { | ||
| &self.0 | ||
| } | ||
| } | ||
|
|
||
| /// A mutable borrow guard returned by [`GcRefCell::borrow_mut`]. | ||
| pub struct GcRefMut<'a, T: Trace>(RefMut<'a, T>); | ||
|
|
||
| impl<T: Trace> Deref for GcRefMut<'_, T> { | ||
| type Target = T; | ||
| fn deref(&self) -> &T { | ||
| &self.0 | ||
| } | ||
| } | ||
|
|
||
| impl<T: Trace> DerefMut for GcRefMut<'_, T> { | ||
| fn deref_mut(&mut self) -> &mut T { | ||
| &mut self.0 | ||
| } | ||
| } | ||
|
|
||
| impl<T: Trace> Finalize for GcRefCell<T> {} | ||
|
|
||
| impl<T: Trace> Trace for GcRefCell<T> { | ||
| fn trace(&mut self, tracer: &mut Tracer) { | ||
| self.inner.get_mut().trace(tracer); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| //! Core pointer types. | ||
|
|
||
| use crate::collectors::mark_sweep_branded::{ | ||
| gc_box::GcBox, | ||
| root_link::RootLink, | ||
| trace::{Finalize, Trace}, | ||
| }; | ||
| use core::fmt; | ||
| use core::marker::PhantomData; | ||
| use core::ops::Deref; | ||
| use core::ptr::NonNull; | ||
| use rust_alloc::boxed::Box; | ||
|
|
||
| /// A transient pointer to a GC-managed value. | ||
| #[derive(Debug)] | ||
| pub struct Gc<'gc, T: Trace + ?Sized + 'gc> { | ||
| pub(crate) ptr: NonNull<GcBox<T>>, | ||
| pub(crate) _marker: PhantomData<(&'gc T, *const ())>, | ||
| } | ||
|
|
||
| impl<'gc, T: Trace + ?Sized + 'gc> Copy for Gc<'gc, T> {} | ||
| impl<'gc, T: Trace + ?Sized + 'gc> Clone for Gc<'gc, T> { | ||
| fn clone(&self) -> Self { | ||
| *self | ||
| } | ||
| } | ||
|
|
||
| impl<'gc, T: Trace + 'gc> Gc<'gc, T> { | ||
| /// Returns a shared reference to the value. | ||
| #[inline] | ||
| pub fn get(&self) -> &T { | ||
| // SAFETY: `ptr` is non-null and valid for `'gc` by construction. | ||
| // The `'gc` lifetime is scoped to a `mutate()` closure, collection only occurs | ||
| // via `cx.collect()` within that same closure and `Gc<'gc, T>` can't | ||
| // escape the closure. | ||
| unsafe { &(*self.ptr.as_ptr()).value } | ||
| } | ||
| } | ||
|
|
||
| impl<'gc, T: Trace + fmt::Display + 'gc> fmt::Display for Gc<'gc, T> { | ||
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| fmt::Display::fmt(self.get(), f) | ||
| } | ||
| } | ||
|
|
||
| impl<'gc, T: Trace + 'gc> Deref for Gc<'gc, T> { | ||
| type Target = T; | ||
| fn deref(&self) -> &T { | ||
| self.get() | ||
| } | ||
| } | ||
|
|
||
| /// Heap node backing a `Root`. | ||
| #[repr(C)] | ||
| pub(crate) struct RootNode<'id, T: Trace> { | ||
| /// Intrusive list link | ||
| pub(crate) link: RootLink, | ||
| /// Pointer to the allocation | ||
| pub(crate) gc_ptr: NonNull<GcBox<T>>, | ||
| pub(crate) _marker: PhantomData<*mut &'id ()>, | ||
| } | ||
|
|
||
| /// A handle that keeps a GC allocation live. | ||
| #[must_use = "dropping a root unregisters it from the GC"] | ||
| pub struct Root<'id, T: Trace> { | ||
| pub(crate) raw: NonNull<RootNode<'id, T>>, | ||
| } | ||
|
|
||
| impl<'id, T: Trace> Root<'id, T> { | ||
| /// Converts this root into a `Gc` pointer | ||
| pub fn get<'gc>( | ||
| &self, | ||
| _cx: &crate::collectors::mark_sweep_branded::MutationContext<'id, 'gc>, | ||
|
nekevss marked this conversation as resolved.
Outdated
|
||
| ) -> Gc<'gc, T> { | ||
| Gc { | ||
| // SAFETY: `raw` is non-null and valid. | ||
| ptr: unsafe { self.raw.as_ref().gc_ptr }, | ||
| _marker: PhantomData, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<'id, T: Trace> Drop for Root<'id, T> { | ||
| fn drop(&mut self) { | ||
| // SAFETY: | ||
| // * `self.raw` was created by `Box::into_raw` | ||
| // * The address is stable. | ||
| unsafe { | ||
| let node = Box::from_raw(self.raw.as_ptr()); | ||
| if node.link.is_linked() { | ||
| RootLink::unlink(NonNull::from(&node.link)); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<T: Trace> Finalize for Gc<'_, T> {} | ||
| impl<T: Trace> Trace for Gc<'_, T> { | ||
| fn trace(&mut self, tracer: &mut crate::collectors::mark_sweep_branded::trace::Tracer) { | ||
| tracer.mark(self); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| //! The heap header wrapping every GC-managed value. | ||
|
|
||
| use core::cell::Cell; | ||
|
|
||
| use crate::collectors::mark_sweep_branded::trace::TraceFn; | ||
|
|
||
| /// Heap wrapper for a garbage-collected value. | ||
| /// | ||
| /// Allocated via [`PoolAllocator`][crate::alloc::mempool3::PoolAllocator]. | ||
| pub(crate) struct GcBox<T: ?Sized> { | ||
| /// Reachability flag set by the mark phase. | ||
| pub(crate) marked: Cell<bool>, | ||
| /// Type-erased trace function. | ||
| pub(crate) trace_fn: Option<TraceFn>, | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is there ever an instance where |
||
| /// Allocation ID used to validate weak pointers. | ||
| pub(crate) alloc_id: usize, | ||
| /// The user value. | ||
| pub(crate) value: T, | ||
| } | ||
|
|
||
| impl<T: ?Sized> GcBox<T> { | ||
| pub(crate) const FREED_ALLOC_ID: usize = usize::MAX; | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: it may be better to move
RootNode,Root, andRootLinkall into their ownrootmodule. I think that may be easier to reason about.