2024-08-19 15:45:23 -04:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
|
|
|
#include "vm.h"
|
2024-08-20 10:55:53 -04:00
|
|
|
#include "gc.h"
|
2024-08-19 15:45:23 -04:00
|
|
|
|
|
|
|
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;
|
2024-08-19 15:45:23 -04:00
|
|
|
return vm;
|
|
|
|
}
|
|
|
|
|
|
|
|
void push(struct virtualMachine *vm, struct garbageObject *value) {
|
|
|
|
if (vm->stackSize >= STACK_MAX) {
|
2024-08-19 16:19:08 -04:00
|
|
|
fprintf(stderr, "ERROR: push(): refusing to overflow the stack!\n");
|
|
|
|
return;
|
2024-08-19 15:45:23 -04:00
|
|
|
}
|
|
|
|
vm->stack[vm->stackSize++] = value;
|
|
|
|
}
|
|
|
|
|
|
|
|
struct garbageObject *pop(struct virtualMachine *vm) {
|
|
|
|
if (vm->stackSize < 0) {
|
|
|
|
fprintf(stderr,
|
2024-08-19 16:19:08 -04:00
|
|
|
"ERROR: pop(): Stack size cannot be negative!");
|
|
|
|
return NULL;
|
2024-08-19 15:45:23 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
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);
|
|
|
|
|
2024-08-19 15:45:23 -04:00
|
|
|
struct garbageObject *obj = malloc(sizeof(struct garbageObject));
|
|
|
|
obj->type = type;
|
2024-08-19 16:19:08 -04:00
|
|
|
obj->mark = 0;
|
2024-08-20 10:55:53 -04:00
|
|
|
obj->next = vm->head;
|
|
|
|
vm->head = obj;
|
|
|
|
vm->refCount++;
|
2024-08-19 16:19:08 -04:00
|
|
|
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);
|
2024-08-19 15:45:23 -04:00
|
|
|
return obj;
|
|
|
|
}
|