Skip to content

Commit 9cafbb2

Browse files
hyperpolymathclaudecoderabbitai[bot]HoTT-stuff
authored
fix(codegen,modules,json): local shadowing, transitive collisions, runtime pruning, stringify escapes; add Url (#798)
Upstream fixes found while porting `metadatastician/consent-aware-inspector`'s core to AffineScript (owner ruling: fix upstream first). **Split:** on the owner's ruling after review, JSON object-key enumeration moved to #799 (`Depends on: #798`). It waits for the `hpm-json-rsr` Zig exports, so no native build here can meet an unresolved symbol. ## Added - **`stdlib/Url.affine`: `url_resolve` and `url_parse`.** WHATWG semantics through the host's `globalThis.URL`, so results agree with browsers and Bun even when a program declares its own `URL`. Bun-ESM only; no native lowering. ## Fixed - **Local bindings named like a host intrinsic** (`get`, `len`, `trim`, `show`, ...) now shadow it. A parameter `get` used to compile to the ref-cell builtin and crash. - Binders are scoped lexically: parameters, `let`, `for`, lambda, match-arm and `catch`. - Sibling arms are generated outside an arm's scope. - A `let`'s initializer still sees the intrinsic, so `let len = len(s)` works. - **Module flattening rebound calls to the wrong function.** When two modules' different public declarations of one name reached a program transitively, last-wins kept one; `viaA(1)` returned 100 instead of 2. - The flattener now raises `ImportCollision`. - One declaration reached by two paths is still accepted, identified by its source span: internalised copies differ structurally but are the same declaration. - **The whole runtime (~300 helpers) was emitted into every Bun-ESM module**, including a `document.body.innerHTML` setter that `web-ext lint` flags. Only the helpers a module reaches are emitted now, in their original order. The inspector core went from 295 helpers to 24 and from 1 lint warning to 0. - **`json::stringify` produced invalid JSON** for `"`, `\` and control characters; `escape_char` returned the bare character. - **`to_json` accepted non-finite numbers**, which have no JSON form; it now rejects them. - **Statement-position `match` guards ran before their arm's bindings existed** (pre-existing). Arms now bind first and fall through on a false guard. - **`for x in e` evaluated `e` with `x` already in its temporal dead zone** (pre-existing). The iterable now goes into a temporary first. ## Tests Every new test fails on the commit before its fix. - `tests/codegen-bun/local_shadows_builtin`: parameter, `let`, lambda, loop and arm scopes, guards, and `for`. - `url_module`: every `UrlParts` field, and a variant named `URL`. - `json_escapes`: escaping and non-finite numbers. - `diamond_internalised`: the same declaration reached by two paths compiles. - `collision/`: a negative check that must fail with `ImportCollision`. - `test/test_runtime_prune.ml`: the runtime has the shape pruning relies on (const declarations only, nothing reached by a computed name), and reachability and order hold. A pruner that drops transitive dependencies fails it and the `http_fetch` corpus harness. Local runs on this branch: - `dune runtest`: 594 tests pass. - Bun-ESM harnesses: 6, plus three negative controls. - codegen-deno corpus: 39 harnesses. WASM corpus: 38 harnesses. - `check-no-extension-ts`, `check-doc-truthing`, `check-deed-gates`: pass. - `check-soundness-ledger`: passes after `git fetch --depth=1000`; it fails on any shallow clone, the base included. ## Review - 11 of CodeRabbit's 12 threads are fixed and resolved. - The O(n²) `acc ++ [x]` accumulation stays open. It is the language-wide idiom, and the owner chose an affine in-place `array::push` (consuming its input, so an in-place JS `push` is sound) as a follow-up PR. ## Follow-ups - Real module namespacing, so two modules may each export `f`. This PR only makes the collision loud. - `docs/STDLIB-EXTERN-AUDIT.adoc` (dated 2026-05-23) already omits `json.affine`. - `affinescript compile -o dir/x.js` raises an uncaught `Sys_error` when `dir` is missing, instead of creating it or reporting it. Commits are unsigned. This container's signing shim is inactive. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01J4QvDiosfvobXq67wbduuK --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> Co-authored-by: CLAUDE <355856132+HoTT-stuff@users.noreply.github.com>
1 parent 2253e90 commit 9cafbb2

30 files changed

Lines changed: 1023 additions & 64 deletions

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,3 +121,5 @@ tools/vendor/
121121
# affinescript-tea browser test deps
122122
/affinescript-tea/e2e/node_modules/
123123
/affinescript-router/e2e/node_modules/
124+
/tests/codegen-bun/collision/*.log
125+
/tests/codegen-bun/collision/*.bun.js

‎CHANGELOG.adoc‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@ kept so existing scripts fail loudly (Refs #56)
2323

2424
==== Added
2525

26+
* json: `hpm_json_object_len` / `hpm_json_object_key` enumerate object
27+
members, so `to_json` materialises objects instead of returning `None`.
28+
Lowered on Bun-ESM; the matching hpm-json-rsr Zig exports are not merged
29+
yet, so native targets cannot link them until they are.
30+
* Url: new `stdlib/Url.affine` with `url_resolve` and `url_parse`, WHATWG
31+
semantics via the host `URL` constructor. Bun-ESM only; no native lowering.
2632
* PixiUI: rename extern type `List` → `UiList` so `use PixiUI` typechecks
2733
against prelude `List<T>` (kind mismatch). Harness actually imports
2834
`smokeIdaptikReach` / Assets mock. Smokes compile + run (Refs #760)
@@ -109,6 +115,26 @@ pure-extern semantics (Closes #332) (#338)
109115

110116
==== Fixed
111117

118+
* Bun-ESM: every module carried the whole runtime (~300 host helpers),
119+
including a `document.body.innerHTML` setter that add-on linters flag. Only
120+
the helpers a module reaches are emitted now, in their original order
121+
(`test/test_runtime_prune.ml`).
122+
* json: `stringify` emitted invalid JSON for strings containing `"`, `\`
123+
or a control character: `escape_char` returned the bare character instead
124+
of its two-character escape. Now round-trips (`tests/codegen-bun/json_escapes`).
125+
* Bun-ESM: a local binding named like a host intrinsic (`get`, `len`,
126+
`trim`, `show`, ...) now shadows it. A parameter `get` compiled to the
127+
ref-cell builtin and crashed at run time. Parameters, `let`, `for`, lambda,
128+
match-arm and `catch` binders are scoped, a block's `let`s end with the block,
129+
a source block keeps its braces, and a call to a local is classed as an `Int`
130+
division operand only by its own declared type (`len: fn(String) -> Int`),
131+
never by the intrinsic it shadows (`tests/codegen-bun/local_shadows_builtin`,
132+
`test/test_int_scope_bun.ml`).
133+
* Bun-ESM: an `Int` assigned inside a nested block to an enclosing variable
134+
was forgotten at the block's end, so a later `n / 2` did not truncate.
135+
* json (Bun-ESM): `hpm_json_object_key` cached an object's keys for the
136+
length of a walk, so after the host deleted a member it still returned the
137+
deleted name. It now reads the live object (`tests/codegen-bun/json_object_keys`).
112138
* fix(modules,codegen): same-named functions in two modules no longer
113139
collapse to one in a flattened program (Bun-ESM, JS and the other
114140
non-Wasm backends). Every function and constant of an imported module is

‎docs/specs/zig-ffi-patterns.adoc‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,22 @@ pub extern fn hpm_json_free(val: HpmJsonValue) -> Int; // ownership: caller fr
213213
* `parse` returns `Option` because parsing can fail.
214214
* `free` discharges the host allocation; every successful `parse` is
215215
balanced by exactly one `free`.
216+
217+
*Wasm host import set (changed in json v0.4).* A Wasm module that brings in
218+
`json`'s externs, for example with `use json::*`, imports every
219+
`hpm_json_*` extern whether or not it calls one. v0.4 adds
220+
`hpm_json_object_len` and `hpm_json_object_key`, so the set grows from 11
221+
to 13. Compiled with `use json::*`, the imports appear under the `json`
222+
module (`json.hpm_json_object_len`, `json.hpm_json_object_key`), not under
223+
`env` as the generic description above says. A host that supplies only the
224+
v0.3 eleven fails to instantiate the module with a `LinkError`, before any
225+
code runs. Stubs are safe only for imports that are never called;
226+
alternatively, import `json` selectively (`use json::{encode_int}` imports
227+
only what it names). A length stub returning 0 makes `to_json` convert
228+
even a non-empty object to `Some(JObject([]))` without calling
229+
`hpm_json_object_key`, so a key stub returning `None` does not reject it.
230+
Object conversion requires working host implementations of both accessors
231+
or an explicit rejection path before object conversion proceeds.
216232
* No effect row: parsing a string is pure with respect to the affine
217233
effect lattice (the allocation is an implementation detail of the host).
218234

‎lib/codegen_deno.ml‎

Lines changed: 356 additions & 42 deletions
Large diffs are not rendered by default.

‎stdlib/Url.affine‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// SPDX-License-Identifier: MPL-2.0
2+
// SPDX-FileCopyrightText: 2026 hyperpolymath
3+
//
4+
// Url.affine — URL parsing and reference resolution.
5+
//
6+
// Semantics are the WHATWG URL Standard's, because the hosts these programs
7+
// run in (browsers, extensions, Bun, Deno) resolve URLs that way, and code
8+
// that compares or rewrites URLs must agree with them. WHATWG differs from
9+
// RFC 3986 in places (backslashes, default ports, host normalisation), so a
10+
// hand-rolled RFC 3986 resolver would silently disagree with the host.
11+
//
12+
// Portability: both externs are lowered by the ESM backend
13+
// (lib/codegen_deno.ml) to the host's `URL` constructor. There is no native
14+
// lowering yet; a native backend must supply a WHATWG-conformant parser
15+
// before these can be used there.
16+
17+
module Url;
18+
19+
use prelude::{Option, Some, None};
20+
21+
/// The components of a parsed absolute URL, as WHATWG's URL API reports
22+
/// them: `protocol` keeps its trailing ":", `search` its leading "?" and
23+
/// `hash` its leading "#"; absent parts are "".
24+
pub type UrlParts = {
25+
href: String,
26+
protocol: String,
27+
username: String,
28+
password: String,
29+
host: String,
30+
hostname: String,
31+
port: String,
32+
pathname: String,
33+
search: String,
34+
hash: String
35+
}
36+
37+
/// Resolve `href` against `base`. `base` "" means no base, so `href` must
38+
/// itself be absolute. `None` when the result is not a valid URL.
39+
pub extern fn url_resolve(href: String, base: String) -> Option<String>;
40+
41+
/// Parse an absolute URL. `None` when `s` is not one.
42+
pub extern fn url_parse(s: String) -> Option<UrlParts>;

‎stdlib/json.affine‎

Lines changed: 63 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,10 @@
2323
// The wrapper does NOT hand-roll a JSON parser: `hpm_json_parse`
2424
// owns parsing + arena allocation, and AffineScript-side functions
2525
// tree-walk the resulting opaque `HpmJsonValue` handle into the AS
26-
// `Json` sum type for leaves + arrays. Object-key enumeration is
27-
// not yet exposed by the Zig FFI — see `to_json` for the gap, and
28-
// prefer the lazy `hpm_json_object_get` + leaf-extract pattern for
29-
// object payloads (e.g. GitHub webhook JSON).
26+
// `Json` sum type. Object members are enumerated through
27+
// `hpm_json_object_len` / `hpm_json_object_key` (v0.4). Those two are
28+
// lowered on the ESM backend; the matching hpm-json-rsr Zig exports are
29+
// not merged yet, so native targets cannot link them until they are.
3030

3131
module json;
3232

@@ -175,19 +175,19 @@ fn hex_digit(n: Int) -> String {
175175
fn escape_char(s: String, i: Int) -> String {
176176
let code = char_to_int(string_get(s, i));
177177
if code == 34 {
178-
"\""
178+
"\\\""
179179
} else if code == 92 {
180-
"\\"
180+
"\\\\"
181181
} else if code == 8 {
182-
"\b"
182+
"\\b"
183183
} else if code == 12 {
184-
"\f"
184+
"\\f"
185185
} else if code == 10 {
186-
"\n"
186+
"\\n"
187187
} else if code == 13 {
188-
"\r"
188+
"\\r"
189189
} else if code == 9 {
190-
"\t"
190+
"\\t"
191191
} else if code < 32 {
192192
let hi = code / 16;
193193
let lo = code - hi * 16;
@@ -212,7 +212,7 @@ fn escape_string(s: String) -> String {
212212
// ============================================================================
213213
// RSR rewire (v0.3) — hpm-json-rsr Zig FFI bindings
214214
//
215-
// The 11 `hpm_json_*` externs faithfully mirror the Zig exports at
215+
// Eleven of the 13 `hpm_json_*` externs mirror the Zig exports at
216216
// `hyperpolymath/hpm-json-rsr/ffi/zig/src/main.zig`. They lower on the
217217
// Deno-ESM backend (lib/codegen_deno.ml) to `JSON.parse` + JS-native
218218
// walks (a handle is just the underlying JS value); on native targets
@@ -229,9 +229,12 @@ fn escape_string(s: String) -> String {
229229
// hpm_json_int -> INT64_MIN on type mismatch
230230
// hpm_json_float -> NaN on type mismatch
231231
//
232-
// Object-key enumeration is NOT yet a Zig export; consequently `to_json`
233-
// returns None for HpmJsonValue roots whose type tag is 6 (object). For
234-
// object payloads, descend lazily via `hpm_json_object_get`.
232+
// hpm_json_object_len -> 0 on type mismatch
233+
// hpm_json_object_key -> None on type mismatch or index out of range
234+
//
235+
// `hpm_json_object_len` and `hpm_json_object_key` are the v0.4 additions.
236+
// Until hpm-json-rsr ships the matching Zig exports they exist on the ESM
237+
// backend only.
235238
// ============================================================================
236239

237240
pub extern type HpmJsonValue;
@@ -244,6 +247,13 @@ pub extern fn hpm_json_int(val: HpmJsonValue) -> Int;
244247
pub extern fn hpm_json_float(val: HpmJsonValue) -> Float;
245248
pub extern fn hpm_json_string(val: HpmJsonValue) -> String;
246249
pub extern fn hpm_json_object_get(val: HpmJsonValue, key: String) -> Option<HpmJsonValue>;
250+
/// Number of members of an object value; 0 on type mismatch.
251+
pub extern fn hpm_json_object_len(val: HpmJsonValue) -> Int;
252+
/// Key of the `idx`-th member of an object value, in document order; `None`
253+
/// on type mismatch or out-of-range index. Integer-like keys may be ordered
254+
/// differently by the JavaScript host (it lists them first), so callers must
255+
/// not depend on their relative order.
256+
pub extern fn hpm_json_object_key(val: HpmJsonValue, idx: Int) -> Option<String>;
247257
pub extern fn hpm_json_array_len(val: HpmJsonValue) -> Int;
248258
pub extern fn hpm_json_array_get(val: HpmJsonValue, idx: Int) -> Option<HpmJsonValue>;
249259
pub extern fn hpm_json_escape_string(src: String) -> String;
@@ -256,11 +266,8 @@ pub fn parse(src: String) -> Option<HpmJsonValue> {
256266
hpm_json_parse(src)
257267
}
258268

259-
/// Tree-walk a non-object `HpmJsonValue` into the AS `Json` sum.
260-
///
261-
/// Returns `None` if the value's root is an object (tag 6) — see the
262-
/// module preamble: object-key enumeration is not yet exported by the
263-
/// Zig FFI. Leaves + arrays of leaves/arrays materialise fully.
269+
/// Tree-walk an `HpmJsonValue` into the AS `Json` sum. Objects keep their
270+
/// members in the order `hpm_json_object_key` reports them.
264271
///
265272
/// Recursively `hpm_json_free`s every child handle the walk allocates;
266273
/// the root handle is the caller's responsibility (matches the parse
@@ -274,7 +281,10 @@ pub fn to_json(val: HpmJsonValue) -> Option<Json> {
274281
} else if t == 2 {
275282
Some(JInt(hpm_json_int(val)))
276283
} else if t == 3 {
277-
Some(JFloat(hpm_json_float(val)))
284+
// JSON has no Infinity or NaN: a value that parsed to one (`1e400`)
285+
// has no JSON form, so it does not convert.
286+
let f = hpm_json_float(val);
287+
if f - f == 0.0 { Some(JFloat(f)) } else { None }
278288
} else if t == 4 {
279289
Some(JString(hpm_json_string(val)))
280290
} else if t == 5 {
@@ -302,8 +312,39 @@ pub fn to_json(val: HpmJsonValue) -> Option<Json> {
302312
i = i + 1;
303313
}
304314
Some(JArray(acc))
315+
} else if t == 6 {
316+
let n = hpm_json_object_len(val);
317+
let mut fields = [];
318+
let mut i = 0;
319+
while i < n {
320+
match hpm_json_object_key(val, i) {
321+
Some(k) => {
322+
match hpm_json_object_get(val, k) {
323+
Some(child) => {
324+
match to_json(child) {
325+
Some(j) => {
326+
fields = fields ++ [(k, j)];
327+
hpm_json_free(child);
328+
},
329+
None => {
330+
hpm_json_free(child);
331+
return None;
332+
}
333+
}
334+
},
335+
None => {
336+
return None;
337+
}
338+
}
339+
},
340+
None => {
341+
return None;
342+
}
343+
};
344+
i = i + 1;
345+
}
346+
Some(JObject(fields))
305347
} else {
306-
// tag 6 (object) — no key-enumeration in the Zig FFI yet;
307348
// tag -1 (null val) — defensive: shouldn't reach here.
308349
None
309350
}

‎test/test_int_scope_bun.ml‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
(* SPDX-License-Identifier: MPL-2.0 *)
2+
open Affinescript
3+
4+
(* Exercise emission directly: the frontend currently rejects nested
5+
statement bindings that shadow an enclosing binding with another type. *)
6+
let count_truncs src =
7+
let prog = Parse_driver.parse_string ~file:"<int_scope>" src in
8+
let loader = Module_loader.create (Module_loader.default_config ()) in
9+
let ctx = match Resolve.resolve_program_with_loader prog loader with
10+
| Ok (ctx, _) -> ctx
11+
| Error (e, _) -> Alcotest.fail (Resolve.show_resolve_error e)
12+
in
13+
match Codegen_deno.codegen_bun prog ctx.symbols with
14+
| Error e -> Alcotest.fail e
15+
| Ok js -> Test_int_div_js.count_occurrences ~needle:"Math.trunc(" js
16+
17+
let expect_truncs what n src =
18+
Alcotest.(check int) what n (count_truncs src)
19+
20+
let check_divisions = expect_truncs "only the Int division truncates" 1
21+
22+
let tests = [
23+
Alcotest.test_case "inner Int preserves outer Float" `Quick (fun () ->
24+
check_divisions {|pub fn f() -> Float {
25+
let x = 7.0; let y = 2.0;
26+
{ let x = 9; let y = 2; x / y; };
27+
x / y
28+
}|});
29+
Alcotest.test_case "inner Float preserves outer Int" `Quick (fun () ->
30+
check_divisions {|pub fn f() -> Int {
31+
let x = 7;
32+
{ let x = 9.0; x / 2.0; };
33+
x / 2
34+
}|});
35+
(* An assignment in a nested block changes the enclosing variable, so the
36+
Int it records outlives the block. *)
37+
Alcotest.test_case "Int assigned in a block to an enclosing var" `Quick (fun () ->
38+
expect_truncs "the division after the block truncates" 1
39+
{|pub fn f(flag: Bool) -> Int {
40+
let mut n = match flag { true => 5, false => 7 };
41+
{ n = 5; };
42+
n / 2
43+
}|});
44+
(* ... but not when the block declared its own binding of that name. *)
45+
Alcotest.test_case "Int assigned to a block's own binding" `Quick (fun () ->
46+
expect_truncs "the outer Float division does not truncate" 0
47+
{|pub fn f() -> Float {
48+
let mut n = 7.0;
49+
{ let mut n = 0.0; n = 5; };
50+
n / 2.0
51+
}|});
52+
(* A lambda parameter is scoped to the lambda: an Int assigned to it does
53+
not classify a same-named outer Float. *)
54+
Alcotest.test_case "Int assigned to a lambda parameter" `Quick (fun () ->
55+
expect_truncs "the outer Float division does not truncate" 0
56+
{|pub fn f() -> Float {
57+
let k = 7.0;
58+
let g = |k| { k = 4; 0 };
59+
k / 2.0
60+
}|});
61+
(* A callable local is classified by its own declared return type. *)
62+
Alcotest.test_case "Int-returning callable parameter" `Quick (fun () ->
63+
expect_truncs "len(s) / 2 truncates" 1
64+
{|pub fn f(len: fn(String) -> Int) -> Int { len("abcde") / 2 }|});
65+
Alcotest.test_case "Float-returning callable shadows intrinsic" `Quick (fun () ->
66+
expect_truncs "len(s) / 2.0 does not truncate" 0
67+
{|pub fn f(len: fn(String) -> Float) -> Float { len("abcde") / 2.0 }|});
68+
Alcotest.test_case "Int-returning callable let" `Quick (fun () ->
69+
expect_truncs "w(s) / 2 truncates" 1
70+
{|pub fn f() -> Int {
71+
let w: fn(String) -> Int = |s| 5;
72+
w("abcde") / 2
73+
}|});
74+
]

‎test/test_main.ml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ let () =
3434
("Module mut (#548)", Test_module_mut.tests);
3535
("Int-div on JS-text backend (#478)", Test_int_div_js.tests);
3636
("Deno builtins ↔ stdlib decls consistency", Test_deno_builtins_consistency.tests);
37+
("Bun integer block scope", Test_int_scope_bun.tests);
38+
("ESM runtime pruning", Test_runtime_prune.tests);
3739
("Stdlib algebraic laws (batch 1)", Test_stdlib_laws.tests);
3840
("Solo CESK (VM M1, ADR-0025)", Test_solo_cesk.tests);
3941
("Polonius solver (ADR-022 M3)", Test_borrow_polonius.tests);

0 commit comments

Comments
 (0)