Files
ai-forth-experiment/forth_core.c
T
haxala1r b115744991 fix: qdup/tuck/2swap bugs, getline, and cached word pointers
Co-authored-by: aider (openrouter/moonshotai/kimi-k2.6) <aider@aider.chat>
2026-05-03 21:39:52 +03:00

131 lines
2.9 KiB
C

#include "forth.h"
// Dynamic storage
int64_t *data_stack = NULL;
int32_t data_sp = -1;
int32_t data_cap = 0;
Cell *ret_stack = NULL;
int32_t rp = -1;
int32_t ret_cap = 0;
Cell* ip = NULL;
Word* dict_head = NULL;
int state = 0;
Cell *compile_buf = NULL;
int32_t compile_idx = 0;
int32_t compile_cap = 0;
char compiling_name[MAX_NAME_LEN + 1] = {0};
char* input_buf = NULL;
size_t input_buf_cap = 0;
char* input_ptr = NULL;
int64_t *compile_stack = NULL;
int32_t compile_sp = -1;
int32_t compile_stack_cap = 0;
Cell *user_mem = NULL;
int64_t user_mem_size = 0;
Cell* here = NULL;
Word* w_exit = NULL;
Word* w_docolon = NULL;
Word* w_lit = NULL;
Word* w_branch = NULL;
Word* w_zbranch = NULL;
Word* w_dot_quote_inner = NULL;
// ---------- Data stack ----------
void data_push(int64_t val) {
if (data_sp + 1 >= data_cap) {
int32_t new_cap = data_cap ? data_cap * 2 : 128;
int64_t *tmp = realloc(data_stack, new_cap * sizeof(int64_t));
if (!tmp) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
data_stack = tmp;
data_cap = new_cap;
}
data_stack[++data_sp] = val;
}
int64_t data_pop(void) {
if (data_sp < 0) {
fprintf(stderr, "Data stack underflow\n");
return 0;
}
return data_stack[data_sp--];
}
// ---------- Return stack (holds Cell values) ----------
static void ensure_ret_stack(void) {
if (rp + 1 >= ret_cap) {
int32_t new_cap = ret_cap ? ret_cap * 2 : 128;
Cell *tmp = realloc(ret_stack, new_cap * sizeof(Cell));
if (!tmp) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
ret_stack = tmp;
ret_cap = new_cap;
}
}
void ret_push_ip(Cell* val) {
ensure_ret_stack();
rp++;
ret_stack[rp].ptr = val; // store pointer in the 'ptr' member
}
Cell* ret_pop_ip(void) {
if (rp < 0) {
fprintf(stderr, "Return stack underflow\n");
return NULL;
}
return ret_stack[rp--].ptr;
}
void ret_push_num(int64_t val) {
ensure_ret_stack();
rp++;
ret_stack[rp].num = val;
}
int64_t ret_pop_num(void) {
if (rp < 0) {
fprintf(stderr, "Return stack underflow (num)\n");
return 0;
}
return ret_stack[rp--].num;
}
// ---------- Compile stack (indices) ----------
static void ensure_compile_stack(void) {
if (compile_sp + 1 >= compile_stack_cap) {
int32_t new_cap = compile_stack_cap ? compile_stack_cap * 2 : 64;
int64_t *tmp = realloc(compile_stack, new_cap * sizeof(int64_t));
if (!tmp) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
compile_stack = tmp;
compile_stack_cap = new_cap;
}
}
void compile_push(int64_t idx) {
ensure_compile_stack();
compile_stack[++compile_sp] = idx;
}
int64_t compile_pop(void) {
if (compile_sp < 0) {
fprintf(stderr, "Compile stack underflow\n");
return -1;
}
return compile_stack[compile_sp--];
}