Skip to content

Commit 2e42667

Browse files
committed
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J4QvDiosfvobXq67wbduuK
1 parent 4a55253 commit 2e42667

7 files changed

Lines changed: 177 additions & 10 deletions

File tree

‎docs/SOUNDNESS.adoc‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
// Freshness stamp — a real main-ancestor commit (survives squash-merge); advance
55
// it (and --reseal) in any change that touches a soundness path. See "Keeping
66
// this honest" and tools/check-soundness-ledger.sh (property 4).
7-
:ground-truth-sha: 84eca60
7+
:ground-truth-sha: 4a55253
88
:ground-truth-date: 2026-12-01
99
:stamp-verified-by: tools/check-soundness-ledger.sh
1010
:toc: macro
@@ -311,6 +311,26 @@ write into the literal region. Layout invariant:
311311
`test_wasm_heap_literals_intact_after_alloc` — run under Bun's WASI;
312312
`test_wasm_heap_exhaustion_traps`); `lib/codegen.ml`
313313
`memory_layout_of_datas` / `check_memory_layout`
314+
315+
| #833
316+
| The tree-walking interpreter — the oracle the compiled backends are compared
317+
against — runs the programs the checker accepts and agrees with Bun-ESM on
318+
them. It used to refuse a function that calls itself, one that calls a later
319+
declaration, any `let mut` / `const mut` assignment, and any use of an
320+
imported `Some` / `None` / `Ok` / `Err` (all loud). One shape was *silent*: an
321+
early `return` evaluated its operand and carried on, so
322+
`if c { return 1; } 2` yielded `2`. (The assignment arm also ignored a
323+
compound operator — `a += 5` would have stored `5` — which a
324+
`let mut` program could not reach, because the assignment failed first.) `affinescript eval` also type-checked
325+
with its own fold of `Typecheck.check_decl`, without the signature
326+
pre-registration of `Typecheck.check_program`, so it rejected forward and
327+
mutual references that `check` and `compile` accept; it now calls
328+
`check_program`. Not changed: `eval` still does not run the borrow checker
329+
(`check` and `compile` do), so it accepts programs they reject.
330+
| `fixed`
331+
| `test/test_interp_eval.ml` (18 cases: each program passes the full frontend,
332+
then its interpreter output is compared with the expected lines and with the
333+
Bun-ESM output of the same program; all 18 fail on `4248912`).
314334
|===
315335

316336
== Still open — read before claiming "sound"

‎lib/codegen_deno.ml‎

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1849,6 +1849,35 @@ let rec lowers_to_statements = function
18491849
| ExprMatch _ | ExprIf _ | ExprBlock _ -> true
18501850
| _ -> false
18511851

