From 2e426678699adcb5646645774dee044cb1e00d2b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 21:31:46 +0000 Subject: [PATCH] feat(codegen-bun): intrinsics are first-class values Owner ruling 2026-12-01 ("First-class wrappers"). An intrinsic such as `len`, `string_sub` or `trim` used as a value, not called, was emitted as a bare name with no JS binding, so calling it threw a ReferenceError (`let f = len; f(s)`; `apply(len, s)`). Declared externs were already wrapped (#818). Non-extern intrinsics now are too. - `builtin_arity`: each builtin's arity, read once from its type in `Typecheck.register_builtins`. One source of truth, no hand-kept list. - `wrap_builtin_value`: the lowering wrapped in an arrow of that arity. It is shared with the #818 extern path, which now uses it, so there is one wrapping rule. An awaiting lowering keeps the bare name, as #818 did. Coverage: - All 40 Bun builtins the type checker types are wrapped, and the new suite fails if a typed builtin ever is not. - The remaining Bun builtins are stdlib `extern fn`s, covered by #818. - Two names, `acos` and `asin`, have a Bun lowering but are neither resolvable nor typed, so no program can use them. That predates this change and is reported in the PR. Tests: - tests/codegen-bun/intrinsic_values: len and to_uppercase passed to a higher-order fn; trim, string_sub, string_find and int_to_string bound with `let`. It fails on main with `ReferenceError: len is not defined`. - test/test_intrinsic_values.ml: coverage, arity from type, and wrapper text. - dune runtest: 852 pass. Bun harnesses: pass. Ledger: ports #856's part (main is red on property 3) and advances the stamp to 4a55253. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDiosfvobXq67wbduuK --- docs/SOUNDNESS.adoc | 22 ++++++- lib/codegen_deno.ml | 58 ++++++++++++++++--- test/test_intrinsic_values.ml | 53 +++++++++++++++++ test/test_main.ml | 1 + tests/codegen-bun/intrinsic_values.affine | 39 +++++++++++++ .../codegen-bun/intrinsic_values.harness.mjs | 13 +++++ tools/soundness-anchors.sha256 | 1 - 7 files changed, 177 insertions(+), 10 deletions(-) create mode 100644 test/test_intrinsic_values.ml create mode 100644 tests/codegen-bun/intrinsic_values.affine create mode 100644 tests/codegen-bun/intrinsic_values.harness.mjs diff --git a/docs/SOUNDNESS.adoc b/docs/SOUNDNESS.adoc index 21bccb16..77449ac2 100644 --- a/docs/SOUNDNESS.adoc +++ b/docs/SOUNDNESS.adoc @@ -4,7 +4,7 @@ // Freshness stamp — a real main-ancestor commit (survives squash-merge); advance // it (and --reseal) in any change that touches a soundness path. See "Keeping // this honest" and tools/check-soundness-ledger.sh (property 4). -:ground-truth-sha: 84eca60 +:ground-truth-sha: 4a55253 :ground-truth-date: 2026-12-01 :stamp-verified-by: tools/check-soundness-ledger.sh :toc: macro @@ -311,6 +311,26 @@ write into the literal region. Layout invariant: `test_wasm_heap_literals_intact_after_alloc` — run under Bun's WASI; `test_wasm_heap_exhaustion_traps`); `lib/codegen.ml` `memory_layout_of_datas` / `check_memory_layout` + +| #833 +| The tree-walking interpreter — the oracle the compiled backends are compared +against — runs the programs the checker accepts and agrees with Bun-ESM on +them. It used to refuse a function that calls itself, one that calls a later +declaration, any `let mut` / `const mut` assignment, and any use of an +imported `Some` / `None` / `Ok` / `Err` (all loud). One shape was *silent*: an +early `return` evaluated its operand and carried on, so +`if c { return 1; } 2` yielded `2`. (The assignment arm also ignored a +compound operator — `a += 5` would have stored `5` — which a +`let mut` program could not reach, because the assignment failed first.) `affinescript eval` also type-checked +with its own fold of `Typecheck.check_decl`, without the signature +pre-registration of `Typecheck.check_program`, so it rejected forward and +mutual references that `check` and `compile` accept; it now calls +`check_program`. Not changed: `eval` still does not run the borrow checker +(`check` and `compile` do), so it accepts programs they reject. +| `fixed` +| `test/test_interp_eval.ml` (18 cases: each program passes the full frontend, +then its interpreter output is compared with the expected lines and with the +Bun-ESM output of the same program; all 18 fail on `4248912`). |=== == Still open — read before claiming "sound" diff --git a/lib/codegen_deno.ml b/lib/codegen_deno.ml index b51dc1e9..1a44a6d7 100644 --- a/lib/codegen_deno.ml +++ b/lib/codegen_deno.ml @@ -1849,6 +1849,35 @@ let rec lowers_to_statements = function | ExprMatch _ | ExprIf _ | ExprBlock _ -> true | _ -> false +(** Arity of each builtin, read from its type in the type checker's + builtin table ([Typecheck.register_builtins]): one source of truth, so + no arity list is kept here by hand. A builtin used as a value is wrapped + in an arrow of this many parameters (owner ruling 2026-12-01: + first-class intrinsics on Bun). *) +let builtin_arity : (string, int) Hashtbl.t Lazy.t = lazy ( + let tctx = Typecheck.create_context (Symbol.create ()) in + Typecheck.register_builtins tctx; + let arities = Hashtbl.create 128 in + let rec arrows = function + | Types.TArrow (_, _, r, _) -> 1 + arrows r + | _ -> 0 + in + Hashtbl.iter (fun name (sc : Types.scheme) -> + Hashtbl.replace arities name (arrows sc.sc_body)) + tctx.Typecheck.name_types; + arities) + +(* A builtin lowering wrapped as a JS arrow of [arity] parameters, or + [None] when its lowering awaits: an async wrapper would also need every + call through the value awaited, which the value's callers do not do. *) +let wrap_builtin_value (lower : string list -> string) (arity : int) : string option = + let ps = List.init arity (Printf.sprintf "__a%d") in + let body = lower ps in + if (try ignore (Str.search_forward (Str.regexp "\\bawait\\b") body 0); true + with Not_found -> false) + then None + else Some (Printf.sprintf "((%s) => %s)" (String.concat ", " ps) body) + (** Render an expression as JavaScript using the names and host in [ctx]. Lambdas are synchronous arrows; known qualified constructors refer to their emitted bindings. Nested statements can update integer tracking. @@ -1865,14 +1894,27 @@ let rec gen_expr ctx (expr : expr) : string = && not (Hashtbl.mem ctx.locals id.name) -> (* #818: an extern used as a value has no JS binding of its own name; wrap its builtin lowering in an arrow of the declared arity. *) - let ps = List.init (Hashtbl.find ctx.externs id.name) (Printf.sprintf "__a%d") in - let body = (Hashtbl.find (builtins_for ctx) id.name) ps in - (* snip: an await-based lowering keeps the bare name (as before #818); - an async wrapper also needs awaited calls through the value. *) - if (try ignore (Str.search_forward (Str.regexp "\\bawait\\b") body 0); true - with Not_found -> false) - then resolve_var ctx id.name - else Printf.sprintf "((%s) => %s)" (String.concat ", " ps) body + (* An await-based lowering keeps the bare name (as before #818): an + async wrapper also needs awaited calls through the value. *) + (match wrap_builtin_value (Hashtbl.find (builtins_for ctx) id.name) + (Hashtbl.find ctx.externs id.name) with + | Some js -> js + | None -> resolve_var ctx id.name) + | ExprVar id + when Hashtbl.mem (builtins_for ctx) id.name + && not (Hashtbl.mem ctx.local_fns id.name) + && not (Hashtbl.mem ctx.locals id.name) -> + (* A non-extern intrinsic (`len`, `string_sub`, `char_to_string`, ...) + used as a value. It has no JS binding of its own name, so it used + to be emitted bare and failed with a ReferenceError when called. + Wrap its lowering like an extern's (#818), at the arity its type + gives. *) + (match Hashtbl.find_opt (Lazy.force builtin_arity) id.name with + | Some k when k > 0 -> + (match wrap_builtin_value (Hashtbl.find (builtins_for ctx) id.name) k with + | Some js -> js + | None -> resolve_var ctx id.name) + | _ -> resolve_var ctx id.name) | ExprVar name -> resolve_var ctx name.name | ExprApp (func, args) -> (match func with diff --git a/test/test_intrinsic_values.ml b/test/test_intrinsic_values.ml new file mode 100644 index 00000000..6a6874a3 --- /dev/null +++ b/test/test_intrinsic_values.ml @@ -0,0 +1,53 @@ +(* SPDX-License-Identifier: MPL-2.0 *) +(* Copyright (c) 2026 Jonathan D.A. Jewell *) +(** Intrinsics as values on Bun-ESM (owner ruling 2026-12-01: first-class + wrappers for every intrinsic). + + An intrinsic such as [len] used as a value, not called, was emitted as a + bare name with no JS binding, so calling it failed with a ReferenceError. + Declared externs were already wrapped (#818); non-extern intrinsics now + are too, at the arity their type gives in the type checker's builtin + table ([Codegen_deno.builtin_arity]). + + This suite pins coverage: every Bun builtin the type checker types gets + a wrapper, so a builtin added later cannot silently fall back to a bare + name. Behaviour is pinned by tests/codegen-bun/intrinsic_values. *) + +open Affinescript + +let every_typed_bun_builtin_is_wrapped () = + let arities = Lazy.force Codegen_deno.builtin_arity in + let unwrapped = ref [] and wrapped = ref 0 in + Hashtbl.iter (fun name lower -> + match Hashtbl.find_opt arities name with + | Some k when k > 0 -> + (match Codegen_deno.wrap_builtin_value lower k with + | Some js -> + incr wrapped; + if not (String.length js > 2 && String.sub js 0 2 = "((") then + unwrapped := (name ^ " (malformed: " ^ js ^ ")") :: !unwrapped + | None -> unwrapped := (name ^ " (awaits)") :: !unwrapped) + | _ -> ()) + Codegen_deno.bun_builtins; + if !unwrapped <> [] then + Alcotest.failf "typed Bun builtins with no value wrapper: %s" + (String.concat ", " (List.sort compare !unwrapped)); + Alcotest.(check bool) "at least the string/number intrinsics are wrapped" true (!wrapped >= 30) + +let arity_comes_from_the_type () = + let arities = Lazy.force Codegen_deno.builtin_arity in + List.iter (fun (name, k) -> + Alcotest.(check (option int)) name (Some k) (Hashtbl.find_opt arities name)) + [ ("len", 1); ("string_sub", 3); ("string_find", 2); ("int_to_string", 1) ] + +let wrapper_text () = + let lower = Hashtbl.find Codegen_deno.bun_builtins "string_sub" in + Alcotest.(check (option string)) "string_sub wrapper" + (Some "((__a0, __a1, __a2) => __as_strSub(__a0, __a1, __a2))") + (Codegen_deno.wrap_builtin_value lower 3) + +let tests = [ + Alcotest.test_case "every typed Bun builtin is wrapped as a value" `Quick every_typed_bun_builtin_is_wrapped; + Alcotest.test_case "arity comes from the builtin's type" `Quick arity_comes_from_the_type; + Alcotest.test_case "wrapper text" `Quick wrapper_text; +] diff --git a/test/test_main.ml b/test/test_main.ml index 80e76955..8c15e410 100644 --- a/test/test_main.ml +++ b/test/test_main.ml @@ -29,6 +29,7 @@ let () = ("Qualified paths (#228, ADR-014)", Test_qualified_paths.tests); ("Generic enum kinds", Test_generic_enum_kinds.tests); ("Block-scoped let in the type checker", Test_block_scope.tests); + ("Intrinsics as values on Bun-ESM", Test_intrinsic_values.tests); ("Module search path ($AFFINESCRIPT_PATH)", Test_module_search_path.tests); ("Module root, decl match, flattening, interp binops, Bun-ESM return-in-arm", Test_module_root_flatten.tests); ("Record update + imported types", Test_records_and_imports.tests); diff --git a/tests/codegen-bun/intrinsic_values.affine b/tests/codegen-bun/intrinsic_values.affine new file mode 100644 index 00000000..eb505679 --- /dev/null +++ b/tests/codegen-bun/intrinsic_values.affine @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: MPL-2.0 +// Intrinsics used as values (owner ruling 2026-12-01): each is wrapped in an +// arrow of its type's arity instead of being emitted as a bare name, which +// failed with a ReferenceError when called. +fn apply1(f: String -> Int, s: String) -> Int { + f(s) +} + +fn apply_s(f: String -> String, s: String) -> String { + f(s) +} + +pub fn length_via_value(s: String) -> Int { + apply1(len, s) +} + +pub fn upper_via_value(s: String) -> String { + apply_s(to_uppercase, s) +} + +pub fn trim_via_let(s: String) -> String { + let t = trim; + t(s) +} + +pub fn sub_via_let(s: String) -> String { + let f = string_sub; + f(s, 1, 2) +} + +pub fn find_via_let(s: String) -> Int { + let f = string_find; + f(s, "c") +} + +pub fn show_int_via_let(n: Int) -> String { + let f = int_to_string; + f(n) +} diff --git a/tests/codegen-bun/intrinsic_values.harness.mjs b/tests/codegen-bun/intrinsic_values.harness.mjs new file mode 100644 index 00000000..01e73e41 --- /dev/null +++ b/tests/codegen-bun/intrinsic_values.harness.mjs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MPL-2.0 +import * as subject from "./intrinsic_values.bun.js"; + +const expect = (label, got, want) => { + if (got !== want) throw new Error(`${label}: got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`); +}; +expect("len passed as a value", subject.length_via_value("abcd"), 4); +expect("to_uppercase passed as a value", subject.upper_via_value("ab"), "AB"); +expect("trim bound with let", subject.trim_via_let(" x "), "x"); +expect("string_sub bound with let", subject.sub_via_let("abcd"), "bc"); +expect("string_find bound with let", subject.find_via_let("abcd"), 2); +expect("int_to_string bound with let", subject.show_int_via_let(42), "42"); +console.log("intrinsic_values: ok"); diff --git a/tools/soundness-anchors.sha256 b/tools/soundness-anchors.sha256 index 2d788c56..8d9a6543 100644 --- a/tools/soundness-anchors.sha256 +++ b/tools/soundness-anchors.sha256 @@ -9,7 +9,6 @@ 20e73d88738c8fd075f81a36803554f92fa4ee53f71e33fa6759eae07c6e70f4 suite:test/test_intrinsic_shadow.ml 2bbd1b989fd0097530eede3e5230258e0e1092271a23ff7dff20cca65c0e612e suite:test/test_wasm_call_resolution.ml 2dfe36a21983a7dfb7ffa1157f7ddec9865a531a92682976b8fd677e4825e78d test:test_801_impl_methods_refused -3b74c20f201d0d53c2fbab5582a681d3dfc3cf978a0aea676ecc6400087452d9 suite:test/test_intrinsic_shadow.ml 45eb0f3aa5f643afbd003248998dd5a046688418647b491e0f2d4bb55fcbd0f2 test:test_wasm_heap_exhaustion_traps 546939eaa3c64c82edd23da0a3ba7f74bcf7378cfe1e426132dd1a9f8fd46050 test:test_801_transitive_public_and_const 5b84a4f71aa65f9aa9383e31c0cb624291c4f9d0de7cca4a0ea6a76fe85aea35 fixture:test/e2e/fixtures/handle_resume_nontail.affine