Chapter 26.5

This commit is contained in:
Tom Willemse 2022-08-12 17:55:32 -07:00
parent 14b3866ac0
commit 89ffc2e60a
3 changed files with 34 additions and 0 deletions

View file

@ -150,6 +150,28 @@ static void traceReferences() {
} }
} }
static void sweep() {
Obj *previous = NULL;
Obj *object = vm.objects;
while (object != NULL) {
if (object->isMarked) {
object->isMarked = false;
previous = object;
object = object->next;
} else {
Obj *unreached = object;
object = object->next;
if (previous != NULL) {
previous->next = object;
} else {
vm.objects = object;
}
freeObject(unreached);
}
}
}
void collectGarbage() { void collectGarbage() {
#ifdef DEBUG_LOG_GC #ifdef DEBUG_LOG_GC
printf("-- gc begin\n"); printf("-- gc begin\n");
@ -157,6 +179,8 @@ void collectGarbage() {
markRoots(); markRoots();
traceReferences(); traceReferences();
tableRemoveWhite(&vm.strings);
sweep();
#ifdef DEBUG_LOG_GC #ifdef DEBUG_LOG_GC
printf("-- gd end\n"); printf("-- gd end\n");

View file

@ -141,6 +141,15 @@ ObjString *tableFindString(Table *table, const char *chars, int length,
} }
} }
void tableRemoveWhite(Table *table) {
for (int i = 0; i < table->capacity; i++) {
Entry *entry = &table->entries[i];
if (entry->key != NULL && !entry->key->obj.isMarked) {
tableDelete(table, entry->key);
}
}
}
void markTable(Table *table) { void markTable(Table *table) {
for (int i = 0; i < table->capacity; i++) { for (int i = 0; i < table->capacity; i++) {
Entry *entry = &table->entries[i]; Entry *entry = &table->entries[i];

View file

@ -23,6 +23,7 @@ bool tableDelete(Table *table, ObjString *key);
void tableAddAll(Table *from, Table *to); void tableAddAll(Table *from, Table *to);
ObjString *tableFindString(Table *talbe, const char *chars, int length, ObjString *tableFindString(Table *talbe, const char *chars, int length,
uint32_t hash); uint32_t hash);
void tableRemoveWhite(Table *table);
void markTable(Table *table); void markTable(Table *table);
#endif #endif