1852+
(** Arity of each builtin, read from its type in the type checker's
1853+
builtin table ([Typecheck.register_builtins]): one source of truth, so
1854+
no arity list is kept here by hand. A builtin used as a value is wrapped
1855+
in an arrow of this many parameters (owner ruling 2026-12-01:
1856+
first-class intrinsics on Bun). *)
1857+
let builtin_arity : (string, int) Hashtbl.t Lazy.t = lazy (
1858+
let tctx = Typecheck.create_context (Symbol.create ()) in
1859+
Typecheck.register_builtins tctx;
1860+
let arities = Hashtbl.create 128 in
1861+
let rec arrows = function
1862+
| Types.TArrow (_, _, r, _) -> 1 + arrows r
1863+
| _ -> 0
1864+
in
1865+
Hashtbl.iter (fun name (sc : Types.scheme) ->
1866+
Hashtbl.replace arities name (arrows sc.sc_body))
1867+
tctx.Typecheck.name_types;
1868+
arities)
1869+
1870+
(* A builtin lowering wrapped as a JS arrow of [arity] parameters, or
1871+
[None] when its lowering awaits: an async wrapper would also need every
1872+
call through the value awaited, which the value's callers do not do. *)
1873+
let wrap_builtin_value (lower : string list -> string) (arity : int) : string option =
1874+
let ps = List.init arity (Printf.sprintf "__a%d") in
1875+
let body = lower ps in
1876+
if (try ignore (Str.search_forward (Str.regexp "\\bawait\\b") body 0); true
1877+
with Not_found -> false)
1878+
then None
1879+
else Some (Printf.sprintf "((%s) => %s)" (String.concat ", " ps) body)
1880+
18521881
(** Render an expression as JavaScript using the names and host in [ctx].
18531882
Lambdas are synchronous arrows; known qualified constructors refer to
18541883
their emitted bindings. Nested statements can update integer tracking.
@@ -1865,14 +1894,27 @@ let rec gen_expr ctx (expr : expr) : string =
18651894
&& not (Hashtbl.mem ctx.locals id.name) ->
18661895
(* #818: an extern used as a value has no JS binding of its own name;
18671896
wrap its builtin lowering in an arrow of the declared arity. *)
1868-
let ps = List.init (Hashtbl.find ctx.externs id.name) (Printf.sprintf "__a%d") in
1869-
let body = (Hashtbl.find (builtins_for ctx) id.name) ps in
1870-
(* snip: an await-based lowering keeps the bare name (as before #818);
1871-
an async wrapper also needs awaited calls through the value. *)
1872-
if (try ignore (Str.search_forward (Str.regexp "\\bawait\\b") body 0); true
1873-
with Not_found -> false)
1874-
then resolve_var ctx id.name
1875-
else Printf.sprintf "((%s) => %s)" (String.concat ", " ps) body
1897+
(* An await-based lowering keeps the bare name (as before #818): an
1898+
async wrapper also needs awaited calls through the value. *)
1899+
(match wrap_builtin_value (Hashtbl.find (builtins_for ctx) id.name)
1900+
(Hashtbl.find ctx.externs id.name) with
1901+
| Some js -> js
1902+
| None -> resolve_var ctx id.name)
1903+
| ExprVar id
1904+
when Hashtbl.mem (builtins_for ctx) id.name
1905+
&& not (Hashtbl.mem ctx.local_fns id.name)
1906+
&& not (Hashtbl.mem ctx.locals id.name) ->
1907+
(* A non-extern intrinsic (`len`, `string_sub`, `char_to_string`, ...)
1908+
used as a value. It has no JS binding of its own name, so it used
1909+
to be emitted bare and failed with a ReferenceError when called.
1910+
Wrap its lowering like an extern's (#818), at the arity its type
1911+
gives. *)
1912+
(match Hashtbl.find_opt (Lazy.force builtin_arity) id.name with
1913+
| Some k when k > 0 ->
1914+
(match wrap_builtin_value (Hashtbl.find (builtins_for ctx) id.name) k with
1915+
| Some js -> js
1916+
| None -> resolve_var ctx id.name)
1917+
| _ -> resolve_var ctx id.name)
18761918
| ExprVar name -> resolve_var ctx name.name
18771919
| ExprApp (func, args) ->
18781920
(match func with

‎test/test_intrinsic_values.ml‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
(* SPDX-License-Identifier: MPL-2.0 *)
2+
(* Copyright (c) 2026 Jonathan D.A. Jewell <jonathan.jewell@open.ac.uk> *)
3+
(** Intrinsics as values on Bun-ESM (owner ruling 2026-12-01: first-class
4+
wrappers for every intrinsic).
5+
6+
An intrinsic such as [len] used as a value, not called, was emitted as a
7+
bare name with no JS binding, so calling it failed with a ReferenceError.
8+
Declared externs were already wrapped (#818); non-extern intrinsics now
9+
are too, at the arity their type gives in the type checker's builtin
10+
table ([Codegen_deno.builtin_arity]).
11+
12+
This suite pins coverage: every Bun builtin the type checker types gets
13+
a wrapper, so a builtin added later cannot silently fall back to a bare
14+
name. Behaviour is pinned by tests/codegen-bun/intrinsic_values. *)
15+
16+
open Affinescript
17+
18+
let every_typed_bun_builtin_is_wrapped () =
19+
let arities = Lazy.force Codegen_deno.builtin_arity in
20+
let unwrapped = ref [] and wrapped = ref 0 in
21+
Hashtbl.iter (fun name lower ->
22+
match Hashtbl.find_opt arities name with
23+
| Some k when k > 0 ->
24+
(match Codegen_deno.wrap_builtin_value lower k with
25+
| Some js ->
26+
incr wrapped;
27+
if not (String.length js > 2 && String.sub js 0 2 = "((") then
28+
unwrapped := (name ^ " (malformed: " ^ js ^ ")") :: !unwrapped
29+
| None -> unwrapped := (name ^ " (awaits)") :: !unwrapped)
30+
| _ -> ())
31+
Codegen_deno.bun_builtins;
32+
if !unwrapped <> [] then
33+
Alcotest.failf "typed Bun builtins with no value wrapper: %s"
34+
(String.concat ", " (List.sort compare !unwrapped));
35+
Alcotest.(check bool) "at least the string/number intrinsics are wrapped" true (!wrapped >= 30)
36+
37+
let arity_comes_from_the_type () =
38+
let arities = Lazy.force Codegen_deno.builtin_arity in
39+
List.iter (fun (name, k) ->
40+
Alcotest.(check (option int)) name (Some k) (Hashtbl.find_opt arities name))
41+
[ ("len", 1); ("string_sub", 3); ("string_find", 2); ("int_to_string", 1) ]
42+
43+
let wrapper_text () =
44+
let lower = Hashtbl.find Codegen_deno.bun_builtins "string_sub" in
45+
Alcotest.(check (option string)) "string_sub wrapper"
46+
(Some "((__a0, __a1, __a2) => __as_strSub(__a0, __a1, __a2))")
47+
(Codegen_deno.wrap_builtin_value lower 3)
48+
49+
let tests = [
50+
Alcotest.test_case "every typed Bun builtin is wrapped as a value" `Quick every_typed_bun_builtin_is_wrapped;
51+
Alcotest.test_case "arity comes from the builtin's type" `Quick arity_comes_from_the_type;
52+
Alcotest.test_case "wrapper text" `Quick wrapper_text;
53+
]

‎test/test_main.ml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ let () =
2929
("Qualified paths (#228, ADR-014)", Test_qualified_paths.tests);
3030
("Generic enum kinds", Test_generic_enum_kinds.tests);
3131
("Block-scoped let in the type checker", Test_block_scope.tests);
32+
("Intrinsics as values on Bun-ESM", Test_intrinsic_values.tests);
3233
("Module search path ($AFFINESCRIPT_PATH)", Test_module_search_path.tests);
3334
("Module root, decl match, flattening, interp binops, Bun-ESM return-in-arm", Test_module_root_flatten.tests);
3435
("Record update + imported types", Test_records_and_imports.tests);
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// SPDX-License-Identifier: MPL-2.0
2+
// Intrinsics used as values (owner ruling 2026-12-01): each is wrapped in an
3+
// arrow of its type's arity instead of being emitted as a bare name, which
4+
// failed with a ReferenceError when called.
5+
fn apply1(f: String -> Int, s: String) -> Int {
6+
f(s)
7+
}
8+
9+
fn apply_s(f: String -> String, s: String) -> String {
10+
f(s)
11+
}
12+
13+
pub fn length_via_value(s: String) -> Int {
14+
apply1(len, s)
15+
}
16+
17+
pub fn upper_via_value(s: String) -> String {
18+
apply_s(to_uppercase, s)
19+
}
20+
21+
pub fn trim_via_let(s: String) -> String {
22+
let t = trim;
23+
t(s)
24+
}
25+
26+
pub fn sub_via_let(s: String) -> String {
27+
let f = string_sub;
28+
f(s, 1, 2)
29+
}
30+
31+
pub fn find_via_let(s: String) -> Int {
32+
let f = string_find;
33+
f(s, "c")
34+
}
35+
36+
pub fn show_int_via_let(n: Int) -> String {
37+
let f = int_to_string;
38+
f(n)
39+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// SPDX-License-Identifier: MPL-2.0
2+
import * as subject from "./intrinsic_values.bun.js";
3+
4+
const expect = (label, got, want) => {
5+
if (got !== want) throw new Error(`${label}: got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`);
6+
};
7+
expect("len passed as a value", subject.length_via_value("abcd"), 4);
8+
expect("to_uppercase passed as a value", subject.upper_via_value("ab"), "AB");
9+
expect("trim bound with let", subject.trim_via_let(" x "), "x");
10+
expect("string_sub bound with let", subject.sub_via_let("abcd"), "bc");
11+
expect("string_find bound with let", subject.find_via_let("abcd"), 2);
12+
expect("int_to_string bound with let", subject.show_int_via_let(42), "42");
13+
console.log("intrinsic_values: ok");

‎tools/soundness-anchors.sha256‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
20e73d88738c8fd075f81a36803554f92fa4ee53f71e33fa6759eae07c6e70f4 suite:test/test_intrinsic_shadow.ml
1010
2bbd1b989fd0097530eede3e5230258e0e1092271a23ff7dff20cca65c0e612e suite:test/test_wasm_call_resolution.ml
1111
2dfe36a21983a7dfb7ffa1157f7ddec9865a531a92682976b8fd677e4825e78d test:test_801_impl_methods_refused
12-
3b74c20f201d0d53c2fbab5582a681d3dfc3cf978a0aea676ecc6400087452d9 suite:test/test_intrinsic_shadow.ml
1312
45eb0f3aa5f643afbd003248998dd5a046688418647b491e0f2d4bb55fcbd0f2 test:test_wasm_heap_exhaustion_traps
1413
546939eaa3c64c82edd23da0a3ba7f74bcf7378cfe1e426132dd1a9f8fd46050 test:test_801_transitive_public_and_const
1514
5b84a4f71aa65f9aa9383e31c0cb624291c4f9d0de7cca4a0ea6a76fe85aea35 fixture:test/e2e/fixtures/handle_resume_nontail.affine

0 commit comments

Comments
 (0)