munificent / craftinginterpreters

Repository for the book "Crafting Interpreters"
http://www.craftinginterpreters.com/
Other
8.87k stars 1.04k forks source link

Garbage collector does not appear to work, marks everything(?) instead #1068

Closed Cuber01 closed 2 years ago

Cuber01 commented 2 years ago

Reproduction

According to the book, running the following sample code, should clear "first value", however, it does not.

var a = "first value";
a = "updated";
// GC here.
print a;

I added collectGarbage() at line 552 in vm.c, so that the garbage collector runs every time OP_SET_GLOBAL is executed.

It does run, yet still marks "first value". Here's the relevant output:

0004    2 OP_CONSTANT         3 'updated'
          [ <script> ][ updated ]
0006    | OP_SET_GLOBAL       2 'a'
-- gc begin
0x55d0f8491c20 mark <script>
0x55d0f8491c70 mark updated
0x55d0f8491b30 mark a
0x55d0f8491800 mark clock
0x55d0f8491830 mark <native fn>
0x55d0f84916d0 mark init
0x55d0f84916d0 blacken init
0x55d0f8491830 blacken <native fn>
0x55d0f8491800 blacken clock
0x55d0f8491b30 blacken a
0x55d0f8491c70 blacken updated
0x55d0f8491c20 blacken <script>
0x55d0f8491ac0 mark <script>
0x55d0f8491ac0 blacken <script>
0x55d0f8491bd0 mark first value
0x55d0f8491bd0 blacken first value
-- gc end
   collected 0 bytes (from 769 to 769) next at 1538
          [ <script> ][ updated ]
0008    | OP_POP
          [ <script> ]
0009    4 OP_GET_GLOBAL       4 'a'
          [ <script> ][ updated ]
0011    | OP_PRINT
updated
          [ <script> ]
0012    | OP_NIL
          [ <script> ][ nil ]
0013    | OP_RETURN
0x55d0f8491c20 free type 2
0x55d0f8491c70 free type 6
0x55d0f8491bd0 free type 6
0x55d0f8491b30 free type 6
0x55d0f8491ac0 free type 3
0x55d0f8491830 free type 5
0x55d0f8491800 free type 6
0x55d0f84916d0 free type 6

What (I think) is the problem

In my own garbage collector, made mostly according to the book, I have a similar problem. Here's the cause:

In the collectGarbage->markRoots loop we mark the entire stack, including the global Githubissues.

  • Githubissues is a development platform for aggregating issues.