feat: add modular Forth interpreter implementation
Co-authored-by: aider (openrouter/tencent/hy3-preview:free) <aider@aider.chat>
This commit is contained in:
+103
@@ -0,0 +1,103 @@
|
||||
#include "forth.h"
|
||||
|
||||
// Global variables
|
||||
int32_t data_stack[DATA_STACK_SIZE];
|
||||
int sp = -1;
|
||||
Cell ret_stack[RET_STACK_SIZE];
|
||||
int rp = -1;
|
||||
Cell* ip = NULL;
|
||||
|
||||
Word dict[DICT_SIZE];
|
||||
int dict_idx = 0;
|
||||
Word* dict_head = NULL;
|
||||
Cell dict_bodies[BODY_SIZE];
|
||||
int body_idx = 0;
|
||||
|
||||
int state = 0;
|
||||
Cell compile_buf[COMPILE_BUF_SIZE];
|
||||
int compile_idx = 0;
|
||||
char compiling_name[MAX_NAME_LEN + 1];
|
||||
|
||||
char input_buf[INPUT_BUF_SIZE];
|
||||
char* input_ptr = NULL;
|
||||
|
||||
Cell* compile_stack[COMPILE_STACK_SIZE];
|
||||
int compile_sp = -1;
|
||||
|
||||
int32_t user_mem[USER_MEMORY_SIZE];
|
||||
int32_t* here = &user_mem[0];
|
||||
|
||||
// Stack helpers
|
||||
void data_push(int32_t val) {
|
||||
if (sp < DATA_STACK_SIZE - 1) {
|
||||
data_stack[++sp] = val;
|
||||
} else {
|
||||
printf("Data stack overflow\n");
|
||||
}
|
||||
}
|
||||
|
||||
int32_t data_pop(void) {
|
||||
if (sp >= 0) {
|
||||
return data_stack[sp--];
|
||||
} else {
|
||||
printf("Data stack underflow\n");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void ret_push_ip(Cell* val) {
|
||||
if (rp < RET_STACK_SIZE - 1) {
|
||||
rp++;
|
||||
ret_stack[rp].cell_ptr = val;
|
||||
} else {
|
||||
printf("Return stack overflow\n");
|
||||
}
|
||||
}
|
||||
|
||||
Cell* ret_pop_ip(void) {
|
||||
if (rp >= 0) {
|
||||
Cell* res = ret_stack[rp].cell_ptr;
|
||||
rp--;
|
||||
return res;
|
||||
} else {
|
||||
printf("Return stack underflow\n");
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
void ret_push_num(int32_t val) {
|
||||
if (rp < RET_STACK_SIZE - 1) {
|
||||
rp++;
|
||||
ret_stack[rp].num = val;
|
||||
} else {
|
||||
printf("Return stack overflow\n");
|
||||
}
|
||||
}
|
||||
|
||||
int32_t ret_pop_num(void) {
|
||||
if (rp >= 0) {
|
||||
int32_t res = ret_stack[rp].num;
|
||||
rp--;
|
||||
return res;
|
||||
} else {
|
||||
printf("Return stack underflow\n");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void compile_push(Cell* addr) {
|
||||
if (compile_sp < COMPILE_STACK_SIZE - 1) {
|
||||
compile_stack[++compile_sp] = addr;
|
||||
} else {
|
||||
printf("Compile stack overflow\n");
|
||||
}
|
||||
}
|
||||
|
||||
Cell* compile_pop(void) {
|
||||
if (compile_sp >= 0) {
|
||||
return compile_stack[compile_sp--];
|
||||
} else {
|
||||
printf("Compile stack underflow\n");
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user