Skip to content

Instantly share code, notes, and snippets.

@Spriithy
Created December 12, 2017 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Spriithy/e16eee372c2292d1b9bb5b51bfc2f1dc to your computer and use it in GitHub Desktop.
Save Spriithy/e16eee372c2292d1b9bb5b51bfc2f1dc to your computer and use it in GitHub Desktop.
A minimalistic VM in C
#include "tvm.c"
int main(void)
{
int code[] = {
Const,
-5564,
Const,
184841,
Add,
Print,
Exit,
};
execute(code);
return 0;
}
#include <stdio.h>
enum {
Const,
Add,
Sub,
Jeq,
Jne,
Load,
Store,
Print,
Exit
};
#define STACK_SIZE 1024
#define push(val) stack[sp++] = val
#define pop() stack[--sp]
int execute(int* code)
{
int stack[STACK_SIZE];
int mem[512];
int pc = 0, sp = 0;
int x, y, n;
while (1) {
switch (code[pc]) {
case Const:
push(code[++pc]);
break;
case Add:
x = pop();
y = pop();
push(x + y);
break;
case Sub:
x = pop();
y = pop();
push(x - y);
break;
case Jeq:
x = pop();
y = pop();
n = pop();
if (x == y)
pc += n;
break;
case Jne:
x = pop();
y = pop();
n = pop();
if (x != y)
pc += n;
break;
case Load:
n = pop();
push(mem[n]);
break;
case Store:
x = pop();
n = pop();
mem[n] = x;
break;
case Print:
x = pop();
printf("%d\n", x);
break;
case Exit:
return stack[pc];
}
pc++;
}
return stack[sp];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment