VM: return instead of exit on stack overflow/underflow

This commit is contained in:
Andrew Scott 2024-08-19 16:19:08 -04:00
parent f1b5822a81
commit d89f7e13cf
Signed by: a
GPG key ID: 7CD5A5977E4931C1

26
vm.c
View file

@ -11,9 +11,8 @@ struct virtualMachine *initVM() {
void push(struct virtualMachine *vm, struct garbageObject *value) { void push(struct virtualMachine *vm, struct garbageObject *value) {
if (vm->stackSize >= STACK_MAX) { if (vm->stackSize >= STACK_MAX) {
fprintf(stderr, "ERROR: push(): Refusing to overflow the stack!\n"); fprintf(stderr, "ERROR: push(): refusing to overflow the stack!\n");
// FIXME: Must free memory before exiting return;
exit(-1);
} }
vm->stack[vm->stackSize++] = value; vm->stack[vm->stackSize++] = value;
} }
@ -21,9 +20,8 @@ void push(struct virtualMachine *vm, struct garbageObject *value) {
struct garbageObject *pop(struct virtualMachine *vm) { struct garbageObject *pop(struct virtualMachine *vm) {
if (vm->stackSize < 0) { if (vm->stackSize < 0) {
fprintf(stderr, fprintf(stderr,
"ERROR: pop(): Stack underflow - stack size cannot be negative!"); "ERROR: pop(): Stack size cannot be negative!");
// FIXME: Must free memory before exiting return NULL;
exit(-1);
} }
return vm->stack[--vm->stackSize]; return vm->stack[--vm->stackSize];
@ -33,5 +31,21 @@ struct garbageObject *initGarbage(struct virtualMachine *vm,
enum garbageData type) { enum garbageData type) {
struct garbageObject *obj = malloc(sizeof(struct garbageObject)); struct garbageObject *obj = malloc(sizeof(struct garbageObject));
obj->type = type; obj->type = type;
obj->mark = 0;
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; return obj;
} }