refactor word compilation to allow recursion

This commit is contained in:
tocariimaa 2025-02-05 14:13:55 -03:00
parent 96709aa013
commit e111afb040

32
pila.c
View file

@ -71,9 +71,8 @@ struct RpnState {
char *rsp; /* reader start pointer */ char *rsp; /* reader start pointer */
char *rep; /* " end " */ char *rep; /* " end " */
/* current word compilation state */ /* current word compilation state */
UserWord cur_comp; Word *cur_compw;
isize cur_comp_cap; isize cur_compw_cap;
Str cur_comp_name;
}; };
struct DictionaryEntry { struct DictionaryEntry {
@ -347,11 +346,20 @@ emit_nat(RpnState *st)
void void
compile_start(RpnState *st, Str wn) compile_start(RpnState *st, Str wn)
{ {
Word *w = malloc(sizeof(*w));
w->name = wn;
w->kind = WORD_USER;
UserWord uw;
uw.words = calloc(16, sizeof(Word));
uw.len = 0;
w->uword = uw;
st->cur_compw_cap = 16;
st->cur_compw = w;
st->compiling = true; st->compiling = true;
st->cur_comp_name = wn;
st->cur_comp.words = calloc(16, sizeof(Word)); add_word(st, w);
st->cur_comp.len = 0;
st->cur_comp_cap = 16;
} }
void void
@ -378,13 +386,9 @@ compile_end_nat(RpnState *st)
signal_error(st, "not in compiling mode"); signal_error(st, "not in compiling mode");
return; return;
} }
Word *w = malloc(sizeof(*w)); Assert(st->cur_compw != nil);
st->compiling = false; st->compiling = false;
w->name = st->cur_comp_name; add_word(st, st->cur_compw);
w->kind = WORD_USER;
w->uword = st->cur_comp;
add_word(st, w);
} }
Str Str
@ -643,7 +647,7 @@ eval(RpnState *st, Str src)
if (w->kind == WORD_NATIVE && w->nat == compile_end_nat) { if (w->kind == WORD_NATIVE && w->nat == compile_end_nat) {
w->nat(st); w->nat(st);
} else { } else {
st->cur_comp.words[st->cur_comp.len++] = w; st->cur_compw->uword.words[st->cur_compw->uword.len++] = w;
} }
} }
} else if (*st->rsp == '\\' || *st->rsp == '(') { } else if (*st->rsp == '\\' || *st->rsp == '(') {