11#include <stdlib.h>
22
33#include "chunk.h"
4+ #include "compiler.h"
45#include "memory.h"
56#include "object.h"
7+ #include "table.h"
68#include "value.h"
79#include "vm.h"
810
11+ #ifdef DEBUG_LOG_GC
12+ #include "debug.h"
13+ #include <stdio.h>
14+ #endif
15+
916void * reallocate (void * pointer , size_t old_size , size_t new_size )
1017{
18+ if (new_size > old_size )
19+ {
20+ #ifdef DEBUG_PRINT_CODE
21+ collect_garbage ();
22+ #endif
23+ }
1124 if (new_size == 0 )
1225 {
1326 free (pointer );
@@ -20,8 +33,35 @@ void* reallocate(void* pointer, size_t old_size, size_t new_size)
2033 return result ;
2134}
2235
36+ void mark_object (Obj * object )
37+ {
38+ if (object == NULL )
39+ return ;
40+
41+ #ifdef DEBUG_LOG_GC
42+ printf ("%p mark " , (void * )object );
43+ print_value (OBJ_VAL (object ));
44+ printf ("\n" );
45+ #endif
46+
47+ object -> is_marked = true;
48+ }
49+
50+ void mark_value (Value value )
51+ {
52+ if (!IS_OBJ (value ))
53+ return ;
54+
55+ mark_object (AS_OBJ (value ));
56+ }
57+
2358static void free_object (Obj * object )
2459{
60+
61+ #ifdef DEBUG_LOG_GC
62+ printf ("%p free type %d\n" , (void * )object , object -> type );
63+ #endif
64+
2565 switch (object -> type )
2666 {
2767 case OBJ_CLOSURE :
@@ -57,6 +97,7 @@ static void free_object(Obj* object)
5797 }
5898 }
5999}
100+
60101void free_objects ()
61102{
62103 Obj * object = vm .objects ;
@@ -67,3 +108,38 @@ void free_objects()
67108 object = next ;
68109 }
69110}
111+
112+ static void mark_roots ()
113+ {
114+ for (Value * slot = vm .stack ; slot < vm .stack_top ; slot ++ )
115+ {
116+ mark_value (* slot );
117+ }
118+
119+ for (int i = 0 ; i < vm .frame_count ; i ++ )
120+ {
121+ mark_object ((Obj * )& vm .frames [i ].closure );
122+ }
123+
124+ // WALKING A LINKED LIST
125+ for (ObjUpvalue * upvalue = vm .open_upvalues ; upvalue != NULL ; upvalue = upvalue -> next )
126+ {
127+ mark_object ((Obj * )upvalue );
128+ }
129+
130+ mark_table (& vm .globals );
131+ mark_compiler_roots ();
132+ }
133+
134+ void collect_garbage ()
135+ {
136+ #ifdef DEBUG_LOG_GC
137+ printf ("-- GC Begins \n" );
138+ #endif
139+
140+ mark_roots ();
141+
142+ #ifdef DEBUG_LOG_GC
143+ printf ("-- GC Ends \n" );
144+ #endif
145+ }
0 commit comments