From e1c68b8e80ec7f8bc5146a30e101bd9046e55ef9 Mon Sep 17 00:00:00 2001 From: zongor Date: Fri, 10 Jul 2026 22:12:19 -0700 Subject: [PATCH] Fix calls with call stack --- compiler.c | 34 +++++++++++++++++++++++++++++++--- compiler.h | 8 +++++++- test/tal/add.tal | 2 +- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/compiler.c b/compiler.c index f855959..f4df485 100644 --- a/compiler.c +++ b/compiler.c @@ -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; diff --git a/compiler.h b/compiler.h index 98d3d6a..385bfed 100644 --- a/compiler.h +++ b/compiler.h @@ -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; diff --git a/test/tal/add.tal b/test/tal/add.tal index ba291ca..00cf7f9 100644 --- a/test/tal/add.tal +++ b/test/tal/add.tal @@ -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