Skip to content

Commit 2ed6e76

Browse files
feat(json): enumerate JSON object members (hpm_json_object_len/_key) (#799)
Depends on: #798 Split from #798 on the owner's ruling after review. That review found that the new object branch of `to_json` calls two externs with no Zig export yet, so a native build linking `to_json` would fail on unresolved symbols. ## What - `hpm_json_object_len` and `hpm_json_object_key` let `to_json` materialise objects; on `main` it returns `None` for them, the gap `json.affine` documents. - They are lowered on Bun-ESM. Index 0 snapshots the object's own keys and later indices reuse the snapshot, so a walk does one `Object.keys` (review: it was one per key). - Integer-like keys: JavaScript lists them first, while std.json keeps document order. The externs document that callers must not rely on that relative order. ## Why this waits The matching `hpm-json-rsr` Zig exports (`hpm_json_object_len`, `hpm_json_object_key`) must land first, and the owner requires atoma to verify them before the consumer leaves alpha. This session could not run a downloaded Zig binary; Guix is being set up to provide Zig 0.15.2. A PR on `hyperpolymath/hpm-json-rsr` will be linked here, and this stays a draft until it merges. Consumer: `metadatastician/consent-aware-inspector` pins this branch's head, because its manifest validation enumerates policy keys. ## Tests - `tests/codegen-bun/json_object_keys`: keys in order, nested round-trip, escaped keys, own keys only, an inherited enumerable key excluded, non-finite members rejected. - `json_escapes`: objects now convert. Local runs on this branch: `dune runtest` passes 594 tests; the Bun harnesses pass (7 plus negative controls); the codegen-deno corpus passes 39 harnesses and the WASM corpus 38. Known, tracked separately: `to_json` accumulates with `acc ++ [x]` (O(n²) for very large objects). The owner chose to fix that with an affine in-place `push` in the stdlib, as its own PR. Commits are unsigned. This container's signing shim is inactive. --- _Generated by [Claude Code](https://claude.ai/code/session_01J4QvDiosfvobXq67wbduuK)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 50b7b96 commit 2ed6e76

7 files changed

Lines changed: 171 additions & 15 deletions

File tree

‎CHANGELOG.adoc‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ 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.
2630
* Url: new `stdlib/Url.affine` with `url_resolve` and `url_parse`, WHATWG
2731
semantics via the host `URL` constructor. Bun-ESM only; no native lowering.
2832
* PixiUI: rename extern type `List` → `UiList` so `use PixiUI` typechecks

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,19 @@ 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. Until `hpm-json-rsr` exports the two functions, such a host must
226+
stub them (`hpm_json_object_len` returning 0, `hpm_json_object_key`
227+
returning `None`), which makes `to_json` reject objects, or import `json`
228+
selectively (`use json::{encode_int}` imports only what it names).
216229
* No effect row: parsing a string is pure with respect to the affine
217230
effect lattice (the allocation is an implementation detail of the host).
218231

‎lib/codegen_deno.ml‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -630,6 +630,26 @@ const __as_urlParse = (s) => {
630630
password: u.password, host: u.host, hostname: u.hostname, port: u.port,
631631
pathname: u.pathname, search: u.search, hash: u.hash });
632632
};
633+
// Object-key enumeration mirrors the planned hpm-json-rsr Zig exports
634+
// `hpm_json_object_len` / `hpm_json_object_key`: own enumerable string keys
635+
// in insertion order (std.json's ObjectMap is an ordered ArrayHashMap).
636+
// JavaScript lists integer-like keys first and the native backend will not,
637+
// so callers must not rely on the relative order of such keys.
638+
const __as_hpmJsonObjectKeys = (v) =>
639+
(v === null || typeof v !== "object" || Array.isArray(v)) ? [] : Object.keys(v);
640+
const __as_hpmJsonObjectLen = (v) => __as_hpmJsonObjectKeys(v).length;
641+
// A walk asks for keys by index, so index 0 takes a snapshot of the object's
642+
// keys and later indices read it: one Object.keys per walk, not per key.
643+
// Each walk starts at 0, so a snapshot never outlives the walk that made it.
644+
const __as_hpmJsonKeySnapshots = new WeakMap();
645+
const __as_hpmJsonObjectKey = (v, i) => {
646+
if (v === null || typeof v !== "object" || Array.isArray(v)) return None;
647+
const idx = Number(i);
648+
if (!Number.isInteger(idx) || idx < 0) return None;
649+
let ks = idx === 0 ? undefined : __as_hpmJsonKeySnapshots.get(v);
650+
if (ks === undefined) { ks = Object.keys(v); __as_hpmJsonKeySnapshots.set(v, ks); }
651+
return idx < ks.length ? Some(ks[idx]) : None;
652+
};
633653
const __as_hpmJsonArrayLen = (v) => (Array.isArray(v) ? v.length : 0);
634654
const __as_hpmJsonArrayGet = (v, i) => {
635655
if (!Array.isArray(v)) return None;
@@ -1215,6 +1235,8 @@ let () =
12151235
b "hpm_json_object_get" (fun a -> Printf.sprintf "__as_hpmJsonObjectGet(%s, %s)" (arg 0 a) (arg 1 a));
12161236
b "url_resolve" (fun a -> Printf.sprintf "__as_urlResolve(%s, %s)" (arg 0 a) (arg 1 a));
12171237
b "url_parse" (fun a -> Printf.sprintf "__as_urlParse(%s)" (arg 0 a));
1238+
b "hpm_json_object_len" (fun a -> Printf.sprintf "__as_hpmJsonObjectLen(%s)" (arg 0 a));
1239+
b "hpm_json_object_key" (fun a -> Printf.sprintf "__as_hpmJsonObjectKey(%s, %s)" (arg 0 a) (arg 1 a));
12181240
b "hpm_json_array_len" (fun a -> Printf.sprintf "__as_hpmJsonArrayLen(%s)" (arg 0 a));
12191241
b "hpm_json_array_get" (fun a -> Printf.sprintf "__as_hpmJsonArrayGet(%s, %s)" (arg 0 a) (arg 1 a));
12201242
b "hpm_json_escape_string" (fun a -> Printf.sprintf "__as_hpmJsonEscapeString(%s)" (arg 0 a));

‎stdlib/json.affine‎

Lines changed: 52 additions & 14 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

@@ -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
@@ -305,8 +312,39 @@ pub fn to_json(val: HpmJsonValue) -> Option<Json> {
305312
i = i + 1;
306313
}
307314
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))
308347
} else {
309-
// tag 6 (object) — no key-enumeration in the Zig FFI yet;
310348
// tag -1 (null val) — defensive: shouldn't reach here.
311349
None
312350
}

