json
Recursive-descent JSON parse + stringify.
JsonValue is the tagged union of every JSON shape. parse returns
JsonValue | JsonError ; parse failures surface as the JsonError variant,
propagated by an explicit if e is JsonError { return e } narrowing guard.
stringify writes a value back, compact or indented.
Numbers are stored as f64 for MVP: fine for the compiler's use cases
(manifests, diagnostics) but loses precision past 2^53. Cf. TODO.md std/json
v2 for the post-MVP compile-time-generated parser à la kotlinx-serialization.
Types
JsonValue :: JsonString | JsonNumber | JsonBool | JsonNull | JsonArray | JsonObject Tagged union covering every JSON shape (null, true/false, numbers,
strings, arrays, objects). Discriminated via is JsonString etc. in
match. Numbers carry an f64 ; precision past 2^53 is lost (MVP
limitation).
JsonString :: struct JSON string variant: UTF-8 decoded, escape-resolved.
Fields
value: string JsonNumber :: struct JSON number variant: f64. Integer-valued numbers round-trip
through to_compact_str for cleaner output.
Fields
value: f64 JsonBool :: struct JSON true/false.
Fields
value: bool JsonNull :: struct JSON null. No payload.
JsonArray :: struct JSON array: ordered list of JsonValues.
Fields
items: JsonValue[] JsonObject :: struct JSON object: string-keyed map of JsonValues. Insertion order is
preserved by the parser ; lookup is O(1) average via MutableMap.
Fields
entries: MutableMap<string, JsonValue> JsonError :: struct Error raised by parse when the input isn't valid JSON. pos is the
byte offset of the offending character.
Fields
msg: string pos: i64 Functions
parse :: fn(input: string) -> JsonValue | JsonError Parse a complete JSON document. The input must contain exactly one JSON value optionally surrounded by whitespace ; trailing non-whitespace is an error.
Policy: malformed syntax (a bad escape, an unterminated string / container,
an invalid number, nesting past MAX_DEPTH) returns a JsonError. A
syntactically valid but unpaired \u surrogate is handled leniently: it
decodes to U+FFFD (matching Go's encoding/json), since a lone surrogate
has no UTF-8 representation.
Parameters
| input | string | the JSON text. |
Errors
JsonErrorcarrying a short message and the byte offset of the offending character.
stringify :: fn(v: JsonValue, indent: i32 = 0) -> string Serialise v to a JSON string, one line per element when indent is
positive.
Parameters
| v | JsonValue | the value to serialise. |
| indent | i32 = 0 | spaces per nesting level; 0, the default, and below write the smallest valid encoding. |
Returns
string Example
list :: JsonArray { .items = [JsonNumber { .value = 1.0 }, JsonNull {}] }
stringify(list) // "[1,null]"
stringify(list, 2) // "[\n 1,\n null\n]"