marCsweep/vm.c

61 lines
1.4 KiB
C
Raw Normal View History

#include <stdio.h>
#include <stdlib.h>
#include "vm.h"
2024-08-20 10:55:53 -04:00
#include "gc.h"
struct virtualMachine *initVM() {
struct virtualMachine *vm = malloc(sizeof(struct virtualMachine));
vm->stackSize = 0;
2024-08-20 10:55:53 -04:00
vm->refCount = 0;
vm->refMax = STACK_MAX / 2;
vm->head = NULL;
return vm;
}
void push(struct virtualMachine *vm, struct garbageObject *value) {
if (vm->stackSize >= STACK_MAX) {
fprintf(stderr, "ERROR: push(): refusing to overflow the stack!\n");
return;
}
vm->stack[vm->stackSize++] = value;
}
struct garbageObject *pop(struct virtualMachine *vm) {
if (vm->stackSize < 0) {
fprintf(stderr,
"ERROR: pop(): Stack size cannot be negative!");
return NULL;
}
return vm->stack[--vm->stackSize];
}
struct garbageObject *initGarbage(struct virtualMachine *vm,
enum garbageData type) {
2024-08-20 10:55:53 -04:00
if (vm->refCount == vm->refMax) collect(vm);
struct garbageObject *obj = malloc(sizeof(struct garbageObject));
obj->type = type;
obj->mark = 0;
2024-08-20 10:55:53 -04:00
obj->next = vm->head;
vm->head = obj;
vm->refCount++;
return obj;
}
void pushInt(struct virtualMachine *vm, int value) {
struct garbageObject *obj = initGarbage(vm, GARBAGE_INT);
obj->value = value;
push(vm, obj);
}
struct garbageObject *pushPair(struct virtualMachine *vm) {
struct garbageObject *obj = initGarbage(vm, GARBAGE_PAIR);
obj->tail = pop(vm);
obj->head = pop(vm);
push(vm, obj);
return obj;
}