ludic/selfhost/backend/emit_decl.ludic
Orkuncakilkaya ea2c6ab246
All checks were successful
bootstrap / cfree-fixpoint (push) Successful in 17s
ci / build-and-test (push) Successful in 1m13s
commit-lint / conventional-commits (push) Successful in 4s
docs / build-and-deploy (push) Successful in 19s
feat(testing): built-in test blocks + expect assertions, auto-run with pass/fail (#12)
A `test "name" { ... }` top-level block is discovered automatically and run by a
synthetic runner @main — no `entry` to write, nothing to register. Inside a test,
expect(cond) / expect_eq(a, b) / expect_near(a, b, tol) assert; on failure they
print `file:line: <what> failed (got G, want W)` and set a per-test fail flag but
keep going, so one run reports every failure. The runner prints `ok   - name` /
`FAIL - name` per test, a `== N passed, M failed ==` summary, and exits non-zero
if any test failed — so `ludic spec_test.ludic` drops straight into bin/x and CI.
expect_near carries the tolerance fixed-point / accumulated-integer game math need.

Frontend: new `test` keyword (parse_test -> N_TEST, collected in g_tests) and the
call node now carries its source line for the file:line messages. Backend:
emit_test_runner synthesises @fn__test_i bodies + the runner @main; the expect*
builtins lower to a branch-print-flag tail (emit_expect_fail). g_src_name (set in
main from the input path) supplies the filename. The compiler's own source has no
`test` blocks, so its self-compiled IR is unchanged and the C-free fixpoint holds.

- `test` wired into the vocabulary (ludic_syntax.h, JetBrains lexer, TextMate
  grammar) and documented (docs/language/testing/)
- examples/library/testing.ludic: a passing spec, guarded by a new spec_case in
  the regression suite (build, run, require exit 0 + the expected summary)

Coverage instrumentation (the biggest lift in #12) is left as a follow-up.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-31 14:27:45 +03:00

207 lines
8.9 KiB
Text

# emit_decl.ludic — functions, main, and the whole-program driver. A function's
# body is built into a scratch buffer so entry-block allocas can be spliced in
# ahead of it (see emit_alloca). Returns go through a %retval slot + `ret` label.
function emit_params_sig(d: Node) -> void {
var i = 0
while i < len(d.kids) {
if i > 0 { emit(", ") }
emit(llty(d.kids[i].ty)); emit(" %arg_"); emit(d.kids[i].s)
i = i + 1
}
}
function emit_fn(d: Node) -> void {
ll_t = 0; ll_lbl = 0; g_term = false; loc_reset(); nloop = 0
ret_ty = d.ty
let fbody = buf_new()
falloc = buf_new()
let saved = code
code = fbody
let rl = llty(ret_ty)
if not (rl == "void") { buf_puts(falloc, " %retval = alloca "); buf_puts(falloc, rl); buf_puts(falloc, "\n") }
# params: store each incoming argument into a stack slot
var i = 0
while i < len(d.kids) {
let p = d.kids[i]
let slot = emit_alloca(llty(p.ty))
emit(" store "); emit(llty(p.ty)); emit(" %arg_"); emit(p.s); emit(", ptr "); emit(slot); emit("\n")
loc_push(p.s, slot, p.ty)
i = i + 1
}
emit_block(d.a)
if not g_term { emit(" br label %ret\n") }
emit("ret:\n")
if (rl == "void") { emit(" ret void\n") }
else { let r = emit_bind(`load {rl}, ptr %retval`); emit(" ret "); emit(rl); emit(" "); emit(r); emit("\n") }
code = saved
emit("define "); emit(rl); emit(" @fn_"); emit(d.s); emit("("); emit_params_sig(d); emit(") {\nentry:\n")
emit(buf_str(falloc))
emit(buf_str(fbody))
emit("}\n\n")
}
function emit_main(d: Node) -> void {
ll_t = 0; ll_lbl = 0; g_term = false; loc_reset(); nloop = 0
ret_ty = "int"
let fbody = buf_new()
falloc = buf_new()
let saved = code
code = fbody
buf_puts(falloc, " %retval = alloca i32\n")
emit(" store i32 %argc, ptr @L_argc\n")
emit(" store ptr %argv, ptr @L_argv\n")
emit(" store i32 0, ptr %retval\n")
emit_block(d.a)
if not g_term { emit(" br label %ret\n") }
emit("ret:\n")
let r = emit_bind("load i32, ptr %retval")
emit(" ret i32 "); emit(r); emit("\n")
code = saved
emit("define i32 @main(i32 %argc, ptr %argv) {\nentry:\n")
emit(buf_str(falloc))
emit(buf_str(fbody))
emit("}\n")
}
# ---- the testing framework -------------------------------------------------
# A `test "name" { ... }` block lowers to a void function; `expect*` assertions
# inside it flip @L_test_fail. A synthetic runner @main runs every test, prints
# `ok - name` / `FAIL - name`, a summary, and exits non-zero if any failed.
# one test block -> a void function @fn__test_<idx> (mirrors emit_fn's shape).
function emit_test_fn(t: Node, idx: int) -> void {
ll_t = 0; ll_lbl = 0; g_term = false; loc_reset(); nloop = 0
ret_ty = "void"
let fbody = buf_new()
falloc = buf_new()
let saved = code
code = fbody
emit_block(t.a)
if not g_term { emit(" br label %ret\n") }
emit("ret:\n ret void\n")
code = saved
emit("define void @fn__test_"); emit(itoa(idx)); emit("() {\nentry:\n")
emit(buf_str(falloc))
emit(buf_str(fbody))
emit("}\n\n")
}
# emit every test body plus the runner @main that drives them.
function emit_test_runner() -> void {
emith("@L_test_fail = internal global i32 0\n")
emith("@.fmt_test_sum = private unnamed_addr constant [28 x i8] c\"== %d passed, %d failed ==\\0A\\00\"\n")
var i = 0
while i < len(g_tests) { emit_test_fn(g_tests[i], i); i = i + 1 }
if g_uses_expect { emith("@.fmt_expect = private unnamed_addr constant [22 x i8] c\"%s (got %d, want %d)\\0A\\00\"\n") }
ll_t = 0; ll_lbl = 0
emit("define i32 @main(i32 %argc, ptr %argv) {\nentry:\n")
emit(" store i32 %argc, ptr @L_argc\n")
emit(" store ptr %argv, ptr @L_argv\n")
emit(" %failed = alloca i32\n store i32 0, ptr %failed\n")
if has_ecs() { emit(" call void @rt_init()\n") }
i = 0
while i < len(g_tests) {
let okmsg = emit_str_const(`ok - {g_tests[i].s}`)
let failmsg = emit_str_const(`FAIL - {g_tests[i].s}`)
emit(" store i32 0, ptr @L_test_fail\n")
emit(` call void @fn__test_{itoa(i)}()\n`)
let f = emit_bind("load i32, ptr @L_test_fail")
let isbad = emit_bind(`icmp ne i32 {f}, 0`)
let lpass = lbl("tpass"); let lfail = lbl("tfail"); let ldone = lbl("tdone")
emit(` br i1 {isbad}, label %{lfail}, label %{lpass}\n`)
emit(`{lpass}:\n`)
emit(` call i32 (ptr, ...) @printf(ptr @.fmt_line, ptr {okmsg})\n`)
emit(` br label %{ldone}\n`)
emit(`{lfail}:\n`)
let cf = emit_bind("load i32, ptr %failed")
let cf1 = emit_bind(`add i32 {cf}, 1`)
emit(` store i32 {cf1}, ptr %failed\n`)
emit(` call i32 (ptr, ...) @printf(ptr @.fmt_line, ptr {failmsg})\n`)
emit(` br label %{ldone}\n`)
emit(`{ldone}:\n`)
i = i + 1
}
let totf = emit_bind("load i32, ptr %failed")
let passed = emit_bind(`sub i32 {itoa(len(g_tests))}, {totf}`)
emit(` call i32 (ptr, ...) @printf(ptr @.fmt_test_sum, i32 {passed}, i32 {totf})\n`)
let allok = emit_bind(`icmp eq i32 {totf}, 0`)
let rc = emit_bind(`select i1 {allok}, i32 0, i32 1`)
emit(` ret i32 {rc}\n}\n`)
}
function emit_program() -> void {
head = buf_new()
code = buf_new()
g_uses_str = false
g_uses_intstr = false
g_uses_strslice = false
g_uses_loopback = false
g_uses_expect = false
loc_name = new []pointer; loc_reg = new []pointer; loc_ty = new []pointer; loc_mut = new []int
brk_lbl = new []pointer; cnt_lbl = new []pointer
self_stk = new []pointer
mach_stk = new []Node
emit_header()
emit_extern_decls()
if has_ecs() { emit_ecs_storage() }
var i = 0
while i < len(prog) { if prog[i].kind == N_FN { emit_fn(prog[i]) }; i = i + 1 }
if len(g_events) > 0 { emit_event_fns() } # EV0: @ev_<E> event-dispatch functions
if has_ecs() and (len(g_events) > 0 or g_uses_query or g_uses_reflect) { emit_world_table() } # EV2/EV8: the mod reflection ABI (also powers Query.* / Reflect.*)
if has_ecs() { emit_ecs_allocator(); emit_snapshot() }
if has_ecs() { emit_net() } # N2/N3: @Sync serializers + @Owned storage (gated internally)
if has_ui() { emit_ui_build() }
if len(g_tests) > 0 { # a test file: synth a runner @main
if has_systems() { emit_game_defs() }
emit_test_runner()
}
else { if has_systems() and has_entry() { # N5: game owns its loop via `entry`
emit_game_defs() # system fns, hooks, tick helpers
i = 0
while i < len(prog) { if prog[i].kind == N_MAIN { emit_main(prog[i]) }; i = i + 1 }
}
else { if has_systems() { emit_game_main() } # the auto frame loop
else {
i = 0
while i < len(prog) { if prog[i].kind == N_MAIN { emit_main(prog[i]) }; i = i + 1 }
} } }
if g_uses_loopback { emit_loopback() } # built-in transport, after all net_send/net_poll uses are seen
if g_uses_str { emit_str_prelude() } # @fn_str_eq / @fn_str_concat, after all uses are seen
if g_uses_intstr { emit_int_str() } # @fn_int_str, for string(int) in interpolation
if g_uses_longstr { emit_long_str() } # @fn_long_str, for string(long) / long interpolation
if g_uses_strslice { emit_str_slice() } # @fn_str_slice, for s[a..b]
if g_uses_mathrt { emit_math_prelude() } # @fn_fx_sqrt / @fn_fx_sin + the sine table
if g_uses_textrt { emit_text_prelude() } # @fn_str_upper/lower/trim/repeat/pad builders
if g_uses_textrt2 { emit_text2_prelude() } # @fn_str_replace/join/split builders
if g_uses_hashrt { emit_hash_prelude() } # @fn_hash_fnv1a / @fn_hash_crc32 byte hashers
if g_uses_cryptort { emit_crypto_prelude() } # @fn_sha256_hex / @fn_hmac_sha256_hex + constant-time compare + CSPRNG
if g_uses_uuidrt { emit_uuid_prelude() } # @fn_uuid_v4 / @fn_uuid_v7 / parse / equals (over the crypto CSPRNG)
if g_uses_noisert { emit_noise_prelude() } # @fn_noise_value2/perlin2/simplex2/fbm2/cellular2 (Q16.16)
if g_uses_logrt { emit_log_prelude() } # @L_log_level + @fn_log_emit (levelled stderr sink)
if g_uses_osrt { emit_os_prelude() } # @fn_os_args/platform/arch/save_dir/... (libc env + uname)
if g_uses_unicodert { emit_unicode_prelude() } # @fn_uni_len/valid/decode/case/truncate/grapheme (UTF-8)
if g_uses_fsrt { emit_fs_prelude() } # @fn_fs_*/fn_path_*/fn_mime_* (libc + string ops)
if g_uses_datert { emit_datetime_prelude() } # @fn_days_from_civil / @fn_civil_from_days conversions
}
# Flush the emitted IR. With a null path it goes to stdout (the pipe the shell
# drivers read); with a path it is written to that file so ludicc can hand it to
# clang itself.
function ir_flush(path: pointer) -> bool {
let h = buf_str(head)
let c = buf_str(code)
if (path == null) { # raw IR to stdout (no trailing newline)
let out = file_stdout()
file_write(out, h, len(h))
file_write(out, c, len(c))
return true
}
let f = file_open(path, "wb")
if (f == null) { return false }
file_write(f, h, len(h))
file_write(f, c, len(c))
file_close(f)
return true
}