Skip to content

Instantly share code, notes, and snippets.

@yvan-sraka
Created August 17, 2021 19:06
Show Gist options
  • Save yvan-sraka/fe9baa0cfe4ed9796b24df52d7fcbe59 to your computer and use it in GitHub Desktop.
Save yvan-sraka/fe9baa0cfe4ed9796b24df52d7fcbe59 to your computer and use it in GitHub Desktop.
#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