data: codecs/Json (RFC 8259 parse / serialize: ordered keys, Types.null, bigInts as strings, pretty / ascii, events pull tokenizer, decodeAt / lines, streaming writer); JSONTestSuite + Python json fixtures; bench lines

Types (backward compatible additions in the Data section): Types.object / isObject / set / keys (ordered objects
and empty-object marking, shared by every data format), Types.Date (RFC 3339 typed dates for TOML / plist / CBOR /
msgpack: new / is / valid / parse / toUnix / fromUnix), XmlNode gains optional text / target / ns fields.
tools/bench.sh: also generates the json fixtures.
This commit is contained in:
4DBug committed 2026-10-31 08:30:05 -05:00
1 parent cdcb5b0b77
commit 19110e6199
10 files changed
+1818 -3

No files matched your search

+210
View File
@@ -0,0 +1,210 @@
-- codecs/Json tests: the JSONTestSuite parsing corpus (y_ must parse to Python's value, n_ must fail, i_ must not
-- throw), Python json.dumps output in four styles parsed and reproduced byte for byte (compact sorted, ordered,
-- indent 2, ensure_ascii), events / lines / decodeAt / writer, options, error codes, and the fuzz pass.
-- Fixtures: tools/fixtures/json.py.
local T = require("@tests/T")
local Json = require("@formats/codecs/Json")
local Types = require("@formats/Types")
local Err = require("@formats/core/Err")
local Canon = require("@tests/data/Canon")
local Suite = require("@tests/gen/json_suite")
local Corpus = require("@tests/gen/json_corpus")
local t = T.suite("json")
-- events() rebuilt into a value (checks the pull tokenizer agrees with decode)
local function fromEvents(s: string): (any, any)
local stack, keys = {}, {}
local top: any = nil
local key: any = nil
local function add(v: any)
local cur = stack[#stack]
if cur == nil then
top = v
elseif keys[#stack] ~= false then
cur[key] = v
else
table.insert(cur, v)
end
end
for ev, v in Json.events(s) do
if ev == "error" then
return nil, v
elseif ev == "object" or ev == "array" then
local tbl = if ev == "object" then Types.object() else {}
add(tbl)
table.insert(stack, tbl)
keys[#stack] = if ev == "object" then true else false
elseif ev == "endObject" or ev == "endArray" then
keys[#stack] = nil
table.remove(stack)
elseif ev == "key" then
key = v
else
add(v)
end
end
return top, nil
end
-- 1. JSONTestSuite
local counts = { y = 0, n = 0, i = 0, iok = 0 }
for _, c in Suite do
local v, err = Json.decode(c.data)
local ev, everr = fromEvents(c.data)
if c.expect == "y" then
t:check(v ~= nil, c.name .. ": parses (" .. tostring(err) .. ")")
t:eq(Canon.of(v), c.canon, c.name .. ": value")
t:check(ev ~= nil, c.name .. ": events parse (" .. tostring(everr) .. ")")
t:eq(Canon.of(ev), c.canon, c.name .. ": events value")
-- and our output reads back the same
local s = Json.encode(v)
t:check(s ~= nil, c.name .. ": encodes")
t:eq(Canon.of(Json.decode(s :: string)), c.canon, c.name .. ": round trip")
elseif c.expect == "n" then
t:check(v == nil and Err.is(err), c.name .. ": rejected")
t:check(ev == nil, c.name .. ": events reject")
else
counts.iok += if v ~= nil then 1 else 0
end
counts[c.expect] += 1
end
t:note("JSONTestSuite: %d y_ accepted, %d n_ rejected, %d of %d i_ accepted", counts.y, counts.n, counts.iok, counts.i)
-- 2. Python's json.dumps output: parse, compare, re-encode byte for byte
for i, c in Corpus do
local v, err = Json.decode(c.compact)
t:check(v ~= nil, "corpus " .. i .. ": " .. tostring(err))
t:eq(Canon.of(v), c.canon, "corpus " .. i .. ": value")
t:eq(Json.encode(v), c.compact, "corpus " .. i .. ": compact text")
t:eq(Json.encode(v, { indent = 2 }), c.pretty, "corpus " .. i .. ": indent 2 text")
t:eq(Json.encode(v, { ascii = true }), c.ascii, "corpus " .. i .. ": ensure_ascii text")
local o = Json.decode(c.ordered, { ordered = true })
t:eq(Json.encode(o), c.ordered, "corpus " .. i .. ": ordered text")
t:eq(Canon.of(Json.decode(c.ascii)), c.canon, "corpus " .. i .. ": ascii parse")
t:eq(Canon.of(Json.decode(c.pretty)), c.canon, "corpus " .. i .. ": pretty parse")
end
-- 3. options and API
do
local v = Json.decode('[12345678901234567890, -9007199254740993, 9007199254740991, 1.5e300]', { bigInts = "string" })
t:eq(v[1], "12345678901234567890", "bigInts string")
t:eq(v[2], "-9007199254740993", "bigInts negative")
t:eq(v[3], 9007199254740991, "2^53 - 1 stays a number")
t:eq(v[4], 1.5e300, "floats stay numbers")
t:eq(Json.decode("[null]", { null = false })[1], false, "opts.null")
t:eq(Json.decode("null"), Types.null, "top-level null")
t:eq(Json.decode("\239\187\191[1]")[1], 1, "BOM skipped")
t:eq(Json.decode(buffer.fromstring(" 7 ")), 7, "buffer input")
local e = Json.decode('{"b":1,"a":{},"c":[]}')
t:eq(Json.encode(e), '{"a":{},"b":1,"c":[]}', "empty object stays an object")
local o = Json.decode('{"z":1,"a":2,"m":{"y":1,"b":2}}', { ordered = true })
t:eq(Json.encode(o), '{"z":1,"a":2,"m":{"y":1,"b":2}}', "ordered keys")
Types.set(o, "b", 3)
o.a = nil
t:eq(Json.encode(o), '{"z":1,"m":{"y":1,"b":2},"b":3}', "ordered set / remove")
t:eq(Json.encode({}, { emptyTable = "object" }), "{}", "emptyTable object")
t:eq(Json.encode({ [1] = "a", [3] = "c" }), '{"1":"a","3":"c"}', "sparse array -> object")
t:eq(Json.encode({ 1, 2, x = 1 }), '{"1":1,"2":2,"x":1}', "mixed table -> object")
t:eq(Json.encode("a/b", { escapeSlash = true }), '"a\\/b"', "escapeSlash")
t:eq(Json.encode(0 / 0, { nan = "null" }), "null", "nan null")
local _, ne = Json.encode(math.huge)
t:eq(ne and ne.code, Err.ARG, "inf is an error")
local cyc = {}
cyc.self = cyc
local _, ce = Json.encode(cyc)
t:eq(ce and ce.code, Err.ARG, "cycle is an error")
local _, fe = Json.encode({ f = print })
t:eq(fe and fe.code, Err.ARG, "function is an error")
t:eq(Json.encode(Types.Date.parse("1979-05-27T07:32:00Z")), '"1979-05-27T07:32:00Z"', "dates as strings")
for _, x in { 0.1, 1 / 3, -2.5e-8, 1e300, 123456789012345, 2 ^ 53, 5e-324, 1.7976931348623157e308 } do
t:eq(Json.decode(Json.encode(x) :: string), x, "number round trip " .. string.format("%.17g", x))
end
end
-- 4. streaming: lines, decodeAt, writer
do
local got = {}
for _, v in Json.lines('{"a":1}\n[2]\n"x"\n 3 ') do
table.insert(got, (Json.encode(v)))
end
t:eq(table.concat(got, "|"), '{"a":1}|[2]|"x"|3', "lines")
local n, last = 0, nil
for _, v, e in Json.lines("1 2 [") do
if e then
last = e
else
n += 1
end
end
t:eq(n, 2, "lines stop at the bad value")
t:eq(last and last.code, Err.TRUNCATED, "lines report the error")
local v, p = Json.decodeAt("[1] [2]", 1)
t:eq(v[1], 1, "decodeAt value")
t:eq(p, 4, "decodeAt next")
t:eq(Json.decodeAt(" ", 1), nil, "decodeAt at the end")
local w = Json.writer({ indent = 2 })
w:beginObject():key("a"):value({ 1, 2 }):key("b"):beginArray():value("x"):beginObject():endObject():endArray():endObject()
local s = w:tostring()
t:eq(s, Json.encode(Json.decode('{"a":[1,2],"b":["x",{}]}', { ordered = true }), { indent = 2 }), "writer pretty")
local w2 = Json.writer()
w2:beginArray()
local parts = {}
for i = 1, 5 do
w2:value(i)
table.insert(parts, w2:flush())
end
w2:endArray()
table.insert(parts, w2:flush())
t:eq(table.concat(parts), "[1,2,3,4,5]", "writer flush chunks")
t:eq(w2:tostring(), "[1,2,3,4,5]", "writer tostring after flushes")
local w3 = Json.writer()
w3:beginArray():key("x")
t:check(w3.err ~= nil, "writer: key in array")
local w4 = Json.writer()
w4:beginObject():value(1)
t:check(w4.err ~= nil, "writer: value without key")
local w5 = Json.writer()
w5:beginObject()
t:check(w5:tostring() == nil, "writer: unclosed")
end
-- 5. errors
local function code(s: string, opts: any?): string?
local _, e = Json.decode(s, opts)
return e and e.code
end
t:eq(code('{"a":'), Err.TRUNCATED, "truncated object")
t:eq(code('"abc'), Err.TRUNCATED, "truncated string")
t:eq(code("[1 2]"), Err.CORRUPT, "missing comma")
t:eq(code("[1] x"), Err.CORRUPT, "trailing data")
t:eq(code(string.rep("[", 50) .. string.rep("]", 50), { maxDepth = 10 }), Err.LIMIT, "maxDepth")
t:eq(code(string.rep("[", 100000)), Err.LIMIT, "100000 opening brackets")
t:eq(code(""), Err.TRUNCATED, "empty input")
local _, ae = Json.decode(42 :: any)
t:eq(ae and ae.code, Err.ARG, "bad argument")
do
local _, e = Json.decode('{"a": tru}')
t:eq(e and e.offset, 6, "error offset")
end
-- 6. fuzz
local samples = {}
for i = 1, 40 do
table.insert(samples, Corpus[i].compact)
end
for _, c in Suite do
if #samples < 120 and c.expect == "y" and #c.data < 200 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
return Json.decode(b)
end, samples)
t:fuzz("events", function(b: buffer)
for _ in Json.events(b) do
end
return nil
end, samples, { garbage = 50 })
t:done()
+86
View File
@@ -0,0 +1,86 @@
-- tests/data/Canon: the canonical text of a decoded data value, the same as tools/fixtures/_data_common.py canon() on
-- Python's parse: null n, true t, false f, numbers #%d (integral under 2^53) or #%.17g, strings s<len>:<bytes>,
-- buffers b<len>:<bytes>, arrays [x,...], objects {k=v,...} sorted by key text, dates d<rfc3339>. A module the data
-- tests require (running it alone does nothing).
local Types = require("@formats/Types")
local Canon = {}
local function num(x: number): string
if x ~= x then
return "#nan"
elseif x == math.huge then
return "#inf"
elseif x == -math.huge then
return "#-inf"
elseif x == math.floor(x) and math.abs(x) < 2 ^ 53 then
return string.format("#%d", x)
end
return "#" .. string.format("%.17g", x)
end
local function isArray(t: { [any]: any }): boolean
if Types.isObject(t) then
return false
end
local n = #t
local c = 0
for _ in next, t do
c += 1
end
return c == n
end
local function canon(v: any, out: { string })
local tv = type(v)
if v == Types.null then
table.insert(out, "n")
elseif tv == "boolean" then
table.insert(out, if v then "t" else "f")
elseif tv == "number" then
table.insert(out, num(v))
elseif tv == "string" then
table.insert(out, "s" .. #v .. ":" .. v)
elseif tv == "buffer" then
table.insert(out, "b" .. buffer.len(v) .. ":" .. buffer.tostring(v))
elseif tv == "table" and Types.Date.is(v) then
table.insert(out, "d" .. tostring(v))
elseif tv == "table" then
if isArray(v) then
table.insert(out, "[")
for i = 1, #v do
canon(v[i], out)
table.insert(out, ",")
end
table.insert(out, "]")
else
local items = {}
for k, x in next, v do
local ko = {}
canon(k, ko)
table.insert(items, { table.concat(ko), x })
end
table.sort(items, function(a, b)
return a[1] < b[1]
end)
table.insert(out, "{")
for _, it in items do
table.insert(out, it[1] .. "=")
canon(it[2], out)
table.insert(out, ",")
end
table.insert(out, "}")
end
else
table.insert(out, "?" .. tv)
end
end
-- of(v) -> the canonical text
function Canon.of(v: any): string
local out = {}
canon(v, out)
return table.concat(out)
end
return Canon