Files
rosetta/src/Formats/codecs/text/Json/init.luau
T
4DBugandClaude Opus 5.5 434a304315 ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically):
- codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder;
  codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample
  VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url;
  codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err
  Crc32 Adler32 Base64 Md5 Input Sniff.
- LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md).
- Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes.

C3, generic code out of format folders:
- containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first,
  trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64
  through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it.
- codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position,
  priming and end trimming) that aac, caf and m4a each carried (~70 lines each).
- codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of
  its own (the AND mask / alpha rule stay ICO's).
- codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model),
  Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is
  Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the
  fixtures' bind shapes).
- README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes:
  FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the
  shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks
  decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type
  baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 12:25:03 -05:00

295 lines
9.1 KiB
Luau

--!strict
-- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
-- Values are plain Luau: objects -> tables (string keys), arrays -> arrays, null -> Types.null (opts.null), numbers
-- -> doubles (opts.bigInts = "string" keeps integers past 2^53 as their text). Empty objects are Types.object() so
-- they write back as {}; opts.ordered makes every object a Types.object with its key order.
--
-- local Json = require("@formats/codecs/text/Json")
-- local v, err = Json.decode('{"a": [1, 2, null]}') -- string | buffer; nil, Err on bad input
-- local s = Json.encode(v, { indent = 2 }) -- string | nil, Err
-- for ev, x in Json.events(text) do ... end -- pull events without building the tree
-- for i, v, err in Json.lines(ndjson) do ... end -- JSON Lines / concatenated JSON values
-- local w = Json.writer({ indent = 2 }); w:beginObject(); w:key("a"); w:value(1); w:endObject(); w:tostring()
--
-- Streaming: decodeAt(src, pos) parses one value and returns where the next begins; events() is a pull tokenizer;
-- writer() builds output incrementally and flush() hands back the text so far. Never throws.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Decode = require("@formats/codecs/text/Json/Decode")
local Encode = require("@formats/codecs/text/Json/Encode")
local Json = {}
export type DecodeOptions = Decode.Options
export type EncodeOptions = Encode.Options
Json.null = Types.null
Json.object = Types.object
Json.keys = Types.keys
Json.set = Types.set
local function text(src: any): (string?, Err.Err?)
if type(src) == "string" then
return src, nil
elseif type(src) == "buffer" then
return buffer.tostring(src), nil
end
return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src))
end
local function fail(msg: any, at: any, n: number): Err.Err
local m = tostring(msg)
local code = if string.find(m, "truncated", 1, true) or string.find(m, "unterminated", 1, true) or (at or 0) >= n
then Err.TRUNCATED
elseif string.find(m, "nested deeper", 1, true) then Err.LIMIT
else Err.CORRUPT
return Err.new(code, m, at)
end
-- decode(src, opts?) -> value | nil, Err. One JSON text: a value with optional whitespace around it (a UTF-8 BOM is
-- skipped). Note a JSON null top-level value decodes to opts.null (Types.null by default), never nil.
function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err?)
local s, terr = text(src)
if not s then
return nil, terr
end
local i = if string.sub(s, 1, 3) == "\239\187\191" then 4 else 1
local v, ni, at = Decode.value(s, i, opts)
if v == nil then
return nil, fail(ni, at, #s)
end
local e = string.match(s, "^[ \t\n\r]*()", ni) :: any
if e <= #s then
return nil, Err.new(Err.CORRUPT, "trailing data after the value", e - 1)
end
return v, nil
end
-- decodeAt(src, pos?, opts?) -> value, nextPos | nil, Err. One value starting at pos (1-based, default 1; leading
-- whitespace skipped); nextPos is just past it. nil, nil when only whitespace is left.
function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?): (any, any)
local s, terr = text(src)
if not s then
return nil, terr
end
local i = string.match(s, "^[ \t\n\r]*()", pos or 1) :: any
if i > #s then
return nil, nil
end
local v, ni, at = Decode.value(s, i, opts)
if v == nil then
return nil, fail(ni, at, #s)
end
return v, ni
end
-- lines(src, opts?) -> iterator: index, value (JSON Lines, or any whitespace-separated sequence of JSON values). A
-- bad value gives a last index, nil, Err: for i, v, err in Json.lines(s) do if err then ... end end
function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, any, Err.Err?)
local s, terr = text(src)
local pos = 1
local index = 0
local dead = false
return function(): (number?, any, Err.Err?)
if dead then
return nil
end
index += 1
if not s then
dead = true
return index, nil, terr
end
local v, ni = Json.decodeAt(s, pos, opts)
if v == nil then
dead = true
if ni == nil then
return nil
end
return index, nil, ni
end
pos = ni
return index, v, nil
end
end
-- events(src, opts?) -> iterator: event, value. Events: "object", "endObject", "array", "endArray", "key" (the key),
-- "value" (a scalar), and on bad input one final "error", Err.
function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string?, any)
local s, terr = text(src)
if not s then
local done = false
return function(): (string?, any)
if done then
return nil, nil
end
done = true
return "error", terr
end
end
local str: string = s
local i = if string.sub(str, 1, 3) == "\239\187\191" then 4 else 1
local nextEv = Decode.events(str, i, opts)
return function(): (string?, any)
local ev, v, at = nextEv()
if ev == "error" then
return ev, fail(v, at, #str)
end
return ev, v
end
end
-- encode(value, opts?) -> string | nil, Err
function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?)
local s, msg = Encode.encode(value, opts)
if not s then
return nil, Err.new(Err.ARG, msg or "cannot encode")
end
return s, nil
end
Json.quote = Encode.quote -- quote(s) -> '"..."' with JSON escapes
Json.number = Encode.number -- number(x) -> the shortest round-trip text (nil for NaN / inf)
-- ------------------------------------------------------------------------------------------------ writer
-- writer(opts?) -> a streaming Writer: beginObject / endObject / beginArray / endArray / key(k) / value(v) (any
-- value, encoded whole), then tostring() for everything or flush() for the text since the last flush. Misuse (a key
-- outside an object, a value where a key is due, unbalanced ends) is recorded in w.err and later calls do nothing.
export type Writer = {
err: Err.Err?,
beginObject: (self: Writer) -> Writer,
endObject: (self: Writer) -> Writer,
beginArray: (self: Writer) -> Writer,
endArray: (self: Writer) -> Writer,
key: (self: Writer, k: string) -> Writer,
value: (self: Writer, v: any) -> Writer,
flush: (self: Writer) -> string,
tostring: (self: Writer) -> (string?, Err.Err?),
}
function Json.writer(opts: EncodeOptions?): Writer
local st = Encode.state(opts)
local ind = st.indent
local kinds: { boolean } = {} -- true = object
local counts: { number } = {}
local depth = 0
local keyDone = false -- an object's key written, its value due
local flushed: { string } = {}
local w: any = { err = nil }
local function bad(msg: string)
if not w.err then
w.err = Err.new(Err.ARG, msg)
end
end
-- before an element: a comma / newline as needed; false when the position is wrong
local function slot(isKey: boolean): boolean
if w.err then
return false
end
if depth == 0 then
if counts[0] and counts[0] > 0 then
bad("one top-level value only")
return false
end
counts[0] = 1
return true
end
local obj = kinds[depth]
if obj and not isKey then
if not keyDone then
bad("an object member needs a key first")
return false
end
keyDone = false
return true
end
if isKey and not obj then
bad("key outside an object")
return false
end
if isKey and keyDone then
bad("two keys in a row")
return false
end
if counts[depth] > 0 then
table.insert(st.out, ",")
end
counts[depth] += 1
if ind then
table.insert(st.out, "\n" .. string.rep(ind, depth))
end
return true
end
local function open(obj: boolean)
if slot(false) then
table.insert(st.out, if obj then "{" else "[")
depth += 1
kinds[depth], counts[depth] = obj, 0
end
return w
end
local function close(obj: boolean)
if w.err then
return w
end
if depth == 0 or kinds[depth] ~= obj or (obj and keyDone) then
bad(if obj then "unbalanced endObject" else "unbalanced endArray")
return w
end
if ind and counts[depth] > 0 then
table.insert(st.out, "\n" .. string.rep(ind, depth - 1))
end
table.insert(st.out, if obj then "}" else "]")
depth -= 1
return w
end
function w.beginObject(_self: Writer): Writer
return open(true)
end
function w.beginArray(_self: Writer): Writer
return open(false)
end
function w.endObject(_self: Writer): Writer
return close(true)
end
function w.endArray(_self: Writer): Writer
return close(false)
end
function w.key(_self: Writer, k: string): Writer
if type(k) ~= "string" then
bad("key must be a string")
elseif slot(true) then
table.insert(st.out, Encode.quote(k, st.ascii, st.slash) .. (if ind then ": " else ":"))
keyDone = true
end
return w
end
function w.value(_self: Writer, v: any): Writer
if slot(false) then
st.n = #st.out
if not Encode.write(st, v, depth) then
bad(st.err or "cannot encode")
end
end
return w
end
function w.flush(_self: Writer): string
local s = table.concat(st.out)
table.clear(st.out)
st.n = 0
table.insert(flushed, s)
return s
end
function w.tostring(_self: Writer): (string?, Err.Err?)
if w.err then
return nil, w.err
end
if depth ~= 0 then
return nil, Err.new(Err.ARG, "unclosed object / array")
end
return table.concat(flushed) .. table.concat(st.out), nil
end
return w :: Writer
end
return Json