diff --git a/.clang-format b/.clang-format index 3048399..46da22a 100644 --- a/.clang-format +++ b/.clang-format @@ -1,4 +1,4 @@ -# C/C++ style for the code we own (pkg/html/shim): tabs (width 4, as the Odin code), +# C/C++ style for the code we own (pkg/jsc, pkg/html/shim): tabs (width 4, as the Odin code), # attached braces, 120 columns, `T *p`. Editors that format on save pick this up; `make fmt` applies it. BasedOnStyle: LLVM Language: Cpp diff --git a/CLAUDE.md b/CLAUDE.md index a1f980d..ab23820 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -158,7 +158,10 @@ appears in CI, read the code or shrink the CPU set; do not just re-run. wrappers exist only for **measured** hot natives; cold natives use the generic `host_native_create` path. The UTF-16→UTF-8 bridge belongs in `pkg/jsc`, not `environment.odin`. -- `make fmt` (`odin strip-semicolon`) before committing Odin. +- `make fmt` before committing: odinfmt (`odinfmt.json`: tabs, 120 columns, sorted + imports) and `odin strip-semicolon` for Odin, clang-format (`.clang-format`: tabs, + 120 columns) for C/C++. odinfmt ships with the OLS extension; pass + `ODINFMT=/path/to/odinfmt` when it is not on PATH. - **`if` always has braces, on their own lines** — no `if x do y`, no `if x {y}` — and **a blank line before and after every `if` statement**, unless it opens or closes a block or a `case` (a comment directly above belongs to the `if`). Applied @@ -166,10 +169,8 @@ appears in CI, read the code or shrink the CPU set; do not just re-run. `scripts/fmt-if.mjs`, which neither formatter covers. - **Declaration order in a file**, Odin and C alike: imports/includes (sorted), then constants, then types, then procedures — public ones first, private helpers last. - The formatters sort imports and includes (`odinfmt.json` `sort_imports`, - `.clang-format` `SortIncludes`); nothing reorders declarations, so this is on the - author. Applies to Larva's own packages (`pkg/html`); Lava-synced files keep Lava's - layout so a sync does not fight over it. + The formatters sort imports and includes; nothing reorders declarations, so this is + on the author. Do not retrofit existing files for it alone. ### Contract comments diff --git a/Makefile b/Makefile index 69d4833..4060b31 100644 --- a/Makefile +++ b/Makefile @@ -51,7 +51,7 @@ help: @printf '%s\n' ' make check-primordials Prototype-pollution ratchet (UPDATE=1 to lower; RAISE=--allow-raise)' @printf '%s\n' ' make check-jsc Locate JavaScriptCore dev files with install hints' @printf '%s\n' ' make check-native Verify native build dependencies via pkg-config' - @printf '%s\n' ' make fmt Strip optional semicolons in Odin sources' + @printf '%s\n' ' make fmt Format Odin (odinfmt, strip-semicolon) and C/C++ (clang-format)' @printf '%s\n' '' @printf '%s\n' 'Test' @printf '%s\n' ' make test Odin unit tests + oracle suites (alias of test-all on Unix)' @@ -377,20 +377,20 @@ test-lava-nohostfn: build # clean diff afterwards. ODINFMT ?= odinfmt +# Odin: odinfmt with odinfmt.json (tabs, 120 columns, sorted imports), then +# strip-semicolon. odinfmt ships with the OLS editor extension and is not on PATH by +# default; point ODINFMT at it. C/C++: clang-format with .clang-format; vendored +# picohttpparser opts out (its own .clang-format). fmt: + @if command -v $(ODINFMT) >/dev/null 2>&1; then \ + for d in cmd/lava pkg/jsc pkg/runtime pkg/std/sqlite pkg/html; do $(ODINFMT) -w $$d >/dev/null; done; \ + else echo 'make fmt: odinfmt not found; set ODINFMT=/path/to/odinfmt'; fi $(ODIN) strip-semicolon cmd/lava -collection:lava=. $(ODIN) strip-semicolon pkg/jsc -no-entry-point - # Larva's own C (.clang-format). pkg/jsc's C++ comes from Lava and is left as Lava - # formats it, so a sync does not fight over whitespace. - clang-format -i pkg/html/shim/*.c - # Odin in pkg/html: imports sorted, odinfmt.json there. odinfmt ships with the OLS editor - # extension, not on PATH by default; point ODINFMT at it. Lava-synced packages are left - # to strip-semicolon above, so a sync does not fight over whitespace. - @if command -v $(ODINFMT) >/dev/null 2>&1; then $(ODINFMT) -w pkg/html; \ - else echo 'make fmt: odinfmt not found; set ODINFMT=/path/to/odinfmt to format pkg/html'; fi + clang-format -i pkg/jsc/*.cpp pkg/html/shim/*.c # Multi-line blocks after if/else/for and blank lines around if: no formatter does # either (scripts/fmt-if.mjs). Run after odinfmt, whose convert_do makes the braces. - node scripts/fmt-if.mjs pkg/html + node scripts/fmt-if.mjs cmd/lava pkg/jsc pkg/runtime pkg/std/sqlite pkg/html # `rm` isn't a Windows command and can't take the $(RUNSCRIPT) prefix (bash would treat # `rm` as a script), so invoke the shell explicitly: $(SHELL) is Git Bash on Windows and diff --git a/cmd/lava/buffer_reentrancy_test.odin b/cmd/lava/buffer_reentrancy_test.odin index 84b33fc..1008edd 100644 --- a/cmd/lava/buffer_reentrancy_test.odin +++ b/cmd/lava/buffer_reentrancy_test.odin @@ -55,7 +55,11 @@ buffer_natives_detach_during_coercion :: proc(t: ^testing.T) { jsc.lava_jsc_init() gctx := jsc.JSGlobalContextCreate(nil) testing.expect(t, gctx != nil, "could not create a JSC global context") - if gctx == nil do return + + if gctx == nil { + return + } + defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -65,6 +69,7 @@ buffer_natives_detach_during_coercion :: proc(t: ^testing.T) { ctx, reentrancy_eval(ctx, "typeof ArrayBuffer.prototype.transfer === 'function'"), ) + if !has_transfer { // Older JSC without the detach primitive: nothing to exercise. return @@ -112,10 +117,7 @@ buffer_natives_detach_during_coercion :: proc(t: ^testing.T) { // bytes; the call must be a no-op (undefined return, no write). { view, _ := reentrancy_setup(ctx) - evil2 := reentrancy_eval( - ctx, - "({ valueOf: function () { globalThis.__ab.transfer(); return 2; } })", - ) + evil2 := reentrancy_eval(ctx, "({ valueOf: function () { globalThis.__ab.transfer(); return 2; } })") args := [2]jsc.JSValueRef{view, evil2} r := lava.buffer_swap_cb(ctx, nil, nil, 2, raw_data(args[:]), &exc) testing.expect(t, jsc.JSValueIsUndefined(ctx, r), "swapInPlace must no-op on a detached target") diff --git a/cmd/lava/dns_alloc_test.odin b/cmd/lava/dns_alloc_test.odin index 9d9e18a..b78bffc 100644 --- a/cmd/lava/dns_alloc_test.odin +++ b/cmd/lava/dns_alloc_test.odin @@ -5,8 +5,8 @@ import "base:runtime" import "core:mem" import "core:sync" import "core:testing" -import eventloop "lava:pkg/runtime/eventloop" import lava "lava:pkg/runtime" +import eventloop "lava:pkg/runtime/eventloop" // Guards the localized dns/fetch allocator fix (Dns_Lookup_Request.allocator). The // hostname is cloned inside the native dns lookup callback (a `proc "c"` where context @@ -83,11 +83,15 @@ watched_allocator_proc :: proc( mem.Allocator_Error, ) { w := cast(^Watched_Allocator)data + if mode == .Alloc || mode == .Alloc_Non_Zeroed { for p in WATCHED_PROCS { - if loc.procedure == p do sync.atomic_add(&w.hits, 1) + if loc.procedure == p { + sync.atomic_add(&w.hits, 1) + } } } + return w.backing.procedure(w.backing.data, mode, size, alignment, old_memory, old_size, loc) } diff --git a/cmd/lava/errors_test.odin b/cmd/lava/errors_test.odin index 4f7cb79..77475bd 100644 --- a/cmd/lava/errors_test.odin +++ b/cmd/lava/errors_test.odin @@ -23,10 +23,12 @@ node_error_factory :: proc(t: ^testing.T) { gclass := lava.make_global_class() gctx := jsc.JSGlobalContextCreate(gclass) testing.expect(t, gctx != nil, "could not create a JSC global context") + if gctx == nil { jsc.JSClassRelease(gclass) return } + defer jsc.JSClassRelease(gclass) defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -81,7 +83,11 @@ node_error_received_types :: proc(t: ^testing.T) { jsc.lava_jsc_init() gctx := jsc.JSGlobalContextCreate(nil) testing.expect(t, gctx != nil, "could not create a JSC global context") - if gctx == nil do return + + if gctx == nil { + return + } + defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -108,13 +114,18 @@ node_error_received_types :: proc(t: ^testing.T) { for c in cases { val := eval_value(ctx, c.expr) e := lava.err_invalid_arg_type(ctx, "x", "string", val) + if !testing.expectf(t, jsc.JSValueIsObject(ctx, e), "%s: error must be an object", c.expr) { continue } + msg, allocated := lava.value_to_string(ctx, lava.get_named(ctx, cast(jsc.JSObjectRef)e, "message")) want := fmt.tprintf("The \"x\" argument must be of type string. Received %s", c.want) testing.expectf(t, msg == want, "%s: got %q want %q", c.expr, msg, want) - if allocated do delete(msg) + + if allocated { + delete(msg) + } } } @@ -131,7 +142,11 @@ expect_error_shape :: proc( want_name, want_message, want_code: string, ) { testing.expect(t, jsc.JSValueIsObject(ctx, err), "error value must be an object") - if !jsc.JSValueIsObject(ctx, err) do return + + if !jsc.JSValueIsObject(ctx, err) { + return + } + obj := cast(jsc.JSObjectRef)err global := jsc.JSContextGetGlobalObject(ctx) @@ -143,6 +158,7 @@ expect_error_shape :: proc( check_string_prop(t, ctx, obj, "message", want_message) code_v := lava.get_named(ctx, obj, "code") + if want_code == "" { testing.expect(t, jsc.JSValueIsUndefined(ctx, code_v), "plain error should have no code") } else { @@ -154,19 +170,29 @@ expect_error_shape :: proc( check_string_prop :: proc(t: ^testing.T, ctx: jsc.JSContextRef, obj: jsc.JSObjectRef, prop, want: string) { v := lava.get_named(ctx, obj, prop) got, allocated := lava.value_to_string(ctx, v) - defer if allocated do delete(got) + defer if allocated { + delete(got) + } testing.expectf(t, got == want, "%s: got %q want %q", prop, got, want) } @(private = "file") eval_truthy :: proc(ctx: jsc.JSContextRef, expr: string) -> bool { c_expr, err := strings.clone_to_cstring(expr, context.temp_allocator) - if err != nil do return false + + if err != nil { + return false + } + src := jsc.JSStringCreateWithUTF8CString(c_expr) defer jsc.JSStringRelease(src) exc: jsc.JSValueRef v := jsc.JSEvaluateScript(ctx, src, nil, nil, 1, &exc) - if exc != nil || v == nil do return false + + if exc != nil || v == nil { + return false + } + return jsc.JSValueToBoolean(ctx, v) } @@ -175,11 +201,19 @@ eval_truthy :: proc(ctx: jsc.JSContextRef, expr: string) -> bool { @(private = "file") eval_value :: proc(ctx: jsc.JSContextRef, expr: string) -> jsc.JSValueRef { c_expr, err := strings.clone_to_cstring(expr, context.temp_allocator) - if err != nil do return jsc.JSValueMakeUndefined(ctx) + + if err != nil { + return jsc.JSValueMakeUndefined(ctx) + } + src := jsc.JSStringCreateWithUTF8CString(c_expr) defer jsc.JSStringRelease(src) exc: jsc.JSValueRef v := jsc.JSEvaluateScript(ctx, src, nil, nil, 1, &exc) - if exc != nil || v == nil do return jsc.JSValueMakeUndefined(ctx) + + if exc != nil || v == nil { + return jsc.JSValueMakeUndefined(ctx) + } + return v } diff --git a/cmd/lava/eval_report_hook_test.odin b/cmd/lava/eval_report_hook_test.odin index 2b342c5..77032d8 100644 --- a/cmd/lava/eval_report_hook_test.odin +++ b/cmd/lava/eval_report_hook_test.odin @@ -3,8 +3,8 @@ package main import "core:strings" import "core:testing" -import eventloop "lava:pkg/runtime/eventloop" import lava "lava:pkg/runtime" +import eventloop "lava:pkg/runtime/eventloop" // Pins eval's `report` hook (runtime.odin, Result_Hook): it fires exactly once per eval, // with the Result eval returns, and BEFORE eval's deferred teardown — the loop is not diff --git a/cmd/lava/fd_census_test.odin b/cmd/lava/fd_census_test.odin index ec893df..ee566a7 100644 --- a/cmd/lava/fd_census_test.odin +++ b/cmd/lava/fd_census_test.odin @@ -22,15 +22,29 @@ RUNNER_THREADS :: #config(ODIN_TEST_THREADS, 0) // skipped — when RUNNER_THREADS != 1. fd_census :: proc(timerfds_only := false) -> int { handle, err := os.open("/proc/self/fd") - if err != nil do return -1 + + if err != nil { + return -1 + } + defer os.close(handle) infos, read_err := os.read_directory(handle, -1, context.temp_allocator) - if read_err != nil do return -1 - if !timerfds_only do return len(infos) + + if read_err != nil { + return -1 + } + + if !timerfds_only { + return len(infos) + } + n := 0 for fi in infos { target, lerr := os.read_link(fi.fullpath, context.temp_allocator) - if lerr == nil && strings.contains(target, "timerfd") do n += 1 + + if lerr == nil && strings.contains(target, "timerfd") { + n += 1 + } } return n } diff --git a/cmd/lava/fetch_url_test.odin b/cmd/lava/fetch_url_test.odin index b0b617d..707a401 100644 --- a/cmd/lava/fetch_url_test.odin +++ b/cmd/lava/fetch_url_test.odin @@ -43,7 +43,11 @@ parse_http_url_cases :: proc(t: ^testing.T) { for c in cases { host, port, path, scheme, ok := lava_runtime.parse_http_url(c.url) testing.expectf(t, ok == c.ok, "%s: ok=%v want %v", c.url, ok, c.ok) - if !c.ok do continue + + if !c.ok { + continue + } + testing.expectf(t, host == c.host, "%s: host=%q want %q", c.url, host, c.host) testing.expectf(t, port == c.port, "%s: port=%d want %d", c.url, port, c.port) testing.expectf(t, path == c.path, "%s: path=%q want %q", c.url, path, c.path) @@ -78,7 +82,11 @@ fetch_parse_chunk_size_cases :: proc(t: ^testing.T) { for c in cases { size, ok := lava_runtime.fetch_parse_chunk_size(c.text) testing.expectf(t, ok == c.ok, "%q: ok=%v want %v", c.text, ok, c.ok) - if !c.ok do continue + + if !c.ok { + continue + } + testing.expectf(t, size == c.size, "%q: size=%d want %d", c.text, size, c.size) } } diff --git a/cmd/lava/fs_write_payload_test.odin b/cmd/lava/fs_write_payload_test.odin index bafbe36..b5e0f80 100644 --- a/cmd/lava/fs_write_payload_test.odin +++ b/cmd/lava/fs_write_payload_test.odin @@ -47,7 +47,11 @@ fs_write_payload_rejects_a_window_resized_by_its_own_getter :: proc(t: ^testing. jsc.lava_jsc_init() gctx := jsc.JSGlobalContextCreate(nil) testing.expect(t, gctx != nil, "could not create a JSC global context") - if gctx == nil do return + + if gctx == nil { + return + } + defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -57,7 +61,10 @@ fs_write_payload_rejects_a_window_resized_by_its_own_getter :: proc(t: ^testing. ctx, payload_eval(ctx, "new ArrayBuffer(8, { maxByteLength: 8 }).resizable === true"), ) - if !resizable do return + + if !resizable { + return + } // A genuine DataView over a 4096-byte resizable buffer, carrying an own byteOffset // getter that shrinks the backing to 8 bytes and an own byteLength that keeps @@ -85,9 +92,7 @@ fs_write_payload_rejects_a_window_resized_by_its_own_getter :: proc(t: ^testing. // The buffer is 8 bytes live by the time the pointer is taken. Anything longer is // memory past the allocation — which is what shipped, at 4096. - live := int( - jsc.JSValueToNumber(ctx, payload_eval(ctx, "globalThis.__ab.byteLength"), nil), - ) + live := int(jsc.JSValueToNumber(ctx, payload_eval(ctx, "globalThis.__ab.byteLength"), nil)) testing.expectf(t, live == 8, "the getter should have resized the backing to 8, got %d", live) testing.expectf( t, diff --git a/cmd/lava/global_surface_test.odin b/cmd/lava/global_surface_test.odin index 2cad5a5..ff2a50c 100644 --- a/cmd/lava/global_surface_test.odin +++ b/cmd/lava/global_surface_test.odin @@ -269,14 +269,7 @@ if (present.length !== 0) throw new Error('web surface still has: ' + present.jo @(test) global_surface_alternates_on_one_thread :: proc(t: ^testing.T) { expect_ok :: proc(t: ^testing.T, what: string, result: lava.Result) { - testing.expectf( - t, - result.status == .Ok, - "%s: status=%v message=%q", - what, - result.status, - result.message, - ) + testing.expectf(t, result.status == .Ok, "%s: status=%v message=%q", what, result.status, result.message) } first := lava.eval(NODE_NAMES_PRESENT, "", nil) @@ -306,7 +299,12 @@ global_surface_web_skips_stdio :: proc(t: ^testing.T) { node_init, node_events := surface_events_compiles(t, .Node) web_init, web_events := surface_events_compiles(t, .Web) - testing.expectf(t, node_events == 0, "node: resolving events compiled %d factories (want 0: stdio loaded it)", node_events) + testing.expectf( + t, + node_events == 0, + "node: resolving events compiled %d factories (want 0: stdio loaded it)", + node_events, + ) testing.expectf(t, web_events > 0, "web: resolving events compiled nothing — stdio was instantiated at init") testing.expectf( t, @@ -325,10 +323,12 @@ surface_events_compiles :: proc(t: ^testing.T, surface: lava.Global_Surface) -> gclass := lava.make_global_class() gctx := jsc.JSGlobalContextCreate(gclass) testing.expect(t, gctx != nil, "could not create a JSC global context") + if gctx == nil { jsc.JSClassRelease(gclass) return } + defer jsc.JSClassRelease(gclass) defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx diff --git a/cmd/lava/host_native_alloc_test.odin b/cmd/lava/host_native_alloc_test.odin index 676335c..dd0c3fc 100644 --- a/cmd/lava/host_native_alloc_test.odin +++ b/cmd/lava/host_native_alloc_test.odin @@ -86,7 +86,9 @@ host_native_tables_are_not_charged_to_the_eval_allocator :: proc(t: ^testing.T) stray := 0 for _, entry in track.allocation_map { - if strings.contains(entry.location.file_path, "host_natives.odin") do stray += 1 + if strings.contains(entry.location.file_path, "host_natives.odin") { + stray += 1 + } } testing.expectf( t, diff --git a/cmd/lava/host_native_failclosed_test.odin b/cmd/lava/host_native_failclosed_test.odin index 8ab74ea..e943965 100644 --- a/cmd/lava/host_native_failclosed_test.odin +++ b/cmd/lava/host_native_failclosed_test.odin @@ -35,12 +35,18 @@ import lava "lava:pkg/runtime" host_native_dispatch_miss_fails_closed :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) // Without the private-ABI path nothing is registered, so there is no miss to // observe and every assertion below would pass vacuously. - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } state := lava.new_runtime_state(nil) jsc.JSObjectSetPrivate(jsc.JSContextGetGlobalObject(c.ctx), cast(rawptr)state) diff --git a/cmd/lava/host_native_registry_test.odin b/cmd/lava/host_native_registry_test.odin index 7767e4c..ab38063 100644 --- a/cmd/lava/host_native_registry_test.odin +++ b/cmd/lava/host_native_registry_test.odin @@ -47,22 +47,35 @@ other_cb :: proc "c" ( eval_text :: proc(ctx: jsc.JSContextRef, source: string) -> (string, bool) { c_src, err := strings.clone_to_cstring(source, context.temp_allocator) - if err != nil do return "", false + + if err != nil { + return "", false + } + js_src := jsc.JSStringCreateWithUTF8CString(c_src) defer jsc.JSStringRelease(js_src) exception: jsc.JSValueRef value := jsc.JSEvaluateScript(ctx, js_src, nil, nil, 1, &exception) - if exception != nil || value == nil do return "", false + + if exception != nil || value == nil { + return "", false + } + // jsc_value_to_string_or_default hands back an OWNED context.allocator buffer. // The test runner installs a per-test tracking allocator and reports whatever is // still live when the test ends, so a helper that keeps it would print a leak on // every assertion here and bury a real one in the code under test. owned, got := lava.jsc_value_to_string_or_default(ctx, value) - if !got do return "", true // empty string: nothing was allocated + + if !got {return "", true} // empty string: nothing was allocated defer delete(owned) copied, clone_err := strings.clone(owned, context.temp_allocator) - if clone_err != nil do return "", false + + if clone_err != nil { + return "", false + } + return copied, true } @@ -77,10 +90,12 @@ Context :: struct { make_context :: proc() -> (Context, bool) { class := lava.make_global_class() gctx := jsc.JSGlobalContextCreate(class) + if gctx == nil { jsc.JSClassRelease(class) return {}, false } + return Context{class = class, gctx = gctx, ctx = cast(jsc.JSContextRef)gctx}, true } @@ -93,12 +108,11 @@ destroy_context :: proc(c: Context) { // this file asserts on it rather than skipping quietly: a silently vacuous // regression test is the failure mode this whole area keeps hitting. host_path_active :: proc(t: ^testing.T, ctx: jsc.JSContextRef) -> bool { - if jsc.host_calls_active(ctx) do return true - testing.expect( - t, - false, - "private-ABI host-call path inactive — this test cannot observe what it pins", - ) + if jsc.host_calls_active(ctx) { + return true + } + + testing.expect(t, false, "private-ABI host-call path inactive — this test cannot observe what it pins") return false } @@ -110,15 +124,25 @@ host_path_active :: proc(t: ^testing.T, ctx: jsc.JSContextRef) -> bool { host_native_sweep_is_scoped_to_its_context :: proc(t: ^testing.T) { a, a_ok := make_context() testing.expect(t, a_ok, "could not create the first JSC global context") - if !a_ok do return + + if !a_ok { + return + } + defer destroy_context(a) b, b_ok := make_context() testing.expect(t, b_ok, "could not create the second JSC global context") - if !b_ok do return + + if !b_ok { + return + } + defer destroy_context(b) - if !host_path_active(t, a.ctx) do return + if !host_path_active(t, a.ctx) { + return + } state_a := lava.new_runtime_state(nil) jsc.JSObjectSetPrivate(jsc.JSContextGetGlobalObject(a.ctx), cast(rawptr)state_a) @@ -142,12 +166,7 @@ host_native_sweep_is_scoped_to_its_context :: proc(t: ^testing.T) { lava.destroy_runtime_state(a.ctx, state_a) after, ok_after := eval_text(b.ctx, "String(probe())") - testing.expectf( - t, - ok_after && after == "42", - "tearing down context A broke context B's registry: %q", - after, - ) + testing.expectf(t, ok_after && after == "42", "tearing down context A broke context B's registry: %q", after) } // The cache exists so per-instance injections (the fs.Stats methods) reuse one @@ -158,10 +177,16 @@ host_native_sweep_is_scoped_to_its_context :: proc(t: ^testing.T) { host_native_create_dedupes_per_callback_and_name :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } state := lava.new_runtime_state(nil) jsc.JSObjectSetPrivate(jsc.JSContextGetGlobalObject(c.ctx), cast(rawptr)state) @@ -169,7 +194,10 @@ host_native_create_dedupes_per_callback_and_name :: proc(t: ^testing.T) { first := lava.host_native_create(c.ctx, "probe", answer_cb) testing.expect(t, first != nil, "host_native_create returned nil on the host path") - if first == nil do return + + if first == nil { + return + } same := lava.host_native_create(c.ctx, "probe", answer_cb) testing.expect(t, same == first, "same (callback, name) minted a second function object") @@ -181,11 +209,7 @@ host_native_create_dedupes_per_callback_and_name :: proc(t: ^testing.T) { testing.expect(t, renamed != nil && renamed != first, "a different name reused the same cell") different := lava.host_native_create(c.ctx, "probe", other_cb) - testing.expect( - t, - different != nil && different != first, - "a different callback reused the same cell", - ) + testing.expect(t, different != nil && different != first, "a different callback reused the same cell") } // Pins the host path's construct-result divergence require.odin documents: @@ -199,20 +223,23 @@ host_native_create_dedupes_per_callback_and_name :: proc(t: ^testing.T) { host_native_construct_returns_call_result :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } state := lava.new_runtime_state(nil) jsc.JSObjectSetPrivate(jsc.JSContextGetGlobalObject(c.ctx), cast(rawptr)state) defer lava.destroy_runtime_state(c.ctx, state) lava.inject_native_function(c.ctx, jsc.JSContextGetGlobalObject(c.ctx), "probe", answer_cb) - text, ok_eval := eval_text( - c.ctx, - "(function(){ var r = new probe(); return typeof r + ':' + String(r); })()", - ) + text, ok_eval := eval_text(c.ctx, "(function(){ var r = new probe(); return typeof r + ':' + String(r); })()") testing.expectf(t, ok_eval && text == "number:42", "host-path construct result changed: %q", text) } @@ -224,10 +251,16 @@ host_native_construct_returns_call_result :: proc(t: ^testing.T) { host_native_create_declines_without_state :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } // Deliberately no JSObjectSetPrivate: this is the bare embedder context. fn := lava.host_native_create(c.ctx, "probe", answer_cb) @@ -292,10 +325,16 @@ failing_allocator :: proc() -> mem.Allocator { host_native_create_survives_allocation_failure :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } // Built normally, so its maps and its own allocation come from the real // allocator; only the name-clone allocator is faulted. Overwriting the field @@ -317,12 +356,7 @@ host_native_create_survives_allocation_failure :: proc(t: ^testing.T) { // The binding still has to work — an OOM in our cache is not an OOM in JSC. lava.inject_native_function(c.ctx, jsc.JSContextGetGlobalObject(c.ctx), "probe", answer_cb) text, ok_eval := eval_text(c.ctx, "String(probe())") - testing.expectf( - t, - ok_eval && text == "42", - "binding broke when the registry could not cache it: %q", - text, - ) + testing.expectf(t, ok_eval && text == "42", "binding broke when the registry could not cache it: %q", text) } // host_throw's contract is that its RETURN says whether the exception was really @@ -337,7 +371,11 @@ host_native_create_survives_allocation_failure :: proc(t: ^testing.T) { host_throw_reports_whether_it_raised :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) testing.expect( diff --git a/cmd/lava/jsc_predicates_test.odin b/cmd/lava/jsc_predicates_test.odin index ebf2e2a..e15c63c 100644 --- a/cmd/lava/jsc_predicates_test.odin +++ b/cmd/lava/jsc_predicates_test.odin @@ -27,7 +27,11 @@ jsc_value_predicates :: proc(t: ^testing.T) { jsc.lava_jsc_init() gctx := jsc.JSGlobalContextCreate(nil) testing.expect(t, gctx != nil, "could not create a JSC global context") - if gctx == nil do return + + if gctx == nil { + return + } + defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -126,11 +130,13 @@ predicate_probe_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { probe_called = true + if argument_count >= 4 { probe_false_is_false = jsc.JSValueToBoolean(ctx, arguments[0]) == false probe_undef_is_undefined = jsc.JSValueIsUndefined(ctx, arguments[1]) probe_obj_is_object = jsc.JSValueIsObject(ctx, arguments[2]) probe_num_not_object = !jsc.JSValueIsObject(ctx, arguments[3]) } + return jsc.JSValueMakeUndefined(ctx) } diff --git a/cmd/lava/lazy_builtins_test.odin b/cmd/lava/lazy_builtins_test.odin index f038cde..316677a 100644 --- a/cmd/lava/lazy_builtins_test.odin +++ b/cmd/lava/lazy_builtins_test.odin @@ -22,10 +22,12 @@ builtin_factories_compile_on_first_require :: proc(t: ^testing.T) { gclass := lava.make_global_class() gctx := jsc.JSGlobalContextCreate(gclass) testing.expect(t, gctx != nil, "could not create a JSC global context") + if gctx == nil { jsc.JSClassRelease(gclass) return } + defer jsc.JSClassRelease(gclass) defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -41,7 +43,9 @@ builtin_factories_compile_on_first_require :: proc(t: ^testing.T) { embedded := 0 for dir in lava.EMBEDDED_JS_DIRS { for file in dir.files { - if strings.has_suffix(file.name, ".js") do embedded += 1 + if strings.has_suffix(file.name, ".js") { + embedded += 1 + } } } @@ -91,7 +95,10 @@ builtin_factories_compile_on_first_require :: proc(t: ^testing.T) { // ponytail: count-based for internal/ ids; record compiled ids on Runtime_State if // that coincidence ever matters. check-js-graph.test.mjs keeps this list current. for id in STATIC_EAGER { - if !strings.has_prefix(id, "node/") do continue + if !strings.has_prefix(id, "node/") { + continue + } + before := state.builtin_compiles src, _ := strings.concatenate({"require('node:", id[len("node/"):], "') != null"}, context.temp_allocator) testing.expectf(t, run_bool(ctx, src), "%s did not load", id) @@ -104,7 +111,54 @@ builtin_factories_compile_on_first_require :: proc(t: ^testing.T) { // The static eager set, sorted. Must equal eagerModules() — asserted by // scripts/check-js-graph.test.mjs, which parses this literal. @(private = "file") -STATIC_EAGER :: [?]string{"internal/abort", "internal/blob", "internal/buffer", "internal/crypto/hash", "internal/crypto/hkdf", "internal/crypto/pbkdf2", "internal/crypto/random", "internal/crypto/scrypt", "internal/crypto/util", "internal/encoding", "internal/errors", "internal/fetch", "internal/fetch/body", "internal/fetch/headers", "internal/fetch/request", "internal/fetch/response", "internal/file", "internal/idna", "internal/primordials", "internal/punycode", "internal/stdio", "internal/streams/add-abort-signal", "internal/streams/destroy", "internal/streams/duplex", "internal/streams/end-of-stream", "internal/streams/legacy", "internal/streams/passthrough", "internal/streams/pipeline", "internal/streams/readable", "internal/streams/transform", "internal/streams/utils", "internal/streams/writable", "internal/structured_clone", "internal/url", "internal/webstreams/queuingstrategies", "internal/webstreams/readablestream", "internal/webstreams/transformstream", "internal/webstreams/util", "internal/webstreams/writablestream", "node/buffer", "node/crypto", "node/events", "node/stream", "node/stream/web", "node/string_decoder", "node/url"} +STATIC_EAGER :: [?]string { + "internal/abort", + "internal/blob", + "internal/buffer", + "internal/crypto/hash", + "internal/crypto/hkdf", + "internal/crypto/pbkdf2", + "internal/crypto/random", + "internal/crypto/scrypt", + "internal/crypto/util", + "internal/encoding", + "internal/errors", + "internal/fetch", + "internal/fetch/body", + "internal/fetch/headers", + "internal/fetch/request", + "internal/fetch/response", + "internal/file", + "internal/idna", + "internal/primordials", + "internal/punycode", + "internal/stdio", + "internal/streams/add-abort-signal", + "internal/streams/destroy", + "internal/streams/duplex", + "internal/streams/end-of-stream", + "internal/streams/legacy", + "internal/streams/passthrough", + "internal/streams/pipeline", + "internal/streams/readable", + "internal/streams/transform", + "internal/streams/utils", + "internal/streams/writable", + "internal/structured_clone", + "internal/url", + "internal/webstreams/queuingstrategies", + "internal/webstreams/readablestream", + "internal/webstreams/transformstream", + "internal/webstreams/util", + "internal/webstreams/writablestream", + "node/buffer", + "node/crypto", + "node/events", + "node/stream", + "node/stream/web", + "node/string_decoder", + "node/url", +} @(private = "file") run_bool :: proc(ctx: jsc.JSContextRef, src: string) -> bool { @@ -113,6 +167,10 @@ run_bool :: proc(ctx: jsc.JSContextRef, src: string) -> bool { defer jsc.JSStringRelease(script) exception: jsc.JSValueRef value := jsc.JSEvaluateScript(ctx, script, nil, nil, 1, &exception) - if exception != nil do return false + + if exception != nil { + return false + } + return jsc.JSValueToBoolean(ctx, value) } diff --git a/cmd/lava/main.odin b/cmd/lava/main.odin index f0cf04b..01abd6e 100644 --- a/cmd/lava/main.odin +++ b/cmd/lava/main.odin @@ -80,10 +80,12 @@ run_command :: proc(args: []string) { // LAVA_WORKERS>1 runs the file on N shared-nothing worker loops (Slice 3a). Resolved fail-fast: // an invalid value or an unsupported platform exits non-zero rather than silently degrading. worker_count, count_ok, count_msg := lava_runtime.lava_resolve_worker_count() + if !count_ok { fmt.eprintfln("lava: %s", count_msg) os.exit(2) } + if worker_count > 1 { // args is [scriptPath, ...userArgs]; the supervisor reads the file once and runs N workers. os.exit(lava_runtime.lava_run_workers(args[0], worker_count, args[1:])) @@ -116,6 +118,7 @@ print_result :: proc(result: lava_runtime.Result, user_data: rawptr) { if len(result.message) > 0 { lava_runtime.process_write(os.stdout, result.message, "\n") } + return } @@ -146,13 +149,25 @@ html_command :: proc(args: []string) { opts.list_scripts = true case a == "--chunk": i += 1 - if i == len(args) do usage() + + if i == len(args) { + usage() + } + n, ok := strconv.parse_int(args[i]) - if !ok || n <= 0 do usage() + + if !ok || n <= 0 { + usage() + } + chunk = n case a == "--select": i += 1 - if i == len(args) do usage() + + if i == len(args) { + usage() + } + css = args[i] case len(a) > 1 && a[0] == '-', path != "": usage() @@ -160,12 +175,17 @@ html_command :: proc(args: []string) { path = a } } - if path == "" do usage() + + if path == "" { + usage() + } data: []byte err: os.Error - if path == "-" do data, err = os.read_entire_file_from_file(os.stdin, context.allocator) - else do data, err = os.read_entire_file(path, context.allocator) + + if path == + "-" {data, err = os.read_entire_file_from_file(os.stdin, context.allocator)} else {data, err = os.read_entire_file(path, context.allocator)} + if err != nil { fmt.eprintfln("lava html: cannot read %s: %v", path, err) os.exit(1) @@ -174,10 +194,18 @@ html_command :: proc(args: []string) { report :: proc(p: ^html.Parser, script: html.Node, user_data: rawptr) { o := cast(^Html_Options)user_data o.scripts += 1 - if !o.list_scripts do return + + if !o.list_scripts { + return + } + // An SVG