From 6561f41ea3ce62e08c7dffc6731b50713db916d3 Mon Sep 17 00:00:00 2001 From: Tim Peters Date: Tue, 28 May 2024 21:23:31 +0200 Subject: [PATCH] Automatically add finalizer. Use needs_drop to see if the type needs to be dropped. Right now this is only . --- lox-gc/src/gc.rs | 11 +++++++++-- lox-gc/src/lib.rs | 6 ------ lox-vm/src/memory/closure.rs | 6 +++--- lox-vm/src/runtime.rs | 2 -- 4 files changed, 12 insertions(+), 13 deletions(-) diff --git a/lox-gc/src/gc.rs b/lox-gc/src/gc.rs index e625561..08d3963 100644 --- a/lox-gc/src/gc.rs +++ b/lox-gc/src/gc.rs @@ -61,7 +61,7 @@ impl ManagedHeap { } } - pub fn finalize(&self, gc: Gc<()>) { + fn finalize(&self, gc: Gc<()>) { self.finalizers.borrow_mut().push(gc); } @@ -90,13 +90,20 @@ impl ManagedHeap { pub fn manage(&self, data: T) -> Gc where T: Trace + 'static { let layout = std::alloc::Layout::new::>(); let ptr = self.heap.alloc(layout) as *mut Allocation; - unsafe { + let gc = unsafe { ptr.write(Allocation::new(data)); Gc { ptr: NonNull::new_unchecked(ptr), } + }; + + if std::mem::needs_drop::() { + //eprintln!("Type {} needs drop. Adding to finalizers.", std::any::type_name::()); + self.finalize(gc.erase()); } + + gc } pub fn collect(&self, roots: &[&dyn Trace]) { diff --git a/lox-gc/src/lib.rs b/lox-gc/src/lib.rs index f4ae682..03592e3 100644 --- a/lox-gc/src/lib.rs +++ b/lox-gc/src/lib.rs @@ -25,9 +25,3 @@ pub fn collect(roots: &[&dyn Trace]) { heap.collect(roots) }) } - -pub fn finalize(gc: Gc) { - HEAP.with(|heap| { - heap.finalize(gc.erase()) - }) -} diff --git a/lox-vm/src/memory/closure.rs b/lox-vm/src/memory/closure.rs index 1a5fbba..6a1f7a3 100644 --- a/lox-vm/src/memory/closure.rs +++ b/lox-vm/src/memory/closure.rs @@ -3,12 +3,12 @@ use std::cell::Cell; use lox_gc::{Gc, Trace, Tracer}; use crate::memory::{Import, Upvalue}; use crate::fiber::Fiber; -use arrayvec::ArrayVec; use crate::string::LoxString; +use crate::array::Array; pub struct Closure { pub function: Function, - pub upvalues: ArrayVec>, 128>, + pub upvalues: Array>>, } unsafe impl Trace for Closure { @@ -57,7 +57,7 @@ impl Closure { }; Closure { - upvalues: ArrayVec::new(), + upvalues: Array::new(), function, } } diff --git a/lox-vm/src/runtime.rs b/lox-vm/src/runtime.rs index adbbcf8..b19ba43 100644 --- a/lox-vm/src/runtime.rs +++ b/lox-vm/src/runtime.rs @@ -122,7 +122,6 @@ impl Runtime { fn prepare_interpret(&mut self, module: Module) -> Gc { let import = Import::with_module("_root", module, &mut self.interner); let import: Gc = self.manage(import.into()); - lox_gc::finalize(import); self.imports.insert(import.name.clone(), import); self.globals_import().copy_to(&import); @@ -142,7 +141,6 @@ impl Runtime { if let Some(module) = module { let import = Import::with_module(path, module, &mut self.interner); let import = self.manage(import.into()); - lox_gc::finalize(import); self.imports.insert(path.into(), import); self.globals_import().copy_to(&import);