Skip to content
Merged
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
82 changes: 82 additions & 0 deletions lib/js_codegen.ml
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,84 @@ let preamble_ctor_shared (td : type_decl) (vd : variant_decl) : bool =
n td.td_name.name arity n want)
| _ -> false

(* ============================================================================
Closed-world check for builtins (#832)
[gen_expr] emits a variable as its bare (mangled) name. The front end
accepts every name [Resolve.seed_builtins] seeds, but this backend's
runtime prelude defines only a few of them. A program that named any
other builtin (`len`, `string_sub`, `int_to_string`, ...) used to compile
and then stop with a `ReferenceError` when the call was reached. The
reference is now refused at compile time, by name.
The set of builtins is taken from the resolver itself, so a builtin added
there is refused here until this backend provides it: the two lists cannot
drift apart silently.
============================================================================ *)

(** Every name the resolver seeds as a builtin. *)
let resolver_builtins : Symbol.t Lazy.t =
lazy (let s = Symbol.create () in Resolve.seed_builtins s; s)

let is_resolver_builtin (name : string) : bool =
Symbol.lookup (Lazy.force resolver_builtins) name <> None

(** Free names of every body this backend emits: function bodies (minus
their parameters) and constant initialisers. `impl` blocks are erased by
[gen_top_level], so their bodies are not emitted and are not checked.
Uses [Ast.free_names], so a parameter, `let`, match-arm, lambda or `for`
binder of the same name hides the builtin, as it does in the emitted JS. *)
let emitted_free_names (program : program) : string list =
List.concat_map (function
| TopFn fd ->
let params =
List.map (fun (p : param) -> p.p_name.name) fd.fd_params in
let free = match fd.fd_body with
| FnExpr e -> Ast.free_names e
| FnBlock b -> Ast.free_names_block b
in
List.filter (fun n -> not (List.mem n params)) free
| TopConst { tc_value; _ } -> Ast.free_names tc_value
| TopType _ | TopEffect _ | TopTrait _ | TopImpl _ -> [])
program.prog_decls

(** Top-level value names the program itself binds in the emitted script. *)
let program_top_names (program : program) : string list =
List.concat_map (function
| TopFn fd -> [ fd.fd_name.name ]
| TopConst { tc_name; _ } -> [ tc_name.name ]
| TopType { td_body = TyEnum variants; _ } ->
List.map (fun (vd : variant_decl) -> vd.vd_name.name) variants
| TopType _ | TopEffect _ | TopTrait _ | TopImpl _ -> [])
program.prog_decls

(** Builtins the program refers to that the emitted script would not define.
[runtime_provides n] says whether the runtime (the prelude, plus any
alias [generate] emits) binds [n] at top level. Sorted, no duplicates. *)
let unprovided_builtins ~(runtime_provides : string -> bool)
(program : program) : string list =
let own = program_top_names program in
emitted_free_names program
|> List.filter (fun n ->
is_resolver_builtin n
&& not (List.mem n own)
&& not (runtime_provides n))
|> List.sort_uniq compare

let refuse_unprovided_builtins ~runtime_provides (program : program) : unit =
match unprovided_builtins ~runtime_provides program with
| [] -> ()
| names ->
let quoted = String.concat ", " (List.map (fun n -> "`" ^ n ^ "`") names) in
failwith
(Printf.sprintf
"%s %s 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"
(if List.length names = 1 then "builtin" else "builtins")
(quoted ^ (if List.length names = 1 then " is" else " are")))

(* ============================================================================
Main Code Generation Entry Point
============================================================================ *)
Expand Down Expand Up @@ -661,6 +739,10 @@ let generate (program : program) (symbols : Symbol.t) : string =
refusing to emit a script in which one replaces the other (#801)"
name)
in
(* #832: every runtime name is in [top_names] by now and no program name
is yet, so membership means "the runtime binds it". *)
refuse_unprovided_builtins
~runtime_provides:(fun n -> Hashtbl.mem top_names (mangle n)) program;
List.iter (fun top ->
match top with
| TopFn fd ->
Expand Down
173 changes: 173 additions & 0 deletions test/test_js_builtin_refusal.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
(* SPDX-License-Identifier: MPL-2.0 *)
(* SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell *)

(** #832: the JS-text backend ([Js_codegen]) refuses, at compile time and by
name, a builtin its runtime prelude does not define.
Before the fix such a program compiled and the emitted script stopped
with [ReferenceError: int_to_string is not defined] when the call was
reached. These tests drive the real front end (parse, resolve,
typecheck) into [Js_codegen.codegen_js] and check the refusal, the names
it reports, and that a program binding of the same name is not refused. *)

open Affinescript

let compile_js = Test_int_div_js.compile_js
let contains = Test_int_div_js.contains

let refused ~names src =
match compile_js src with
| Ok _ ->
Alcotest.failf
"expected a compile-time refusal naming %s, but the JS backend emitted \
a script (#832 has regressed)"
(String.concat ", " names)
| Error msg ->
Alcotest.(check bool) ("is a JS codegen refusal: " ^ msg) true
(contains ~needle:"JS codegen error" msg
&& contains ~needle:"not provided by the JS-text backend" msg
&& contains ~needle:"#832" msg);
List.iter (fun n ->
Alcotest.(check bool) ("refusal names `" ^ n ^ "`: " ^ msg) true
(contains ~needle:("`" ^ n ^ "`") msg))
names

let accepted src : string =
match compile_js src with
| Ok js -> js
| Error msg -> Alcotest.failf "expected the JS backend to compile, got: %s" msg

(* 1. The program from the issue. *)
let issue_example () =
refused ~names:[ "int_to_string"; "len" ]
"fn main() -> () { println(int_to_string(len(\"abc\"))); }\n"

(* 2. Each string builtin named in #831/#832 is refused by its own name, and
the refusal names nothing the program did not use. *)
let string_builtins =
[ ("len", "fn f(s: String) -> Int { len(s) }");
("string_length", "fn f(s: String) -> Int { string_length(s) }");
("string_get", "fn f(s: String) -> Char { string_get(s, 0) }");
("string_sub", "fn f(s: String) -> String { string_sub(s, 0, 1) }");
("string_find", "fn f(s: String) -> Int { string_find(s, \"a\") }");
("string_char_code_at", "fn f(s: String) -> Int { string_char_code_at(s, 0) }");
("char_to_int", "fn f(c: Char) -> Int { char_to_int(c) }");
("int_to_string", "fn f(n: Int) -> String { int_to_string(n) }");
("float_to_string", "fn f(x: Float) -> String { float_to_string(x) }");
("to_uppercase", "fn f(s: String) -> String { to_uppercase(s) }");
("trim", "fn f(s: String) -> String { trim(s) }") ]

let each_string_builtin () =
List.iter (fun (name, src) ->
refused ~names:[ name ] (src ^ "\n");
(match compile_js (src ^ "\n") with
| Error msg ->
List.iter (fun (other, _) ->
if other <> name then
Alcotest.(check bool)
(Printf.sprintf "refusal of `%s` does not name `%s`" name other)
false (contains ~needle:("`" ^ other ^ "`") msg))
string_builtins
| Ok _ -> ()))
string_builtins

(* 3. Closed world: every name the resolver seeds as a builtin is either
bound by the emitted runtime or refused. A builtin added to the resolver
later is covered without touching this test. Parse only: the check must
not depend on the type checker having run. *)
let prelude_binds name =
List.exists (fun line ->
let starts p =
String.length line >= String.length p
&& String.sub line 0 (String.length p) = p in
starts ("const " ^ name ^ " ") || starts ("let " ^ name ^ " "))
(String.split_on_char '\n' Js_codegen.prelude)

let every_resolver_builtin_bound_or_refused () =
let syms = Symbol.create () in
Resolve.seed_builtins syms;
let names =
Hashtbl.fold (fun _ (s : Symbol.symbol) acc -> s.sym_name :: acc)
syms.Symbol.all_symbols []
|> List.sort_uniq compare
in
Alcotest.(check bool) "the resolver seeds builtins" true (List.length names > 40);
let refused_n = ref 0 and bound_n = ref 0 in
List.iter (fun name ->
let prog =
Parse_driver.parse_string ~file:"<closed-world>"
(Printf.sprintf "fn probe() -> Int { let f = %s; 0 }\n" name)
in
match Js_codegen.codegen_js prog (Symbol.create ()) with
| Error msg ->
incr refused_n;
Alcotest.(check bool) ("refusal names `" ^ name ^ "`") true
(contains ~needle:("`" ^ name ^ "`") msg);
Alcotest.(check bool)
("`" ^ name ^ "` is refused, so the prelude must not bind it") false
(prelude_binds name)
| Ok js ->
incr bound_n;
(* Accepted: the emitted script must bind the name at top level. *)
Alcotest.(check bool)
("`" ^ name ^ "` is accepted, so the script must bind it") true
(contains ~needle:("\nconst " ^ name ^ " ") js
|| contains ~needle:("\nlet " ^ name ^ " ") js))
names;
Alcotest.(check bool) "some builtins are refused" true (!refused_n > 0);
Alcotest.(check bool) "print/println/read_line are bound" true (!bound_n >= 3)

(* 4. The prelude's own builtins still compile. *)
let provided_builtins_compile () =
let js = accepted "fn main() -> () { print(\"a\"); println(\"b\"); let r = read_line(); }\n" in
Alcotest.(check bool) "main is emitted" true (contains ~needle:"function main()" js)

(* 5. A program binding of the same name is not the builtin: no refusal. *)
let program_bindings_shadow () =
ignore (accepted
"fn len(s: String) -> Int { 7 }\n\
fn main() -> Int { len(\"abc\") }\n");
ignore (accepted "fn f(len: Int) -> Int { len + 1 }\n");
ignore (accepted "fn f() -> Int { let trim = 3; trim + 1 }\n");
ignore (accepted "fn f(xs: [Int]) -> Int { let mut t = 0; for len in xs { t = t + len; } t }\n");
ignore (accepted "fn f() -> Int { let g = fn(len: Int) => len + 1; g(1) }\n");
ignore (accepted
"enum Box { Full(Int), Empty }\n\
fn f(o: Box) -> Int { match o { Full(len) => len, Empty => 0 } }\n");
ignore (accepted "const trim: Int = 4;\nfn f() -> Int { trim }\n")

(* 6. A binder hides the builtin only in its own scope. *)
let shadow_is_scoped () =
refused ~names:[ "len" ]
"fn g(len: Int) -> Int { len }\n\
fn f(s: String) -> Int { len(s) }\n";
refused ~names:[ "len" ]
"fn f(s: String) -> Int { let n = len(s); let len = 3; n + len }\n"

(* 7. The reference is found wherever it sits: lambda body, match arm,
constant initialiser, loop body. *)
let nested_references () =
refused ~names:[ "int_to_string" ]
"fn f() -> String { let g = fn(n: Int) => int_to_string(n); g(1) }\n";
refused ~names:[ "len" ]
"enum Box { Full(String), Empty }\n\
fn f(o: Box) -> Int { match o { Full(s) => len(s), Empty => 0 } }\n";
refused ~names:[ "len" ] "const N: Int = len(\"abc\");\n";
refused ~names:[ "len" ]
"fn f(s: String) -> Int { let mut i = 0; while i < len(s) { i = i + 1; } i }\n"

(* 8. A program with no builtin reference is untouched. *)
let no_builtins_unaffected () =
let js = accepted "fn add(a: Int, b: Int) -> Int { a + b }\n" in
Alcotest.(check bool) "add is emitted" true (contains ~needle:"function add(a, b)" js)

let tests = [
Alcotest.test_case "issue #832 example is refused by name" `Quick issue_example;
Alcotest.test_case "each string builtin is refused by its own name" `Quick each_string_builtin;
Alcotest.test_case "every resolver builtin is bound or refused" `Quick every_resolver_builtin_bound_or_refused;
Alcotest.test_case "prelude builtins still compile" `Quick provided_builtins_compile;
Alcotest.test_case "a program binding shadows the builtin" `Quick program_bindings_shadow;
Alcotest.test_case "shadowing is scoped" `Quick shadow_is_scoped;
Alcotest.test_case "nested references are refused" `Quick nested_references;
Alcotest.test_case "program without builtins is unaffected" `Quick no_builtins_unaffected;
]
1 change: 1 addition & 0 deletions test/test_main.ml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ let () =
("Record update + imported types", Test_records_and_imports.tests);
("Module mut (#548)", Test_module_mut.tests);
("Int-div on JS-text backend (#478)", Test_int_div_js.tests);
("JS-text backend refuses unprovided builtins (#832)", Test_js_builtin_refusal.tests);
("Bun-ESM let rebinding (#827)", Test_let_rebind_bun.tests);
("Deno builtins ↔ stdlib decls consistency", Test_deno_builtins_consistency.tests);
("Bun integer block scope", Test_int_scope_bun.tests);
Expand Down
Loading