Fix calls with call stack

This commit is contained in:
zongor 2026-07-10 22:12:19 -07:00
parent bff2f3e55a
commit e1c68b8e80
3 changed files with 39 additions and 5 deletions

View File

@ -10,6 +10,7 @@ Emitter *emitter;
Arena *arena;
List *code;
List *memory;
CallStack *call_stack;
/****************************************************
* Scope
@ -107,6 +108,23 @@ scope_add_symbol(const char *name, u32 name_length, SymbolType type, u32 size)
sizeof(Symbol));
}
void CallStack_push(CallStack *stack, Symbol *symbol) {
if (stack->count >= stack->capacity) {
emitter->error("call stack full", 16, parser->previous.line);
}
stack->symbols[stack->count] = symbol;
stack->count++;
}
Symbol *CallStack_pop(CallStack *stack) {
if (stack->count == 0) {
emitter->error("call stack empty", 17, parser->previous.line);
}
stack->count--;
return stack->symbols[stack->count];
}
bool
is_global(void)
{
@ -590,7 +608,7 @@ variable(void)
}
if(sym->type == SYMBOL_FUNCTION) {
parser->call_fn = sym;
CallStack_push(call_stack, sym);
return;
}
@ -862,6 +880,8 @@ function(void)
void
call(void)
{
Symbol *call_fn;
if(!check(TOKEN_RPAREN)) {
do {
expression();
@ -869,8 +889,9 @@ call(void)
}
consume(TOKEN_RPAREN);
emitter->emit_arena_fn_call(arena, code, parser->call_fn);
parser->current_type = parser->call_fn->secondary_type;
call_fn = CallStack_pop(call_stack);
emitter->emit_arena_fn_call(arena, code, call_fn);
parser->current_type = call_fn->secondary_type;
return;
}
@ -1120,6 +1141,13 @@ bool
compile(Arena *a, List *c, List *m, Emitter *e, char *source)
{
Parser p = {0};
Symbol *syms[50] = {0};
CallStack cs;
cs.symbols = syms;
cs.count = 0;
cs.capacity = 50;
call_stack = &cs;
arena = a;
emitter = e;
code = c;

View File

@ -15,6 +15,13 @@ struct scope_s {
u32 locals_offset;
};
typedef struct call_stack_s CallStack;
struct call_stack_s {
Symbol **symbols;
u32 count;
u32 capacity;
};
typedef enum {
PREC_NONE,
PREC_ASSIGNMENT, /* = */
@ -39,7 +46,6 @@ struct parse_rule_s {
};
struct parser_s {
Symbol *call_fn;
Scope *current_scope;
List *scopes;
Token current;

View File

@ -1,7 +1,7 @@
|100
LIT2r 0000
#0001 #0001 add_ nat_to_str_ add_
#0001 #0001 add_ nat_to_str_ print_
POP2r BRK
@add_ ( a b -- res )
OVR2r LIT2r 0004 SUB2r