Skip to content

Commit 70180a1

Browse files
fix(js-backend): refuse an unprovided builtin at compile time, by name (#832) (#842)
Closes #832 ## What was wrong The JS-text backend (`lib/js_codegen.ml`, output `*.js`) emits a variable as its bare name. Its runtime prelude defines only `print`, `println` and `read_line`. A program that named any other builtin compiled, and the script then stopped when the call was reached: ``` $ affinescript compile idx.affine -o idx.js # succeeded $ node idx.js ReferenceError: int_to_string is not defined ``` ## What changes `Js_codegen.generate` runs a closed-world check before it emits any declaration. A free name is refused when all three hold: - the resolver seeds it as a builtin (`Resolve.seed_builtins`); - the program does not bind it at top level, and no enclosing parameter, `let`, match arm, lambda or `for` binds it; - the emitted runtime does not bind it. The refusal names every such builtin: ``` $ affinescript compile idx.affine -o idx.js JS codegen error: builtins `int_to_string`, `len` are not provided by the JS-text backend: the emitted script would stop with a ReferenceError when the reference is reached (#832). The Bun-ESM backend (`--bun-esm`, output `.bun.js`) and the interpreter (`eval`) provide more of the builtins ``` ## Refuse, not lower: why I chose refusal for every unprovided builtin and lowered none. - The string index builtins (`len`, `string_get`, `string_sub`, `string_char_code_at`) have no agreed meaning on a JS string until #831 is decided. Lowering them here would add another meaning to the ones #829 measured. - The unambiguous ones (`int_to_string`, `to_uppercase`, `trim`, the math functions) could be lowered later by sharing the Bun-ESM table (option 2 in the issue). That is a feature, and it is not needed to close the bug. `Codegen_deno` depends on `Js_codegen`, so sharing the table needs the table moved to its own module first. ## Design notes - **One source for "is a builtin".** The set is read from `Resolve.seed_builtins`. A builtin added to the resolver is refused here until this backend provides it. A test walks the whole set and checks each name is either bound by the emitted script or refused. - **One source for "the runtime provides it".** The check reads the `top_names` table that `generate` already fills for the prelude. An alias registered there is accepted without a second list. This is what keeps #829 working (below). - **Scoping** comes from `Ast.free_names`, the walker import flattening already uses, so shadowing follows the same rules as the rest of the compiler. ## Interaction with #829 (open, not merged) This branch is based on `main` and does not need #829's API. I merged `origin/claude/unicode-octets` (`161eaaf`) into this branch locally to check the two together: - The merge is clean, with no conflicts. - The main suite passes: 715 tests (680 on `main`, 27 from #829, 8 new here). - On the merged build, a program using `utf8_byte_length`, `code_points` and `string_from_code_points` compiles to `.js` and prints the right values under `node`; `len` and `int_to_string` in the same build are refused. So either merge order works, with no follow-up edit. In that merged worktree the separate `res-to-affine` walker suite failed 32 tests with "tree-sitter grammar not built". That is the untracked vendored grammar being absent from a fresh worktree; the same suite passes in the main checkout. ## Behaviour change to be aware of A program that names an unprovided builtin only on a path it never executes used to compile and run. It is now refused. That is the intended closed-world behaviour, but it is a change. ## Not fixed here (found while testing) - `impl` methods and effect operations are erased by this backend (`// impl block (erased)`), so a call to one is still a run-time `ReferenceError`. They are not resolver builtins, so this check does not cover them. The issue's option 1 in full (any unbound free identifier) would. - `read_line` is typed `Result[String, String]`, but this backend's prelude returns a bare string. ## Test evidence Run on this branch at `main` `4248912`. ``` $ dune runtest --force Test Successful in 0.608s. 680 tests run. # main suite, 8 new Test Successful in 2.113s. 32 tests run. # res-to-affine walker exit=0 $ just check OK: capability anchors intact — Test-anchors section present + every named test exists. exit=0 $ tools/run_codegen_wasm_tests.sh All codegen WASM tests passed (48 JS harnesses). $ tools/run_codegen_deno_tests.sh All codegen Bun-ESM (legacy codegen-deno corpus) tests passed (42 harnesses). $ tools/run_codegen_bun_tests.sh All native Bun-ESM tests passed (8 harnesses). ``` New tests, `test/test_js_builtin_refusal.ml`: ``` [OK] JS-text backend refuses unprovided builtins (#832) 0 issue #832 example is refused by name. [OK] JS-text backend refuses unprovided builtins (#832) 1 each string builtin is refused by its own name. [OK] JS-text backend refuses unprovided builtins (#832) 2 every resolver builtin is bound or refused. [OK] JS-text backend refuses unprovided builtins (#832) 3 prelude builtins still compile. [OK] JS-text backend refuses unprovided builtins (#832) 4 a program binding shadows the builtin. [OK] JS-text backend refuses unprovided builtins (#832) 5 shadowing is scoped. [OK] JS-text backend refuses unprovided builtins (#832) 6 nested references are refused. [OK] JS-text backend refuses unprovided builtins (#832) 7 program without builtins is unaffected. ``` Run by hand: a program that shadows `len`, `int_to_string` and `trim` with its own bindings compiles to `.js` and prints `shadow ok: 12` under both `node` and `bun`. `lint` in `just check` printed "ocamlformat not installed; skipping format check" in this container, so formatting was not checked here. ## Soundness ledger Only `lib/js_codegen.ml` and tests change. No soundness path is touched, so `docs/SOUNDNESS.adoc` is not advanced. --- _Generated by [Claude Code](https://claude.ai/code)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 84eca60 commit 70180a1

3 files changed

Lines changed: 256 additions & 0 deletions

File tree

‎lib/js_codegen.ml‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -611,6 +611,84 @@ let preamble_ctor_shared (td : type_decl) (vd : variant_decl) : bool =
611611
n td.td_name.name arity n want)
612612
| _ -> false
613613

