From e97abba2539e450eb028c20ae68529a2af3eb25f Mon Sep 17 00:00:00 2001 From: "Jonathan D.A. Jewell" <6759885+hyperpolymath@users.noreply.github.com> Date: Mon, 11 May 2026 05:33:28 +0200 Subject: [PATCH] fix(codegen): resolve top-level const refs in ExprVar (#73) ExprVar name lookup fell through to UnboundVariable after checking locals and variant_tags, never reaching func_indices where TopConst bindings are stored (negative sentinel: global_idx = -(k+1)). Add a GlobalGet fallback so const identifiers used inside fn bodies compile correctly. check already passed; compile now passes too. --- lib/codegen.ml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/codegen.ml b/lib/codegen.ml index 0863a04..9e6534a 100644 --- a/lib/codegen.ml +++ b/lib/codegen.ml @@ -436,7 +436,13 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = UnboundVariable even though the parser accepts it. *) begin match List.assoc_opt id.name ctx.variant_tags with | Some tag -> Ok (ctx, [I32Const (Int32.of_int tag)]) - | None -> Error (UnboundVariable id.name) + | None -> + (* Top-level const bindings are stored in func_indices with a + negative sentinel: actual global index = -(k+1). *) + begin match List.assoc_opt id.name ctx.func_indices with + | Some k when k < 0 -> Ok (ctx, [GlobalGet (-(k + 1))]) + | _ -> Error (UnboundVariable id.name) + end end end