diff --git a/main.c b/main.c index 78f2de1..2f2dade 100644 --- a/main.c +++ b/main.c @@ -1 +1,108 @@ -int main(void) { return 0; } +#include +#include +#include + +#include "gc.h" +#include "test_gc.h" +#include "vm.h" + +void test_int_alloc() { + struct virtualMachine *vm = initVM(); + pushInt(vm, 100); + pushInt(vm, 1000); + pushInt(vm, 10000); + pushInt(vm, -100000); + assert(vm->refCount == 4 && + "test_int_alloc: GARBAGE_INT allocation failure\n"); + printf("test_int_alloc: PASS\n"); + free(vm); +} + +void test_pair_alloc() { + struct virtualMachine *vm = initVM(); + pushInt(vm, 100); + pushInt(vm, 1000); + pushInt(vm, 10000); + pushInt(vm, -100000); + pushPair(vm); + pushPair(vm); + assert(vm->refCount == 6 && + "test_pair_alloc: FAILED: GARBAGE_PAIR allocation failure\n"); + printf("test_pair_alloc: PASS\n"); + free(vm); +} + +void test_obj_count() { + struct virtualMachine *vm = initVM(); + pushInt(vm, 100); + pushInt(vm, 1000); + pushInt(vm, 10000); + pushInt(vm, -100000); + collect(vm); + assert(vm->refCount == 4 && + "test_obj_count: FAILED: GC occurred when it shouldn't have\n"); + printf("test_obj_count: PASS\n"); + free(vm); +} + +void test_nested_pair() { + struct virtualMachine *vm = initVM(); + pushInt(vm, 100); + pushInt(vm, 1000); + pushPair(vm); + pushInt(vm, 10000); + pushInt(vm, -100000); + pushPair(vm); + pushPair(vm); + collect(vm); + assert(vm->refCount == 7 && + "test_nested_pair: FAILED: GARBAGE_PAIR allocation failure\n"); + printf("test_pair_alloc: PASS\n"); + free(vm); +} + +void test_unreachable() { + struct virtualMachine *vm = initVM(); + pushInt(vm, 100); + pushInt(vm, 1000); + pop(vm); + pop(vm); + collect(vm); + assert(vm->refCount == 0 && + "test_unreachable: FAILED: 2 GARBAGE_INT should have been freed\n"); + printf("test_unreachable: PASS\n"); + free(vm); +} + +void test_auto_gc() { + struct virtualMachine *vm = initVM(); + + for (size_t i = 0; i < 505; ++i) { + pushInt(vm, 1); + } + + for (size_t i = 0; i < 5; ++i) { + pop(vm); + } + + for (size_t i = 0; i < 50; ++i) { + pushInt(vm, 2); + } + + assert(vm->refCount == 550 && + "test_auto_gc: FAILED: 5 references should have been freed\n"); + printf("test_auto_gc: PASS\n"); + free(vm); +} + +int main(void) { + + test_int_alloc(); + test_pair_alloc(); + test_obj_count(); + test_nested_pair(); + test_unreachable(); + test_auto_gc(); + + return 0; +} diff --git a/test_gc.h b/test_gc.h new file mode 100644 index 0000000..f00bbb0 --- /dev/null +++ b/test_gc.h @@ -0,0 +1,16 @@ +#ifndef TEST_GC_H +#define TEST_GC_H + +void test_int_alloc(void); + +void test_pair_alloc(void); + +void test_obj_count(void); + +void test_nested_pair(void); + +void test_unreachable(void); + +void test_auto_gc(void); + +#endif /* TEST_GC_H */