From 8a26ba535123529322793beb1214d7866ac5831a Mon Sep 17 00:00:00 2001 From: Andre Wagner Date: Sat, 9 May 2026 10:37:02 -0500 Subject: [PATCH] . --- lua-temp/TODO.md | 6 +++--- lua-temp/tests.lua | 7 ++++--- lua-temp/tyche-vm.lua | 23 ++++++++++++++++++----- 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/lua-temp/TODO.md b/lua-temp/TODO.md index 853472c..dc3fbd7 100644 --- a/lua-temp/TODO.md +++ b/lua-temp/TODO.md @@ -11,9 +11,9 @@ Progress of the Lua port: - [x] Control flow - [x] Labels in Assembly - [x] Recursion -- [ ] Strings - - [ ] From constants - - [ ] Garbage collection +- [x] Strings + - [x] From constants + - [x] Garbage collection - [ ] Arrays - [ ] Garbage collection - [ ] Tables diff --git a/lua-temp/tests.lua b/lua-temp/tests.lua index 7c6ff6d..9eec2b1 100755 --- a/lua-temp/tests.lua +++ b/lua-temp/tests.lua @@ -302,7 +302,7 @@ do TEST "VM: managed strings" assert_eq(vm:to_string(-1), "Hello") end -do TEST "VM: concatenate strings" +do TEST "VM: concatenate strings (GC won't delete)" local vm = VM.new():load(assemble [[ .const 0: "Hello " @@ -311,6 +311,7 @@ do TEST "VM: concatenate strings" pushc 0 pushc 1 sum + gc ret ]]):call(0) @@ -319,7 +320,7 @@ do TEST "VM: concatenate strings" assert_eq(vm.heap:size(), 1) end -do TEST "VM: collect strings" +do TEST "VM: GC strings" local vm = VM.new():load(assemble [[ .const 0: "Hello " @@ -334,7 +335,7 @@ do TEST "VM: collect strings" ret ]]):call(0) - print(vm:debug_heap()) + -- print(vm:debug_heap()) assert_eq(vm:is(-1, 'nil'), true) assert_eq(vm.heap:size(), 0) end diff --git a/lua-temp/tyche-vm.lua b/lua-temp/tyche-vm.lua index 86380cd..8fb6c61 100644 --- a/lua-temp/tyche-vm.lua +++ b/lua-temp/tyche-vm.lua @@ -221,8 +221,8 @@ function Heap.new() end function Heap:add_value(value) - local key = math.random(math.mininteger, math.maxinteger) - while self.items[key] do key = math.random(math.mininteger, math.maxinteger) end + local key = math.random(1, math.maxinteger) + while self.items[key] do key = math.random(1, math.maxinteger) end self.items[key] = value return key end @@ -237,8 +237,21 @@ function Heap:size() return n end -function Heap:call_gc() - -- TODO +function Heap:call_gc(roots) + -- mark + local marked = {} + for _,v in ipairs(roots) do -- TODO - recursive, add support to array + if v.type == 'string' and v.ref then + marked[v.ref] = true + end + end + + -- sweep + for key,_ in pairs(self.items) do + if not marked[key] then + self.items[key] = nil + end + end end ---------------------- @@ -527,7 +540,7 @@ function VM:_step() -- elseif op.operator == 'gc' then - self.heap:call_gc() + self.heap:call_gc(self.stack.stack) -- -- instruction not found