-
-
Save yvan-sraka/fe9baa0cfe4ed9796b24df52d7fcbe59 to your computer and use it in GitHub Desktop.
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> | |
#include <stdlib.h> | |
typedef enum { | |
MOV, | |
SET, | |
ADD, | |
SUB, | |
JMP, | |
SYSCALL, | |
EXIT | |
} keyword; | |
typedef enum { | |
GET, | |
PUT | |
} syscalls; | |
typedef struct { | |
keyword opcode; | |
int arg1; | |
int arg2; | |
} instruction; | |
int main(void) { | |
int *registers = malloc(16 * sizeof(char)); | |
instruction bytecode[] = { | |
{ SET, 0, 0 }, | |
{ SET, 3, 1 }, | |
{ SYSCALL, GET, 1 }, | |
{ SYSCALL, PUT, 1 }, | |
{ JMP, 1, 0 }, | |
}; | |
size_t pc = 0; | |
while (1) { | |
int a1 = bytecode[pc].arg1; | |
int a2 = bytecode[pc].arg2; | |
int *r1 = registers + a1; | |
int *r2 = registers + a2; | |
switch(bytecode[pc].opcode) { | |
case MOV: | |
*r1 = *r2; ++pc; break; | |
case SET: | |
*r2 = a1; ++pc; break; | |
case ADD: | |
*r2 += *r1; ++pc; break; | |
case SUB: | |
*r2 -= *r1; ++pc; break; | |
case JMP: | |
if (!*r2) pc = *r1; | |
else ++pc; break; | |
case SYSCALL: | |
switch(a1) { | |
case PUT: putchar(*r2); break; | |
case GET: (*r2) = getchar(); break; | |
} | |
++pc; break; | |
default: | |
return a1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment