58e0de7ae1
Co-authored-by: aider (openrouter/moonshotai/kimi-k2.6) <aider@aider.chat>
61 lines
1.8 KiB
C
61 lines
1.8 KiB
C
#include "forth.h"
|
|
|
|
// Input tokenizer
|
|
char* next_token(void) {
|
|
if (input_ptr == NULL) return NULL;
|
|
while (*input_ptr != '\0' && isspace((unsigned char)*input_ptr)) {
|
|
input_ptr++;
|
|
}
|
|
if (*input_ptr == '\0') return NULL;
|
|
char* start = input_ptr;
|
|
while (*input_ptr != '\0' && !isspace((unsigned char)*input_ptr)) {
|
|
input_ptr++;
|
|
}
|
|
if (*input_ptr != '\0') {
|
|
*input_ptr = '\0';
|
|
input_ptr++;
|
|
}
|
|
return start;
|
|
}
|
|
|
|
// Interpreter functions
|
|
void inner_interpreter(void) {
|
|
while (ip != NULL) {
|
|
Cell current = *ip;
|
|
ip++; // Move to next cell
|
|
current.word->code(current.word);
|
|
}
|
|
}
|
|
|
|
void process_token(const char* token) {
|
|
Word* w = lookup_word(token);
|
|
if (w != NULL) {
|
|
if (state == 0) { // Interpret mode
|
|
if (w->code == do_docolon) { // Colon definition
|
|
ret_push_ip(NULL); // Return address to stop interpreter
|
|
ip = w->body;
|
|
inner_interpreter();
|
|
} else { // Primitive word
|
|
w->code(w);
|
|
}
|
|
} else { // Compile mode
|
|
if (w->flags & (1 << 7)) { // Immediate word: execute now
|
|
if (w->code == do_docolon) {
|
|
ret_push_ip(NULL);
|
|
ip = w->body;
|
|
inner_interpreter();
|
|
} else {
|
|
w->code(w);
|
|
}
|
|
} else { // Normal word: compile into current definition
|
|
if (compile_idx >= COMPILE_BUF_SIZE) {
|
|
printf("Compile buffer full\n");
|
|
return;
|
|
}
|
|
compile_buf[compile_idx++] = (Cell){.word = w};
|
|
}
|
|
}
|
|
} else { // Not a known word: try to parse as number
|
|
char* end;
|
|
long v = strtol(token, &end, 10);
|
|
if |