From 8d7a24bfdad7665bdedccb2683fb49b34090d89c Mon Sep 17 00:00:00 2001 From: Andrew Scott Date: Mon, 19 Aug 2024 15:45:23 -0400 Subject: [PATCH] VM: added definitions for init, push, and pop --- vm.c | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 vm.c diff --git a/vm.c b/vm.c new file mode 100644 index 0000000..0e9a1ac --- /dev/null +++ b/vm.c @@ -0,0 +1,37 @@ +#include +#include + +#include "vm.h" + +struct virtualMachine *initVM() { + struct virtualMachine *vm = malloc(sizeof(struct virtualMachine)); + vm->stackSize = 0; + 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"); + // FIXME: Must free memory before exiting + exit(-1); + } + vm->stack[vm->stackSize++] = value; +} + +struct garbageObject *pop(struct virtualMachine *vm) { + if (vm->stackSize < 0) { + fprintf(stderr, + "ERROR: pop(): Stack underflow - stack size cannot be negative!"); + // FIXME: Must free memory before exiting + exit(-1); + } + + return vm->stack[--vm->stackSize]; +} + +struct garbageObject *initGarbage(struct virtualMachine *vm, + enum garbageData type) { + struct garbageObject *obj = malloc(sizeof(struct garbageObject)); + obj->type = type; + return obj; +}