Created
December 12, 2017 21:40
-
-
Save Spriithy/e16eee372c2292d1b9bb5b51bfc2f1dc to your computer and use it in GitHub Desktop.
A minimalistic VM in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "tvm.c" | |
int main(void) | |
{ | |
int code[] = { | |
Const, | |
-5564, | |
Const, | |
184841, | |
Add, | |
Print, | |
Exit, | |
}; | |
execute(code); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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