Scan for globals in c_program(). During the first pass (which finds function definitions), also collect top-level var declarations:
At the top of c_program(), before scanning for functions:
// Scan for top-level globals
c_global_count = 0;
source = input;
pos = 0;
skip();
var brace_depth: i32 = 0;
while (pos < source.len) {
if (source[pos] == '{') { brace_depth += 1; pos += 1; continue; }
if (source[pos] == '}') { brace_depth -= 1; pos += 1; continue; }
if (brace_depth == 0 and is_letter(cur())) {
const s: usize = pos;
const w: []const u8 = read_name();
if (streq(w, "var") or streq(w, "const")) {
const vn: []const u8 = read_name();
if (cur() == ':') { pos += 1; skip(); _ = read_name(); }
c_global_names[c_global_count] = vn;
c_global_count += 1;
} else if (streq(w, "fn")) {
// skip entire fn (will be handled in function pass)
while (cur() != '{' and cur() != 0) { pos += 1; }
if (cur() == '{') { skip_block(); }
} else {
pos = s;
pos += 1;
}
} else {
pos += 1;
}
}
Then emit the global declarations:
for (0..c_global_count) |i| {
emit_str("(global $");
emit_str(c_global_names[i]);
emit_str(" (mut i64) (i64.const 0))\n");
}