614+
(* ============================================================================
615+
Closed-world check for builtins (#832)
616+
617+
[gen_expr] emits a variable as its bare (mangled) name. The front end
618+
accepts every name [Resolve.seed_builtins] seeds, but this backend's
619+
runtime prelude defines only a few of them. A program that named any
620+
other builtin (`len`, `string_sub`, `int_to_string`, ...) used to compile
621+
and then stop with a `ReferenceError` when the call was reached. The
622+
reference is now refused at compile time, by name.
623+
624+
The set of builtins is taken from the resolver itself, so a builtin added
625+
there is refused here until this backend provides it: the two lists cannot
626+
drift apart silently.
627+
============================================================================ *)
628+
629+
(** Every name the resolver seeds as a builtin. *)
630+
let resolver_builtins : Symbol.t Lazy.t =
631+
lazy (let s = Symbol.create () in Resolve.seed_builtins s; s)
632+
633+
let is_resolver_builtin (name : string) : bool =
634+
Symbol.lookup (Lazy.force resolver_builtins) name <> None
635+
636+
(** Free names of every body this backend emits: function bodies (minus
637+
their parameters) and constant initialisers. `impl` blocks are erased by
638+
[gen_top_level], so their bodies are not emitted and are not checked.
639+
Uses [Ast.free_names], so a parameter, `let`, match-arm, lambda or `for`
640+
binder of the same name hides the builtin, as it does in the emitted JS. *)
641+
let emitted_free_names (program : program) : string list =
642+
List.concat_map (function
643+
| TopFn fd ->
644+
let params =
645+
List.map (fun (p : param) -> p.p_name.name) fd.fd_params in
646+
let free = match fd.fd_body with
647+
| FnExpr e -> Ast.free_names e
648+
| FnBlock b -> Ast.free_names_block b
649+
in
650+
List.filter (fun n -> not (List.mem n params)) free
651+
| TopConst { tc_value; _ } -> Ast.free_names tc_value
652+
| TopType _ | TopEffect _ | TopTrait _ | TopImpl _ -> [])
653+
program.prog_decls
654+
655+
(** Top-level value names the program itself binds in the emitted script. *)
656+
let program_top_names (program : program) : string list =
657+
List.concat_map (function
658+
| TopFn fd -> [ fd.fd_name.name ]
659+
| TopConst { tc_name; _ } -> [ tc_name.name ]
660+
| TopType { td_body = TyEnum variants; _ } ->
661+
List.map (fun (vd : variant_decl) -> vd.vd_name.name) variants
662+
| TopType _ | TopEffect _ | TopTrait _ | TopImpl _ -> [])
663+
program.prog_decls
664+
665+
(** Builtins the program refers to that the emitted script would not define.
666+
[runtime_provides n] says whether the runtime (the prelude, plus any
667+
alias [generate] emits) binds [n] at top level. Sorted, no duplicates. *)
668+
let unprovided_builtins ~(runtime_provides : string -> bool)
669+
(program : program) : string list =
670+
let own = program_top_names program in
671+
emitted_free_names program
672+
|> List.filter (fun n ->
673+
is_resolver_builtin n
674+
&& not (List.mem n own)
675+
&& not (runtime_provides n))
676+
|> List.sort_uniq compare
677+
678+
let refuse_unprovided_builtins ~runtime_provides (program : program) : unit =
679+
match unprovided_builtins ~runtime_provides program with
680+
| [] -> ()
681+
| names ->
682+
let quoted = String.concat ", " (List.map (fun n -> "`" ^ n ^ "`") names) in
683+
failwith
684+
(Printf.sprintf
685+
"%s %s not provided by the JS-text backend: the emitted script \
686+
would stop with a ReferenceError when the reference is reached \
687+
(#832). The Bun-ESM backend (`--bun-esm`, output `.bun.js`) and \
688+
the interpreter (`eval`) provide more of the builtins"
689+
(if List.length names = 1 then "builtin" else "builtins")
690+
(quoted ^ (if List.length names = 1 then " is" else " are")))
691+
614692
(* ============================================================================
615693
Main Code Generation Entry Point
616694
============================================================================ *)
@@ -661,6 +739,10 @@ let generate (program : program) (symbols : Symbol.t) : string =
661739
refusing to emit a script in which one replaces the other (#801)"
662740
name)
663741
in
742+
(* #832: every runtime name is in [top_names] by now and no program name
743+
is yet, so membership means "the runtime binds it". *)
744+
refuse_unprovided_builtins
745+
~runtime_provides:(fun n -> Hashtbl.mem top_names (mangle n)) program;
664746
List.iter (fun top ->
665747
match top with
666748
| TopFn fd ->

‎test/test_js_builtin_refusal.ml‎

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
(* SPDX-License-Identifier: MPL-2.0 *)
2+
(* SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell *)
3+
4+
(** #832: the JS-text backend ([Js_codegen]) refuses, at compile time and by
5+
name, a builtin its runtime prelude does not define.
6+
7+
Before the fix such a program compiled and the emitted script stopped
8+
with [ReferenceError: int_to_string is not defined] when the call was
9+
reached. These tests drive the real front end (parse, resolve,
10+
typecheck) into [Js_codegen.codegen_js] and check the refusal, the names
11+
it reports, and that a program binding of the same name is not refused. *)
12+
13+
open Affinescript
14+
15+
let compile_js = Test_int_div_js.compile_js
16+
let contains = Test_int_div_js.contains
17+
18+
let refused ~names src =
19+
match compile_js src with
20+
| Ok _ ->
21+
Alcotest.failf
22+
"expected a compile-time refusal naming %s, but the JS backend emitted \
23+
a script (#832 has regressed)"
24+
(String.concat ", " names)
25+
| Error msg ->
26+
Alcotest.(check bool) ("is a JS codegen refusal: " ^ msg) true
27+
(contains ~needle:"JS codegen error" msg
28+
&& contains ~needle:"not provided by the JS-text backend" msg
29+
&& contains ~needle:"#832" msg);
30+
List.iter (fun n ->
31+
Alcotest.(check bool) ("refusal names `" ^ n ^ "`: " ^ msg) true
32+
(contains ~needle:("`" ^ n ^ "`") msg))
33+
names
34+
35+
let accepted src : string =
36+
match compile_js src with
37+
| Ok js -> js
38+
| Error msg -> Alcotest.failf "expected the JS backend to compile, got: %s" msg
39+
40+
(* 1. The program from the issue. *)
41+
let issue_example () =
42+
refused ~names:[ "int_to_string"; "len" ]
43+
"fn main() -> () { println(int_to_string(len(\"abc\"))); }\n"
44+
45+
(* 2. Each string builtin named in #831/#832 is refused by its own name, and
46+
the refusal names nothing the program did not use. *)
47+
let string_builtins =
48+
[ ("len", "fn f(s: String) -> Int { len(s) }");
49+
("string_length", "fn f(s: String) -> Int { string_length(s) }");
50+
("string_get", "fn f(s: String) -> Char { string_get(s, 0) }");
51+
("string_sub", "fn f(s: String) -> String { string_sub(s, 0, 1) }");
52+
("string_find", "fn f(s: String) -> Int { string_find(s, \"a\") }");
53+
("string_char_code_at", "fn f(s: String) -> Int { string_char_code_at(s, 0) }");
54+
("char_to_int", "fn f(c: Char) -> Int { char_to_int(c) }");
55+
("int_to_string", "fn f(n: Int) -> String { int_to_string(n) }");
56+
("float_to_string", "fn f(x: Float) -> String { float_to_string(x) }");
57+
("to_uppercase", "fn f(s: String) -> String { to_uppercase(s) }");
58+
("trim", "fn f(s: String) -> String { trim(s) }") ]
59+
60+
let each_string_builtin () =
61+
List.iter (fun (name, src) ->
62+
refused ~names:[ name ] (src ^ "\n");
63+
(match compile_js (src ^ "\n") with
64+
| Error msg ->
65+
List.iter (fun (other, _) ->
66+
if other <> name then
67+
Alcotest.(check bool)
68+
(Printf.sprintf "refusal of `%s` does not name `%s`" name other)
69+
false (contains ~needle:("`" ^ other ^ "`") msg))
70+
string_builtins
71+
| Ok _ -> ()))
72+
string_builtins
73+
74+
(* 3. Closed world: every name the resolver seeds as a builtin is either
75+
bound by the emitted runtime or refused. A builtin added to the resolver
76+
later is covered without touching this test. Parse only: the check must
77+
not depend on the type checker having run. *)
78+
let prelude_binds name =
79+
List.exists (fun line ->
80+
let starts p =
81+
String.length line >= String.length p
82+
&& String.sub line 0 (String.length p) = p in
83+
starts ("const " ^ name ^ " ") || starts ("let " ^ name ^ " "))
84+
(String.split_on_char '\n' Js_codegen.prelude)
85+
86+
let every_resolver_builtin_bound_or_refused () =
87+
let syms = Symbol.create () in
88+
Resolve.seed_builtins syms;
89+
let names =
90+
Hashtbl.fold (fun _ (s : Symbol.symbol) acc -> s.sym_name :: acc)
91+
syms.Symbol.all_symbols []
92+
|> List.sort_uniq compare
93+
in
94+
Alcotest.(check bool) "the resolver seeds builtins" true (List.length names > 40);
95+
let refused_n = ref 0 and bound_n = ref 0 in
96+
List.iter (fun name ->
97+
let prog =
98+
Parse_driver.parse_string ~file:"<closed-world>"
99+
(Printf.sprintf "fn probe() -> Int { let f = %s; 0 }\n" name)
100+
in
101+
match Js_codegen.codegen_js prog (Symbol.create ()) with
102+
| Error msg ->
103+
incr refused_n;
104+
Alcotest.(check bool) ("refusal names `" ^ name ^ "`") true
105+
(contains ~needle:("`" ^ name ^ "`") msg);
106+
Alcotest.(check bool)
107+
("`" ^ name ^ "` is refused, so the prelude must not bind it") false
108+
(prelude_binds name)
109+
| Ok js ->
110+
incr bound_n;
111+
(* Accepted: the emitted script must bind the name at top level. *)
112+
Alcotest.(check bool)
113+
("`" ^ name ^ "` is accepted, so the script must bind it") true
114+
(contains ~needle:("\nconst " ^ name ^ " ") js
115+
|| contains ~needle:("\nlet " ^ name ^ " ") js))
116+
names;
117+
Alcotest.(check bool) "some builtins are refused" true (!refused_n > 0);
118+
Alcotest.(check bool) "print/println/read_line are bound" true (!bound_n >= 3)
119+
120+
(* 4. The prelude's own builtins still compile. *)
121+
let provided_builtins_compile () =
122+
let js = accepted "fn main() -> () { print(\"a\"); println(\"b\"); let r = read_line(); }\n" in
123+
Alcotest.(check bool) "main is emitted" true (contains ~needle:"function main()" js)
124+
125+
(* 5. A program binding of the same name is not the builtin: no refusal. *)
126+
let program_bindings_shadow () =
127+
ignore (accepted
128+
"fn len(s: String) -> Int { 7 }\n\
129+
fn main() -> Int { len(\"abc\") }\n");
130+
ignore (accepted "fn f(len: Int) -> Int { len + 1 }\n");
131+
ignore (accepted "fn f() -> Int { let trim = 3; trim + 1 }\n");
132+
ignore (accepted "fn f(xs: [Int]) -> Int { let mut t = 0; for len in xs { t = t + len; } t }\n");
133+
ignore (accepted "fn f() -> Int { let g = fn(len: Int) => len + 1; g(1) }\n");
134+
ignore (accepted
135+
"enum Box { Full(Int), Empty }\n\
136+
fn f(o: Box) -> Int { match o { Full(len) => len, Empty => 0 } }\n");
137+
ignore (accepted "const trim: Int = 4;\nfn f() -> Int { trim }\n")
138+
139+
(* 6. A binder hides the builtin only in its own scope. *)
140+
let shadow_is_scoped () =
141+
refused ~names:[ "len" ]
142+
"fn g(len: Int) -> Int { len }\n\
143+
fn f(s: String) -> Int { len(s) }\n";
144+
refused ~names:[ "len" ]
145+
"fn f(s: String) -> Int { let n = len(s); let len = 3; n + len }\n"
146+
147+
(* 7. The reference is found wherever it sits: lambda body, match arm,
148+
constant initialiser, loop body. *)
149+
let nested_references () =
150+
refused ~names:[ "int_to_string" ]
151+
"fn f() -> String { let g = fn(n: Int) => int_to_string(n); g(1) }\n";
152+
refused ~names:[ "len" ]
153+
"enum Box { Full(String), Empty }\n\
154+
fn f(o: Box) -> Int { match o { Full(s) => len(s), Empty => 0 } }\n";
155+
refused ~names:[ "len" ] "const N: Int = len(\"abc\");\n";
156+
refused ~names:[ "len" ]
157+
"fn f(s: String) -> Int { let mut i = 0; while i < len(s) { i = i + 1; } i }\n"
158+
159+
(* 8. A program with no builtin reference is untouched. *)
160+
let no_builtins_unaffected () =
161+
let js = accepted "fn add(a: Int, b: Int) -> Int { a + b }\n" in
162+
Alcotest.(check bool) "add is emitted" true (contains ~needle:"function add(a, b)" js)
163+
164+
let tests = [
165+
Alcotest.test_case "issue #832 example is refused by name" `Quick issue_example;
166+
Alcotest.test_case "each string builtin is refused by its own name" `Quick each_string_builtin;
167+
Alcotest.test_case "every resolver builtin is bound or refused" `Quick every_resolver_builtin_bound_or_refused;
168+
Alcotest.test_case "prelude builtins still compile" `Quick provided_builtins_compile;
169+
Alcotest.test_case "a program binding shadows the builtin" `Quick program_bindings_shadow;
170+
Alcotest.test_case "shadowing is scoped" `Quick shadow_is_scoped;
171+
Alcotest.test_case "nested references are refused" `Quick nested_references;
172+
Alcotest.test_case "program without builtins is unaffected" `Quick no_builtins_unaffected;
173+
]

‎test/test_main.ml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ let () =
3434
("Record update + imported types", Test_records_and_imports.tests);
3535
("Module mut (#548)", Test_module_mut.tests);
3636
("Int-div on JS-text backend (#478)", Test_int_div_js.tests);
37+
("JS-text backend refuses unprovided builtins (#832)", Test_js_builtin_refusal.tests);
3738
("Bun-ESM let rebinding (#827)", Test_let_rebind_bun.tests);
3839
("Deno builtins ↔ stdlib decls consistency", Test_deno_builtins_consistency.tests);
3940
("Bun integer block scope", Test_int_scope_bun.tests);

0 commit comments

Comments
 (0)