#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define STACK_SIZE 2048
#define STACK_TYPE_INT 1
typedef struct {
unsigned char stack[STACK_SIZE];
unsigned char* head;
} VMS;
static void VMS_init(VMS* inst)
{
memset(inst, 0, sizeof(VMS));
inst->head = inst->stack + STACK_SIZE;
}
static inline size_t VMS_space(const VMS* inst)
{
return inst->head - inst->stack;
}
static void VMS_assert(const VMS* inst, size_t space)
{
assert(VMS_space(inst) >= space);
}
static inline int VMS_empty(const VMS* inst)
{
return inst->head == (inst->stack + STACK_SIZE);
}
static void VMS_put(VMS* inst, unsigned char ch)
{
VMS_assert(inst, 1)
--(inst->head);
*(inst->head) = ch;
}
static void VMS_put_int(VMS* inst, int num)
{
VMS_assert(inst, sizeof(int));
inst->head -= sizeof(int);
*(int*)(inst->head) = num;
}
/**
* Puts an int on the stack with a marked type
*/
static void VMS_putm_int(VMS* inst, int num)
{
VMS_assert(inst, sizeof(int) + 1);
inst->head -= sizeof(int);
*(int*)(inst->head) = num;
--(inst->head);
*(inst->head) = STACK_TYPE_INT;
}
static void VMS_sum_int(VMS* inst)
{
int sum = *(int*)(inst->head);
inst->head += sizeof(int);
*(int*)(inst->head) += sum;
}
static int VMS_head_int(const VMS* inst)
{
return *(int*)(inst->head);
}
#define VMS_INSC_STOP 0
#define VMS_INSC_PUSH 1
#define VMS_INSC_SUM 2
static void VMS_run_instruc(VMS* inst, const unsigned char* instruc, size_t size)
{
const unsigned char* instruc_end = instruc + size;
while (instruc != instruc_end) {
switch (*instruc) {
case VMS_INSC_STOP:
return;
case VMS_INSC_PUSH:
break;
case VMS_INSC_SUM:
break;
default:
fprintf("Got unknown instruction %u\n", *instruc);
exit(2);
}
}
}
int main(int argc, char const *argv[])
{
puts("Stack Machine PoC");
VMS a;
VMS_init(&a);
VMS_put_int(&a, 5);
VMS_put_int(&a, 5);
VMS_sum_int(&a);
printf("result is %d\n", VMS_head_int(&a));
return 0;
}