undar-lang-fixed-length/arch/linux/tui/main.c

157 lines
2.9 KiB
C

#include "../../../vm/vm.h"
#include "../../../tools/compiler/compiler.h"
#include <stdio.h>
#define MEMORY_SIZE 65536
#define CODE_SIZE 8192
#define STACK_SIZE 1024
u8 lmem[MEMORY_SIZE] = {0};
u8 lcode[CODE_SIZE] = {0};
u32 lstack[STACK_SIZE] = {0};
Frame lframes[STACK_SIZE] = {0};
void reset() {
pc = 0;
cp = 0;
mp = 0;
fp = 0;
sp = 0;
interrupt = 0;
status = 0;
}
bool init_vm() {
mem = lmem;
code = lcode;
stack = lstack;
frames = lframes;
reset();
return true;
}
void error(const char* msg) {
printf("%s", msg);
}
bool table_realloc(ScopeTable *table) {
USED(table);
// static so do nothing;
return true;
}
u32 syscall(u32 id, u32 mem_ptr) {
u32 size;
switch(id) {
case SYSCALL_CONSOLE_WRITE: {
u32 size = *(u32*)&mem[mem_ptr];
u8 *ptr = &mem[mem_ptr + 4];
for (u32 i = 0; i < size; i++) {
putchar(*(ptr++));
}
return 0;
}
case SYSCALL_CONSOLE_READ: {
u8 *ptr = &mem[mp];
mcpy(ptr, &size, sizeof(u32));
ptr += 4;
for (u32 i = 0; i < size; i++) {
u8 ch = getchar();
if (ch == '\0')
break;
if (ch == '\n')
break;
*(ptr++) = ch;
}
ptr[size] = '\0';
mp += 4 + size + 1;
}
}
return 1; // generic error
}
//static void repl() {
// ScopeTable st;
// char line[1024];
// for (;;) {
// printf("> ");
//
// if (!fgets(line, sizeof(line), stdin)) {
// printf("\n");
// break;
// }
//
// reset();
//
// compile(&st, line);
//
// while(step_vm()) {}
//
// syscall(SYSCALL_CONSOLE_WRITE, stack[0]);
// }
//}
void fib() {
u8 fib_ptr = 10;
code[cp++] = OP_PUSH_8;
code[cp++] = 35;
code[cp++] = OP_PUSH_8;
code[cp++] = fib_ptr;
code[cp++] = OP_CALL;
code[cp++] = OP_INT_TO_STR;
code[cp++] = OP_PUSH_8;
code[cp++] = SYSCALL_CONSOLE_WRITE;
code[cp++] = OP_SYSCALL;
code[cp++] = OP_HALT;
/* fib (int n) int */
code[cp++] = OP_SET_IMM;
code[cp++] = 0;
/* if (n < 2) { */
code[cp++] = OP_GET_IMM;
code[cp++] = 0;
code[cp++] = OP_PUSH_8;
code[cp++] = 2;
code[cp++] = OP_LTS;
code[cp++] = OP_PUSH_8;
u8 if_true = cp + 5;
code[cp++] = if_true;
code[cp++] = OP_JNZ;
code[cp++] = OP_PUSH_8;
u8 if_false = cp + 5;
code[cp++] = if_false;
code[cp++] = OP_JMP;
code[cp++] = OP_GET_IMM;
code[cp++] = 0;
code[cp++] = OP_RETURN;
code[cp++] = OP_GET_IMM;
code[cp++] = 0;
code[cp++] = OP_PUSH_8;
code[cp++] = 2;
code[cp++] = OP_SUB_INT;
code[cp++] = OP_PUSH_8;
code[cp++] = fib_ptr;
code[cp++] = OP_CALL;
code[cp++] = OP_GET_IMM;
code[cp++] = 0;
code[cp++] = OP_PUSH_8;
code[cp++] = 1;
code[cp++] = OP_SUB_INT;
code[cp++] = OP_PUSH_8;
code[cp++] = fib_ptr;
code[cp++] = OP_CALL;
code[cp++] = OP_ADD_INT;
code[cp++] = OP_RETURN;
while(step_vm()) {}
}
i32 main() {
init_vm();
fib();
//repl();
return 0;
}