pr6.1
This commit is contained in:
@@ -10,6 +10,11 @@ pub struct StoredObject {
|
||||
/// Optional typed elements for `ObjectKind::Array`.
|
||||
/// When present, `header.payload_len` must equal `array_elems.len() as u32`.
|
||||
pub array_elems: Option<Vec<Value>>,
|
||||
/// Optional captured environment for `ObjectKind::Closure`.
|
||||
/// `header.payload_len` stores the fixed-size metadata length (8 bytes):
|
||||
/// [fn_id: u32][env_len: u32].
|
||||
/// The actual env slots are stored here to remain GC-visible.
|
||||
pub closure_env: Option<Vec<Value>>,
|
||||
}
|
||||
|
||||
/// Simple vector-backed heap. No GC or compaction.
|
||||
@@ -26,7 +31,7 @@ impl Heap {
|
||||
/// Returns an opaque `HeapRef` handle.
|
||||
pub fn allocate_object(&mut self, kind: ObjectKind, payload: &[u8]) -> HeapRef {
|
||||
let header = ObjectHeader::new(kind, payload.len() as u32);
|
||||
let obj = StoredObject { header, payload: payload.to_vec(), array_elems: None };
|
||||
let obj = StoredObject { header, payload: payload.to_vec(), array_elems: None, closure_env: None };
|
||||
let idx = self.objects.len();
|
||||
// No free-list reuse in this PR: append and keep indices stable.
|
||||
self.objects.push(Some(obj));
|
||||
@@ -37,13 +42,35 @@ impl Heap {
|
||||
/// `payload_len` stores the element count; raw `payload` bytes are empty.
|
||||
pub fn allocate_array(&mut self, elements: Vec<Value>) -> HeapRef {
|
||||
let header = ObjectHeader::new(ObjectKind::Array, elements.len() as u32);
|
||||
let obj = StoredObject { header, payload: Vec::new(), array_elems: Some(elements) };
|
||||
let obj = StoredObject { header, payload: Vec::new(), array_elems: Some(elements), closure_env: None };
|
||||
let idx = self.objects.len();
|
||||
// No free-list reuse in this PR: append and keep indices stable.
|
||||
self.objects.push(Some(obj));
|
||||
HeapRef(idx as u32)
|
||||
}
|
||||
|
||||
/// Allocate a new `Closure` object with the given function id and captured environment.
|
||||
/// Layout:
|
||||
/// payload bytes: [fn_id: u32][env_len: u32]
|
||||
/// env slots: stored out-of-line in `closure_env` for GC visibility
|
||||
pub fn alloc_closure(&mut self, fn_id: u32, env_values: &[Value]) -> HeapRef {
|
||||
let mut payload = Vec::with_capacity(8);
|
||||
payload.extend_from_slice(&fn_id.to_le_bytes());
|
||||
let env_len = env_values.len() as u32;
|
||||
payload.extend_from_slice(&env_len.to_le_bytes());
|
||||
|
||||
let header = ObjectHeader::new(ObjectKind::Closure, payload.len() as u32);
|
||||
let obj = StoredObject {
|
||||
header,
|
||||
payload,
|
||||
array_elems: None,
|
||||
closure_env: Some(env_values.to_vec()),
|
||||
};
|
||||
let idx = self.objects.len();
|
||||
self.objects.push(Some(obj));
|
||||
HeapRef(idx as u32)
|
||||
}
|
||||
|
||||
/// Returns true if this handle refers to an allocated object.
|
||||
pub fn is_valid(&self, r: HeapRef) -> bool {
|
||||
let idx = r.0 as usize;
|
||||
@@ -84,8 +111,18 @@ impl Heap {
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()
|
||||
}
|
||||
ObjectKind::Closure => {
|
||||
// Traverse only Value::HeapRef inside the closure env.
|
||||
o.closure_env
|
||||
.as_ref()
|
||||
.into_iter()
|
||||
.flat_map(|v| v.iter())
|
||||
.filter_map(|val| if let Value::HeapRef(h) = val { Some(*h) } else { None })
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()
|
||||
}
|
||||
// These kinds have no inner references in this PR.
|
||||
ObjectKind::String | ObjectKind::Bytes | ObjectKind::Closure | ObjectKind::UserData | ObjectKind::Unknown => {
|
||||
ObjectKind::String | ObjectKind::Bytes | ObjectKind::UserData | ObjectKind::Unknown => {
|
||||
Vec::new().into_iter()
|
||||
}
|
||||
})
|
||||
@@ -93,6 +130,25 @@ impl Heap {
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Read the `fn_id` stored in a closure object. Returns None if kind mismatch or invalid ref.
|
||||
pub fn closure_fn_id(&self, r: HeapRef) -> Option<u32> {
|
||||
let idx = r.0 as usize;
|
||||
let slot = self.objects.get(idx)?.as_ref()?;
|
||||
if slot.header.kind != ObjectKind::Closure { return None; }
|
||||
if slot.payload.len() < 8 { return None; }
|
||||
let mut bytes = [0u8; 4];
|
||||
bytes.copy_from_slice(&slot.payload[0..4]);
|
||||
Some(u32::from_le_bytes(bytes))
|
||||
}
|
||||
|
||||
/// Get the captured environment slice of a closure. Returns None if kind mismatch or invalid ref.
|
||||
pub fn closure_env_slice(&self, r: HeapRef) -> Option<&[Value]> {
|
||||
let idx = r.0 as usize;
|
||||
let slot = self.objects.get(idx)?.as_ref()?;
|
||||
if slot.header.kind != ObjectKind::Closure { return None; }
|
||||
slot.closure_env.as_deref()
|
||||
}
|
||||
|
||||
/// Mark phase: starting from the given roots, traverse and set mark bits
|
||||
/// on all reachable objects. Uses an explicit stack to avoid recursion.
|
||||
pub fn mark_from_roots<I: IntoIterator<Item = HeapRef>>(&mut self, roots: I) {
|
||||
@@ -238,6 +294,40 @@ mod tests {
|
||||
assert!(heap.header(b).unwrap().is_marked());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closure_allocation_with_empty_env() {
|
||||
let mut heap = Heap::new();
|
||||
let c = heap.alloc_closure(42, &[]);
|
||||
assert!(heap.is_valid(c));
|
||||
let h = heap.header(c).unwrap();
|
||||
assert_eq!(h.kind, ObjectKind::Closure);
|
||||
// payload has only metadata (8 bytes)
|
||||
assert_eq!(h.payload_len, 8);
|
||||
assert_eq!(heap.closure_fn_id(c), Some(42));
|
||||
let env = heap.closure_env_slice(c).unwrap();
|
||||
assert_eq!(env.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closure_allocation_with_env_and_access() {
|
||||
let mut heap = Heap::new();
|
||||
let a = heap.allocate_object(ObjectKind::String, b"a");
|
||||
let env_vals = vec![Value::Int32(7), Value::HeapRef(a), Value::Boolean(true)];
|
||||
let c = heap.alloc_closure(7, &env_vals);
|
||||
|
||||
let h = heap.header(c).unwrap();
|
||||
assert_eq!(h.kind, ObjectKind::Closure);
|
||||
assert_eq!(h.payload_len, 8);
|
||||
assert_eq!(heap.closure_fn_id(c), Some(7));
|
||||
let env = heap.closure_env_slice(c).unwrap();
|
||||
assert_eq!(env, &env_vals[..]);
|
||||
|
||||
// GC traversal should see the inner HeapRef in closure env when marking.
|
||||
heap.mark_from_roots([c]);
|
||||
assert!(heap.header(c).unwrap().is_marked());
|
||||
assert!(heap.header(a).unwrap().is_marked());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sweep_reclaims_unreachable_and_invalidates_handles() {
|
||||
let mut heap = Heap::new();
|
||||
|
||||
Reference in New Issue
Block a user