‎tests/codegen-bun/json_escapes.harness.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,5 @@ for (const v of ["q\"uote", "back\\slash", "nl\nx", "cr\rtab\t", "bs\bff\f", "c\
1414
}
1515
expect("non-finite element", subject.roundtrip("[1e400]"), "<none>");
1616
expect("finite exponent", subject.roundtrip("[1e3]"), "[1000]");
17-
expect("objects need key enumeration, not on this branch", subject.roundtrip('{"a":1}'), "<none>");
17+
expect("objects convert", subject.roundtrip('{"a":1}'), '{"a":1}');
1818
console.log("json_escapes: ok");
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+
// hpm_json_object_len / hpm_json_object_key (json.affine v0.4): object
3+
// members are enumerable, so `to_json` materialises objects instead of
4+
// returning None, and `stringify` round-trips them in member order.
5+
6+
use prelude::{ Option, Some, None };
7+
use json::{ Json, parse, to_json, stringify, hpm_json_object_len,
8+
hpm_json_object_key, HpmJsonValue };
9+
10+
pub fn roundtrip(src: String) -> String {
11+
match parse(src) {
12+
Some(h) => match to_json(h) { Some(j) => stringify(j), None => "<none>" },
13+
None => "<parse-fail>"
14+
}
15+
}
16+
17+
pub fn keys(src: String) -> [String] {
18+
let mut out = [];
19+
match parse(src) {
20+
Some(h) => {
21+
let n = hpm_json_object_len(h);
22+
let mut i = 0;
23+
while i < n {
24+
match hpm_json_object_key(h, i) { Some(k) => { out = out ++ [k]; }, None => {} };
25+
i = i + 1;
26+
}
27+
},
28+
None => {}
29+
};
30+
out
31+
}
32+
33+
pub fn key_at(src: String, i: Int) -> String {
34+
match parse(src) {
35+
Some(h) => match hpm_json_object_key(h, i) { Some(k) => k, None => "<none>" },
36+
None => "<parse-fail>"
37+
}
38+
}
39+
40+
pub fn len_of(src: String) -> Int {
41+
match parse(src) { Some(h) => hpm_json_object_len(h), None => -2 }
42+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// SPDX-License-Identifier: MPL-2.0
2+
import * as subject from "./json_object_keys.bun.js";
3+
4+
const expect = (label, got, want) => {
5+
const g = JSON.stringify(got), w = JSON.stringify(want);
6+
if (g !== w) throw new Error(`${label}: got ${g}, want ${w}`);
7+
};
8+
expect("flat object keys in order", subject.keys('{"b":1,"a":2,"c":3}'), ["b", "a", "c"]);
9+
expect("nested object round-trip", subject.roundtrip('{"p":{"q":[1,{"r":null}],"s":"t"},"u":true}'),
10+
'{"p":{"q":[1,{"r":null}],"s":"t"},"u":true}');
11+
expect("empty object", subject.roundtrip("{}"), "{}");
12+
expect("escaped key", subject.roundtrip('{"a\\"b":1}'), '{"a\\"b":1}');
13+
expect("length of object", subject.len_of('{"x":1,"y":2}'), 2);
14+
expect("length of array is 0", subject.len_of("[1,2]"), 0);
15+
expect("length of scalar is 0", subject.len_of("5"), 0);
16+
expect("key out of range", subject.key_at('{"x":1}', 1), "<none>");
17+
expect("negative index", subject.key_at('{"x":1}', -1), "<none>");
18+
expect("key of non-object", subject.key_at("[1]", 0), "<none>");
19+
expect("own keys only", subject.keys('{"__proto__":1,"constructor":2}'), ["__proto__", "constructor"]);
20+
// stringify must emit valid JSON that reparses to the same value (escape_char
21+
// used to return bare quote, backslash and control characters).
22+
for (const v of ["q\"uote", "back\\slash", "nl\nx", "cr\rtab\t", "bs\bff\f", "c\u0001\u001f", "\u00e9 \u2028", ""]) {
23+
const src = JSON.stringify({ k: v, [v]: [v] });
24+
const out = subject.roundtrip(src);
25+
let back;
26+
try { back = JSON.parse(out); } catch (e) { throw new Error(`invalid JSON for ${JSON.stringify(v)}: ${out}`); }
27+
expect(`string escapes ${JSON.stringify(v)}`, back, JSON.parse(src));
28+
}
29+
// Inherited enumerable keys are not members.
30+
Object.prototype.inheritedProbe = 1;
31+
try { expect("inherited key excluded", subject.keys('{"a":1}'), ["a"]); }
32+
finally { delete Object.prototype.inheritedProbe; }
33+
// JSON has no Infinity: a number that parsed to one does not convert.
34+
expect("non-finite member", subject.roundtrip('{"n":1e400}'), "<none>");
35+
expect("non-finite element", subject.roundtrip("[1e400]"), "<none>");
36+
expect("finite exponent", subject.roundtrip("[1e3]"), "[1000]");
37+
console.log("json_object_keys: ok");

0 commit comments

Comments
 (0)