Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion docs/SOUNDNESS.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
58 changes: 50 additions & 8 deletions lib/codegen_deno.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
53 changes: 53 additions & 0 deletions test/test_intrinsic_values.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
(* SPDX-License-Identifier: MPL-2.0 *)
(* Copyright (c) 2026 Jonathan D.A. Jewell <jonathan.jewell@open.ac.uk> *)
(** 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;
]
1 change: 1 addition & 0 deletions test/test_main.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
39 changes: 39 additions & 0 deletions tests/codegen-bun/intrinsic_values.affine
Original file line number Diff line number Diff line change
@@ -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)
}
13 changes: 13 additions & 0 deletions tests/codegen-bun/intrinsic_values.harness.mjs
Original file line number Diff line number Diff line change
@@ -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");
1 change: 0 additions & 1 deletion tools/soundness-anchors.sha256
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading