-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.affine
More file actions
335 lines (304 loc) · 9.8 KB
/
Copy pathjson.affine
File metadata and controls
335 lines (304 loc) · 9.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2025 hyperpolymath
//
// Json - JSON value type, decoders, encoders, and serialisation (echidna#63)
//
// Backs the ReScript->AffineScript migration's `Json` requirement
// (echidna `[migration-roadmap.rescript-to-affinescript]`, Client.res):
// request bodies are built with the encoders + `stringify`, and backend
// responses are inspected with the decoders.
//
// `Json` is a pure recursive sum type (not the opaque `Deno.Json`
// host handle): the decoders need an inspectable structure, and a pure
// ADT keeps the module self-contained and exercised by the #136 AOT
// gate. Object payloads use the assoc-list shape `[(String, Json)]` —
// the same representation as `dict.affine` (echidna#64), so a decoded
// object feeds `dict::get` directly.
//
// Scope (echidna#63 "What is needed"): the `Json` type, the decode_*
// and encode_* combinators, and `stringify`.
//
// v0.3 (this revision) — adds the `parse` bridge as a thin wrapper
// over the `hyperpolymath/hpm-json-rsr` Zig FFI surface (11 exports).
// The wrapper does NOT hand-roll a JSON parser: `hpm_json_parse`
// owns parsing + arena allocation, and AffineScript-side functions
// tree-walk the resulting opaque `HpmJsonValue` handle into the AS
// `Json` sum type for leaves + arrays. Object-key enumeration is
// not yet exposed by the Zig FFI — see `to_json` for the gap, and
// prefer the lazy `hpm_json_object_get` + leaf-extract pattern for
// object payloads (e.g. GitHub webhook JSON).
module json;
use prelude::{ Option, Some, None };
use string::{ join };
// ============================================================================
// The JSON value
// ============================================================================
pub type Json =
JNull
| JBool(Bool)
| JInt(Int)
| JFloat(Float)
| JString(String)
| JArray([Json])
| JObject([(String, Json)])
// ============================================================================
// Encoders (typed value -> Json)
// ============================================================================
/// JSON `null`.
pub fn encode_null() -> Json {
JNull
}
pub fn encode_bool(b: Bool) -> Json {
JBool(b)
}
pub fn encode_int(n: Int) -> Json {
JInt(n)
}
pub fn encode_float(f: Float) -> Json {
JFloat(f)
}
pub fn encode_string(s: String) -> Json {
JString(s)
}
pub fn encode_array(xs: [Json]) -> Json {
JArray(xs)
}
/// Build an object from `(key, Json)` pairs (same shape as `dict`).
pub fn encode_object(fields: [(String, Json)]) -> Json {
JObject(fields)
}
// ============================================================================
// Decoders (Json -> Option<typed value>)
//
// Each returns `None` on a type mismatch so callers can fail softly on
// malformed backend data (Client.res pattern).
// ============================================================================
/// `Some(())`-style null check: `true` iff the value is JSON `null`.
pub fn decode_null(j: Json) -> Bool {
match j {
JNull => true,
_ => false
}
}
pub fn decode_bool(j: Json) -> Option<Bool> {
match j {
JBool(b) => Some(b),
_ => None
}
}
pub fn decode_int(j: Json) -> Option<Int> {
match j {
JInt(n) => Some(n),
_ => None
}
}
pub fn decode_float(j: Json) -> Option<Float> {
match j {
JFloat(f) => Some(f),
_ => None
}
}
pub fn decode_string(j: Json) -> Option<String> {
match j {
JString(s) => Some(s),
_ => None
}
}
pub fn decode_array(j: Json) -> Option<[Json]> {
match j {
JArray(xs) => Some(xs),
_ => None
}
}
/// Decode an object to its `(key, Json)` pairs — feed straight into
/// `dict::get` for field lookup.
pub fn decode_object(j: Json) -> Option<[(String, Json)]> {
match j {
JObject(fields) => Some(fields),
_ => None
}
}
/// Look up a single object field by key (`None` if not an object or the
/// key is absent). Convenience for the common `obj["field"]` pattern.
pub fn get_field(j: Json, key: String) -> Option<Json> {
match j {
JObject(fields) => {
for (k, v) in fields {
if k == key {
return Some(v);
}
}
None
},
_ => None
}
}
// ============================================================================
// Serialisation (Json -> String)
// ============================================================================
/// Map a nibble (0-15) to its lowercase hex digit.
fn hex_digit(n: Int) -> String {
let table = "0123456789abcdef";
if n >= 0 && n < 16 {
string_sub(table, n, 1)
} else {
"0"
}
}
/// Escape one source character (given by its code point) for inclusion
/// in a JSON string literal. Handles the JSON-mandatory escapes plus
/// `\u00XX` for the remaining C0 control characters.
fn escape_char(s: String, i: Int) -> String {
let code = char_to_int(string_get(s, i));
if code == 34 {
"\""
} else if code == 92 {
"\\"
} else if code == 8 {
"\b"
} else if code == 12 {
"\f"
} else if code == 10 {
"\n"
} else if code == 13 {
"\r"
} else if code == 9 {
"\t"
} else if code < 32 {
let hi = code / 16;
let lo = code - hi * 16;
"\\u00" ++ hex_digit(hi) ++ hex_digit(lo)
} else {
string_sub(s, i, 1)
}
}
/// Quote and escape a string as a JSON string literal.
fn escape_string(s: String) -> String {
let n = len(s);
let mut out = "\"";
let mut i = 0;
while i < n {
out = out ++ escape_char(s, i);
i = i + 1;
}
out ++ "\""
}
// ============================================================================
// RSR rewire (v0.3) — hpm-json-rsr Zig FFI bindings
//
// The 11 `hpm_json_*` externs faithfully mirror the Zig exports at
// `hyperpolymath/hpm-json-rsr/ffi/zig/src/main.zig`. They lower on the
// Deno-ESM backend (lib/codegen_deno.ml) to `JSON.parse` + JS-native
// walks (a handle is just the underlying JS value); on native targets
// they map to FFI into the hpm-json-rsr cdylib.
//
// HpmJsonValue is an opaque, host-managed handle. Pair every Some(h)
// from `parse` / `hpm_json_object_get` / `hpm_json_array_get` with a
// matching `hpm_json_free(h)` to release the arena (no-op on JS, real
// free on native).
//
// Sentinel conventions (faithful to the Zig surface):
// hpm_json_type -> 0=null 1=bool 2=int 3=float 4=string 5=array 6=object; -1 on null val
// hpm_json_bool -> 0/1; -1 on type mismatch
// hpm_json_int -> INT64_MIN on type mismatch
// hpm_json_float -> NaN on type mismatch
//
// Object-key enumeration is NOT yet a Zig export; consequently `to_json`
// returns None for HpmJsonValue roots whose type tag is 6 (object). For
// object payloads, descend lazily via `hpm_json_object_get`.
// ============================================================================
pub extern type HpmJsonValue;
pub extern fn hpm_json_parse(src: String) -> Option<HpmJsonValue>;
pub extern fn hpm_json_free(val: HpmJsonValue) -> Int;
pub extern fn hpm_json_type(val: HpmJsonValue) -> Int;
pub extern fn hpm_json_bool(val: HpmJsonValue) -> Int;
pub extern fn hpm_json_int(val: HpmJsonValue) -> Int;
pub extern fn hpm_json_float(val: HpmJsonValue) -> Float;
pub extern fn hpm_json_string(val: HpmJsonValue) -> String;
pub extern fn hpm_json_object_get(val: HpmJsonValue, key: String) -> Option<HpmJsonValue>;
pub extern fn hpm_json_array_len(val: HpmJsonValue) -> Int;
pub extern fn hpm_json_array_get(val: HpmJsonValue, idx: Int) -> Option<HpmJsonValue>;
pub extern fn hpm_json_escape_string(src: String) -> String;
/// Parse `src` into an owning RSR handle, or `None` on malformed JSON.
/// Caller MUST pair every returned `Some(h)` with `hpm_json_free(h)`
/// to release the underlying parsed arena. (No-op on Deno-ESM, real
/// arena-free on native.)
pub fn parse(src: String) -> Option<HpmJsonValue> {
hpm_json_parse(src)
}
/// Tree-walk a non-object `HpmJsonValue` into the AS `Json` sum.
///
/// Returns `None` if the value's root is an object (tag 6) — see the
/// module preamble: object-key enumeration is not yet exported by the
/// Zig FFI. Leaves + arrays of leaves/arrays materialise fully.
///
/// Recursively `hpm_json_free`s every child handle the walk allocates;
/// the root handle is the caller's responsibility (matches the parse
/// ownership contract).
pub fn to_json(val: HpmJsonValue) -> Option<Json> {
let t = hpm_json_type(val);
if t == 0 {
Some(JNull)
} else if t == 1 {
Some(JBool(hpm_json_bool(val) == 1))
} else if t == 2 {
Some(JInt(hpm_json_int(val)))
} else if t == 3 {
Some(JFloat(hpm_json_float(val)))
} else if t == 4 {
Some(JString(hpm_json_string(val)))
} else if t == 5 {
let n = hpm_json_array_len(val);
let mut acc = [];
let mut i = 0;
while i < n {
match hpm_json_array_get(val, i) {
Some(child) => {
match to_json(child) {
Some(j) => {
acc = acc ++ [j];
hpm_json_free(child);
},
None => {
hpm_json_free(child);
return None;
}
}
},
None => {
return None;
}
};
i = i + 1;
}
Some(JArray(acc))
} else {
// tag 6 (object) — no key-enumeration in the Zig FFI yet;
// tag -1 (null val) — defensive: shouldn't reach here.
None
}
}
/// Serialise a `Json` value to a compact JSON string.
pub fn stringify(j: Json) -> String {
match j {
JNull => "null",
JBool(b) => if b { "true" } else { "false" },
JInt(n) => int_to_string(n),
JFloat(f) => float_to_string(f),
JString(s) => escape_string(s),
JArray(xs) => {
let mut parts = [];
for x in xs {
parts = parts ++ [stringify(x)];
}
"[" ++ join(parts, ",") ++ "]"
},
JObject(fields) => {
let mut parts = [];
for (k, v) in fields {
parts = parts ++ [escape_string(k) ++ ":" ++ stringify(v)];
}
"{" ++ join(parts, ",") ++ "}"
}
}
}