refactor: make interpreter portable with static pools and I/O hooks

Co-authored-by: aider (openrouter/moonshotai/kimi-k2.6) <aider@aider.chat>
This commit is contained in:
2026-05-03 22:35:21 +03:00
parent b115744991
commit f033187c6c
6 changed files with 145 additions and 153 deletions
+17 -19
View File
@@ -19,17 +19,12 @@ char* next_token(void) {
}
// Ensure compile_buf has room for at least 'needed' more cells
void ensure_compile_cap(int32_t needed) {
while (compile_idx + needed > compile_cap) {
int32_t new_cap = compile_cap ? compile_cap * 2 : 256;
Cell *tmp = realloc(compile_buf, new_cap * sizeof(Cell));
if (!tmp) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
compile_buf = tmp;
compile_cap = new_cap;
int ensure_compile_cap(int32_t needed) {
if (compile_idx + needed > compile_cap) {
forth_printf("Compile buffer overflow\n");
return 0;
}
return 1;
}
// Inner interpreter (unchanged)
@@ -62,7 +57,7 @@ void process_token(const char* token) {
w->code(w);
}
} else { // Compile normal word
ensure_compile_cap(1);
if (!ensure_compile_cap(1)) return;
compile_buf[compile_idx++] = (Cell){.word = w};
}
}
@@ -74,27 +69,30 @@ void process_token(const char* token) {
data_push((int64_t)v);
} else { // Compile lit + number
if (!w_lit) {
fprintf(stderr, "Fatal: lit word not found\n");
forth_printf("Fatal: lit word not found\n");
return;
}
ensure_compile_cap(2);
if (!ensure_compile_cap(2)) return;
compile_buf[compile_idx++] = (Cell){.word = w_lit};
compile_buf[compile_idx++] = (Cell){.num = (int64_t)v};
}
} else {
printf("Unknown word: '%s'\n", token);
forth_printf("Unknown word: '%s'\n", token);
}
}
}
void outer_interpreter(void) {
static char line_buf[256];
while (1) {
printf("ok ");
fflush(stdout);
ssize_t n = getline(&input_buf, &input_buf_cap, stdin);
if (n < 0) {
forth_printf("ok ");
forth_fflush();
if (fgets(line_buf, sizeof(line_buf), stdin) == NULL) {
break;
}
input_buf = line_buf;
input_buf_cap = sizeof(line_buf);
size_t n = strlen(input_buf);
if (n > 0 && input_buf[n - 1] == '\n') {
input_buf[n - 1] = '\0';
}
@@ -104,5 +102,5 @@ void outer_interpreter(void) {
process_token(tok);
}
}
printf("\n");
forth_printf("\n");
}