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

+279 -2
View File
@@ -343,12 +343,289 @@ export type Archive = {
-- ------------------------------------------------------------------------------------------------ Data
-- data formats decode to plain Luau values; JSON null / YAML ~ / CBOR null is this sentinel (nil cannot sit in a
-- table). XML decodes to XmlNode trees.
-- table). XML decodes to XmlNode trees. Byte strings (msgpack bin, CBOR bytes, plist data) are buffers.
local nullMeta = { __tostring = function()
return "null"
end }
Types.null = table.freeze(setmetatable({}, nullMeta))
export type XmlNode = { name: string, attrs: { [string]: string }, children: { XmlNode | string }, parent: XmlNode? }
-- Objects (maps) whose key order matters, and empty objects (which would otherwise read back as empty arrays), carry
-- an "object" metatable with their key order. Decoders mark empty objects always and every object when asked
-- (opts.ordered); encoders write an object's keys in that order (keys added later, or plain tables: sorted).
-- local o = Types.object() o.b = 1; o.a = 2 -- or Types.object({ a = 2, b = 1 }, { "b", "a" })
-- Types.set(o, "c", 3) -- assigns and appends "c" to the order
-- for _, k in Types.keys(o) do ... end
local OBJECT = { __object = true }
local objectMeta: { [any]: { any } } = setmetatable({}, { __mode = "k" }) :: any -- object -> its key order
-- object(t?, keys?) -> t marked as an object, keys = its key order (default: none recorded; Types.set appends)
function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any }
local o = t or {}
if getmetatable(o) == nil then
setmetatable(o, OBJECT)
end
objectMeta[o] = keys or {}
return o
end
-- isObject(v) -> true for tables made by Types.object
function Types.isObject(v: any): boolean
return type(v) == "table" and objectMeta[v] ~= nil
end
-- set(o, k, v): o[k] = v, appending k to o's key order when new (o must be an object; a plain table just assigns)
function Types.set(o: { [any]: any }, k: any, v: any)
local order = objectMeta[o]
if order and o[k] == nil and v ~= nil then
table.insert(order, k)
end
o[k] = v
end
local function keyLess(a: any, b: any): boolean
local ta, tb = type(a), type(b)
if ta ~= tb then
return ta < tb
end
if ta == "number" or ta == "string" then
return a < b
end
return tostring(a) < tostring(b)
end
-- keys(t) -> the keys in order: an object's recorded order (keys since removed are skipped), then any other keys
-- sorted (numbers before strings)
function Types.keys(t: { [any]: any }): { any }
local order = objectMeta[t]
local out, seen = {}, {}
if order then
for _, k in order do
if t[k] ~= nil and not seen[k] then
seen[k] = true
table.insert(out, k)
end
end
end
local rest = {}
for k in next, t do
if not seen[k] then
table.insert(rest, k)
end
end
if #rest > 0 then
table.sort(rest, keyLess)
table.move(rest, 1, #rest, #out + 1, out)
end
return out
end
-- Dates and times (TOML datetimes, plist <date>, CBOR tags 0 / 1, msgpack timestamps). Fields present depend on the
-- kind: "datetime" (with offset: an instant), "datetime-local", "date-local", "time-local". offset is in minutes
-- east of UTC (nil = local time). tostring gives RFC 3339 ("1979-05-27T07:32:00.5-07:00", "07:32:00", ...).
export type Date = {
kind: "datetime" | "datetime-local" | "date-local" | "time-local",
year: number?,
month: number?,
day: number?,
hour: number?,
minute: number?,
second: number?,
nanosecond: number?, -- 0 .. 999999999
offset: number?, -- minutes east of UTC
}
local DateMeta = {}
local function p2(n: number): string
return string.format("%02d", n)
end
local function fmtDate(d: any): string
local s = ""
if d.year then
s = string.format("%04d-%02d-%02d", d.year, d.month or 1, d.day or 1)
end
if d.hour then
if s ~= "" then
s ..= "T"
end
s ..= p2(d.hour) .. ":" .. p2(d.minute or 0) .. ":" .. p2(d.second or 0)
local ns = d.nanosecond or 0
if ns > 0 then
local f = string.format("%09d", ns)
s ..= "." .. (string.gsub(f, "0+$", ""))
end
if d.offset then
if d.offset == 0 then
s ..= "Z"
else
local o = math.abs(d.offset)
s ..= (if d.offset < 0 then "-" else "+") .. p2(o // 60) .. ":" .. p2(o % 60)
end
end
end
return s
end
DateMeta.__tostring = fmtDate
DateMeta.__eq = function(a: any, b: any): boolean
return fmtDate(a) == fmtDate(b) and a.kind == b.kind
end
local DateLib = {}
-- days since 1970-01-01 of a civil date (proleptic Gregorian; Howard Hinnant's algorithm)
local function daysFromCivil(y: number, m: number, d: number): number
y = if m <= 2 then y - 1 else y
local era = (if y >= 0 then y else y - 399) // 400
local yoe = y - era * 400
local mp = (m + 9) % 12
local doy = (153 * mp + 2) // 5 + d - 1
local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy
return era * 146097 + doe - 719468
end
local function civilFromDays(z: number): (number, number, number)
z += 719468
local era = (if z >= 0 then z else z - 146096) // 146097
local doe = z - era * 146097
local yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365
local y = yoe + era * 400
local doy = doe - (365 * yoe + yoe // 4 - yoe // 100)
local mp = (5 * doy + 2) // 153
local d = doy - (153 * mp + 2) // 5 + 1
local m = if mp < 10 then mp + 3 else mp - 9
return (if m <= 2 then y + 1 else y), m, d
end
local MDAYS = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
-- new(fields) -> Date (kind inferred from the fields present when not given)
function DateLib.new(f: { [string]: any }): Date
local d: any = {}
for k, v in f do
d[k] = v
end
if d.kind == nil then
d.kind = if d.year and d.hour then (if d.offset then "datetime" else "datetime-local")
elseif d.year then "date-local"
else "time-local"
end
return setmetatable(d, DateMeta) :: any
end
-- is(v) -> true for Dates
function DateLib.is(v: any): boolean
return type(v) == "table" and getmetatable(v) == DateMeta
end
-- valid(d) -> true when the fields are in range (month 1..12, the day exists in that month, hour < 24, ...)
function DateLib.valid(d: Date): boolean
if d.year then
local y, m, dd = d.year, d.month or 0, d.day or 0
if y < 0 or y > 9999 or m < 1 or m > 12 or dd < 1 or dd > MDAYS[m] then
return false
end
if m == 2 and dd == 29 and not (y % 4 == 0 and (y % 100 ~= 0 or y % 400 == 0)) then
return false
end
end
if d.hour then
if d.hour > 23 or (d.minute or 0) > 59 or (d.second or 0) > 60 then
return false
end
end
if d.offset and math.abs(d.offset) >= 24 * 60 then
return false
end
return true
end
-- parse(s) -> Date | nil: RFC 3339 / ISO 8601 date-times and their TOML partial forms ("1979-05-27",
-- "07:32:00.999", "1979-05-27 07:32:00Z", lower-case t / z accepted); out-of-range fields return nil
function DateLib.parse(s: string): Date?
local d: any = {}
local rest = s
local y, mo, dd, r1 = string.match(rest, "^(%d%d%d%d)%-(%d%d)%-(%d%d)(.*)$")
if y then
d.year, d.month, d.day = tonumber(y), tonumber(mo), tonumber(dd)
rest = r1
if rest == "" then
return if DateLib.valid(d) then DateLib.new(d) else nil
end
local sep = string.sub(rest, 1, 1)
if sep ~= "T" and sep ~= "t" and sep ~= " " then
return nil
end
rest = string.sub(rest, 2)
end
local h, mi, r2 = string.match(rest, "^(%d%d):(%d%d)(.*)$")
if not h then
return nil
end
d.hour, d.minute = tonumber(h), tonumber(mi)
rest = r2
local sec, r3 = string.match(rest, "^:(%d%d)(.*)$")
if not sec then
return nil
end
d.second = tonumber(sec)
rest = r3
local frac, r4 = string.match(rest, "^%.(%d+)(.*)$")
if frac then
d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9))
rest = r4
else
d.nanosecond = 0
end
if rest ~= "" then
if not d.year then
return nil
end
if rest == "Z" or rest == "z" then
d.offset = 0
else
local sign, oh, om = string.match(rest, "^([%+%-])(%d%d):(%d%d)$")
if not sign then
return nil
end
local oh_n, om_n = tonumber(oh) :: number, tonumber(om) :: number
if oh_n > 23 or om_n > 59 then
return nil
end
d.offset = (oh_n * 60 + om_n) * (if sign == "-" then -1 else 1)
end
end
return if DateLib.valid(d) then DateLib.new(d) else nil
end
-- toUnix(d) -> seconds since 1970-01-01T00:00:00Z (fractional; local times are taken as UTC)
function DateLib.toUnix(d: Date): number
local days = if d.year then daysFromCivil(d.year, d.month or 1, d.day or 1) else 0
local s = days * 86400 + (d.hour or 0) * 3600 + (d.minute or 0) * 60 + (d.second or 0) - (d.offset or 0) * 60
return s + (d.nanosecond or 0) / 1e9
end
-- fromUnix(seconds, offset?) -> a "datetime" Date (offset in minutes, default 0 = UTC)
function DateLib.fromUnix(t: number, offset: number?): Date
local off = offset or 0
local whole = math.floor(t)
local ns = math.floor((t - whole) * 1e9 + 0.5)
if ns >= 1e9 then
whole += 1
ns -= 1e9
end
local lt = whole + off * 60
local days = lt // 86400
local secs = lt - days * 86400
local y, m, dd = civilFromDays(days)
return DateLib.new({
kind = "datetime",
year = y,
month = m,
day = dd,
hour = secs // 3600,
minute = (secs // 60) % 60,
second = secs % 60,
nanosecond = ns,
offset = off,
})
end
Types.Date = table.freeze(DateLib)
-- XML: an element, or (name starting with "#") a "#document" / "#comment" / "#cdata" / "#pi" / "#doctype" node with
-- its content in text. attrs is a Types.object (attribute order kept). Text children are plain strings.
export type XmlNode = {
name: string,
attrs: { [string]: string },
children: { XmlNode | string },
parent: XmlNode?,
text: string?, -- "#comment" / "#cdata" / "#pi" (the data after the target) / "#doctype" content
target: string?, -- "#pi": the target
ns: string?, -- the namespace URI (opts.namespaces)
[string]: any,
}
-- ------------------------------------------------------------------------------------------------ Vector
export type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any }
+433
View File
@@ -0,0 +1,433 @@
--!strict
--!native
-- codecs/Json/Decode: the RFC 8259 parser behind codecs/Json. Iterative (an explicit container stack, so deep nesting
-- is a LIMIT error, never a stack overflow), strict grammar (no comments, trailing commas, leading zeros, NaN, single
-- quotes or raw control characters), \u escapes with surrogate pairs (lone surrogates become WTF-8 bytes). Also the
-- pull tokenizer behind Json.events. Never throws: failures return nil, message, offset (0-based byte offset).
local Types = require("@formats/Types")
local Decode = {}
local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char
local tonumber = tonumber
local concat = table.concat
export type Options = {
ordered: boolean?, -- every object is a Types.object with its key order (default false: only empty objects are)
bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their exact text (default "number")
null: any?, -- the value for null (default Types.null)
maxDepth: number?, -- nesting limit (default 1000)
}
local ESC: { [number]: string } = {
[34] = '"',
[92] = "\\",
[47] = "/",
[98] = "\b",
[102] = "\f",
[110] = "\n",
[114] = "\r",
[116] = "\t",
}
-- utf8 bytes of a code point (surrogates too: WTF-8)
local function utf8char(c: number): string
if c < 0x80 then
return char(c)
elseif c < 0x800 then
return char(0xC0 + c // 64, 0x80 + c % 64)
elseif c < 0x10000 then
return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64)
end
return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64)
end
Decode.utf8char = utf8char
local function hex4(s: string, i: number): number?
local h = match(s, "^%x%x%x%x", i)
if not h then
return nil
end
return tonumber(h, 16)
end
-- string(s, i) -> value, next | nil, message, offset. i is at the opening quote.
local function str(s: string, i: number): (string?, any, number?)
local j = find(s, '[%z\1-\31"\\]', i + 1)
if not j then
return nil, "unterminated string", #s
end
local c = byte(s, j)
if c == 34 then
return sub(s, i + 1, j - 1), j + 1
end
local parts = {}
local np = 0
local start = i + 1
while true do
if c == 34 then
np += 1
parts[np] = sub(s, start, j - 1)
return concat(parts), j + 1
elseif c ~= 92 then
return nil, "control character in string", j - 1
end
np += 1
parts[np] = sub(s, start, j - 1)
local e = byte(s, j + 1)
if e == nil then
return nil, "unterminated string", #s
end
local simple = ESC[e]
if simple then
np += 1
parts[np] = simple
start = j + 2
elseif e == 117 then -- \u
local cp = hex4(s, j + 2)
if not cp then
return nil, "bad \\u escape", j - 1
end
start = j + 6
if cp >= 0xD800 and cp <= 0xDBFF and byte(s, start) == 92 and byte(s, start + 1) == 117 then
local lo = hex4(s, start + 2)
if lo and lo >= 0xDC00 and lo <= 0xDFFF then
cp = 0x10000 + (cp - 0xD800) * 1024 + (lo - 0xDC00)
start += 6
end
end
np += 1
parts[np] = utf8char(cp)
else
return nil, "bad escape", j - 1
end
j = find(s, '[%z\1-\31"\\]', start)
if not j then
return nil, "unterminated string", #s
end
c = byte(s, j)
end
end
Decode.string = str
-- number(s, i) -> value, next | nil, message, offset
local function num(s: string, i: number, bigStrings: boolean): (any, any, number?)
local p = i
if byte(s, p) == 45 then
p += 1
end
local c = byte(s, p)
if c == 48 then
p += 1
elseif c and c >= 49 and c <= 57 then
p = match(s, "^%d*()", p + 1) :: any
else
return nil, if c == nil then "truncated: expected a value" elseif p == i then "unexpected character" else "bad number", p - 1
end
local int = true
if byte(s, p) == 46 then
local q = match(s, "^%d+()", p + 1)
if not q then
return nil, "bad fraction", p
end
p = q :: any
int = false
end
c = byte(s, p)
if c == 101 or c == 69 then
p += 1
c = byte(s, p)
if c == 43 or c == 45 then
p += 1
end
local q = match(s, "^%d+()", p)
if not q then
return nil, "bad exponent", p - 1
end
p = q :: any
int = false
end
local text = sub(s, i, p - 1)
local n = tonumber(text) :: number
if n == nil then -- LuaJIT: absurd exponents (1e0066999...) -> nil; they overflow / underflow
local m, es = match(text, "^([^eE]*)[eE]([%+%-]?)")
local mv = tonumber(m) or 0
n = if mv == 0 then mv elseif es == "-" then mv * 0 else mv * math.huge
end
if int and bigStrings and p - i > 15 and (n >= 9007199254740992 or n <= -9007199254740992) then
return text, p
end
return n, p
end
Decode.number = num
-- decode(s, i, opts) -> value, next | nil, message, offset. Parses one value starting at i (leading whitespace
-- skipped); next is the position after the value (trailing whitespace not skipped).
function Decode.value(s: string, i: number, opts: Options?): (any, any, number?)
local o: Options = opts or {}
local ordered = o.ordered == true
local bigStrings = o.bigInts == "string"
local nullv = if o.null ~= nil then o.null else Types.null
local maxDepth = o.maxDepth or 1000
local object = Types.object
local stackT: { any } = {} -- containers
local stackK: { any } = {} -- object: the pending key; array: the count
local stackO: { any } = {} -- object: its key order (or true); array: false
local depth = 0
local n = #s
local value: any
while true do
i = match(s, "^[ \t\n\r]*()", i) :: any
local c = byte(s, i)
local haveValue = true
if c == 123 then -- {
depth += 1
if depth > maxDepth then
return nil, "nested deeper than " .. maxDepth, i - 1
end
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
local t = {}
c = byte(s, i)
if c == 125 then
i += 1
depth -= 1
value = object(t, {})
elseif c == 34 then
local k, ni, at = str(s, i)
if k == nil then
return nil, ni, at
end
i = match(s, "^[ \t\n\r]*()", ni) :: any
if byte(s, i) ~= 58 then
return nil, if i > n then "truncated object" else "expected ':'", i - 1
end
i += 1
stackT[depth], stackK[depth] = t, k
stackO[depth] = if ordered then {} else true
haveValue = false
else
return nil, if c == nil then "truncated object" else "expected a key", i - 1
end
elseif c == 91 then -- [
depth += 1
if depth > maxDepth then
return nil, "nested deeper than " .. maxDepth, i - 1
end
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
if byte(s, i) == 93 then
i += 1
depth -= 1
value = {}
else
stackT[depth], stackK[depth], stackO[depth] = {}, 0, false
haveValue = false
end
elseif c == 34 then
local v, ni, at = str(s, i)
if v == nil then
return nil, ni, at
end
value, i = v, ni
elseif c == 116 then
if sub(s, i, i + 3) ~= "true" then
return nil, "bad literal", i - 1
end
value, i = true, i + 4
elseif c == 102 then
if sub(s, i, i + 4) ~= "false" then
return nil, "bad literal", i - 1
end
value, i = false, i + 5
elseif c == 110 then
if sub(s, i, i + 3) ~= "null" then
return nil, "bad literal", i - 1
end
value, i = nullv, i + 4
elseif c == nil then
return nil, "truncated: expected a value", n
else
local v, ni, at = num(s, i, bigStrings)
if v == nil then
return nil, ni, at
end
value, i = v, ni
end
-- attach the value to the open containers, closing them as their ends come
while haveValue do
if depth == 0 then
return value, i
end
local t = stackT[depth]
local ord = stackO[depth]
if ord then
local k = stackK[depth]
if ord ~= true and t[k] == nil then
table.insert(ord, k)
end
t[k] = value
else
local cnt = stackK[depth] + 1
t[cnt] = value
stackK[depth] = cnt
end
i = match(s, "^[ \t\n\r]*()", i) :: any
c = byte(s, i)
if c == 44 then -- ,
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
if ord then
if byte(s, i) ~= 34 then
return nil, if i > n then "truncated object" else "expected a key", i - 1
end
local k, ni, at = str(s, i)
if k == nil then
return nil, ni, at
end
i = match(s, "^[ \t\n\r]*()", ni) :: any
if byte(s, i) ~= 58 then
return nil, if i > n then "truncated object" else "expected ':'", i - 1
end
i += 1
stackK[depth] = k
end
haveValue = false
elseif ord and c == 125 then
i += 1
value = if ord ~= true then object(t, ord) elseif next(t) == nil then object(t, {}) else t
stackT[depth] = nil
depth -= 1
elseif not ord and c == 93 then
i += 1
value = t
stackT[depth] = nil
depth -= 1
elseif c == nil then
return nil, if ord then "truncated object" else "truncated array", n
else
return nil, if ord then "expected ',' or '}'" else "expected ',' or ']'", i - 1
end
end
end
end
-- events: a pull tokenizer. next() -> event, value | nil at the end | "error", message, offset. Events: "object",
-- "endObject", "array", "endArray", "key" (string), "value" (scalar). The grammar is checked as it goes.
function Decode.events(s: string, i: number, opts: Options?): () -> (string?, any, number?)
local o: Options = opts or {}
local bigStrings = o.bigInts == "string"
local nullv = if o.null ~= nil then o.null else Types.null
local maxDepth = o.maxDepth or 1000
local stack: { boolean } = {} -- true = object
local depth = 0
-- state: "value" (a value expected), "first" (after { or [: value / key or close), "after" (after a value),
-- "key" (a key expected), "done", "dead"
local state = "value"
local n = #s
local function fail(msg: string, at: number): (string, any, number)
state = "dead"
return "error", msg, at
end
return function(): (string?, any, number?)
if state == "dead" then
return nil
end
i = match(s, "^[ \t\n\r]*()", i) :: any
local c = byte(s, i)
if state == "done" then
state = "dead"
if c ~= nil then
return "error", "trailing data", i - 1
end
return nil
end
if state == "after" then
local obj = stack[depth]
if c == 44 then
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
c = byte(s, i)
state = if obj then "key" else "value"
elseif c == (if obj then 125 else 93) then
i += 1
stack[depth] = nil
depth -= 1
state = if depth == 0 then "done" else "after"
return if obj then "endObject" else "endArray", nil
elseif c == nil then
return fail("truncated", n)
else
return fail("expected ',' or a close", i - 1)
end
end
if state == "first" then
local obj = stack[depth]
if c == (if obj then 125 else 93) then
i += 1
stack[depth] = nil
depth -= 1
state = if depth == 0 then "done" else "after"
return if obj then "endObject" else "endArray", nil
end
state = if obj then "key" else "value"
end
if state == "key" then
if c ~= 34 then
return fail(if c == nil then "truncated" else "expected a key", i - 1)
end
local k, ni, at = str(s, i)
if k == nil then
return fail(ni, at :: number)
end
i = match(s, "^[ \t\n\r]*()", ni) :: any
if byte(s, i) ~= 58 then
return fail("expected ':'", i - 1)
end
i += 1
state = "value"
return "key", k
end
-- a value
local after = if depth == 0 then "done" else "after"
if c == 123 or c == 91 then
depth += 1
if depth > maxDepth then
return fail("nested deeper than " .. maxDepth, i - 1)
end
stack[depth] = c == 123
i += 1
state = "first"
return if c == 123 then "object" else "array", nil
elseif c == 34 then
local v, ni, at = str(s, i)
if v == nil then
return fail(ni, at :: number)
end
i = ni
state = after
return "value", v
elseif c == 116 and sub(s, i, i + 3) == "true" then
i += 4
state = after
return "value", true
elseif c == 102 and sub(s, i, i + 4) == "false" then
i += 5
state = after
return "value", false
elseif c == 110 and sub(s, i, i + 3) == "null" then
i += 4
state = after
return "value", nullv
elseif c == nil then
return fail("truncated: expected a value", n)
end
local v, ni, at = num(s, i, bigStrings)
if v == nil then
return fail(ni, at :: number)
end
i = ni
state = after
return "value", v
end
end
return Decode
+310
View File
@@ -0,0 +1,310 @@
--!strict
--!native
-- codecs/Json/Encode: the serializer behind codecs/Json. Compact or pretty (indent), objects in their Types.object key
-- order (plain tables: sorted keys), arrays for tables with keys 1..n, shortest round-trip number text, optional
-- ASCII-only output. Never throws: bad values (cycles, NaN / inf, functions, non-string keys that are not numbers)
-- return nil, message.
local Types = require("@formats/Types")
local Encode = {}
local byte, format, gsub = string.byte, string.format, string.gsub
local floor, huge = math.floor, math.huge
local concat = table.concat
export type Options = {
indent: (number | string)?, -- pretty print: spaces per level (or the indent string); default compact
sortKeys: boolean?, -- plain tables' keys sorted (default true; false = next() order, faster)
ascii: boolean?, -- escape every non-ASCII character as \uXXXX (default false: UTF-8 as is)
nan: ("error" | "null")?, -- NaN / inf: an error (default) or null
emptyTable: ("array" | "object")?, -- what a plain empty table is (default "array"; Types.object() is "{}")
maxDepth: number?, -- nesting limit (default 1000; also catches cycles)
escapeSlash: boolean?, -- write / as \/ (default false)
}
local ESCAPES: { [string]: string } = {
['"'] = '\\"',
["\\"] = "\\\\",
["\b"] = "\\b",
["\f"] = "\\f",
["\n"] = "\\n",
["\r"] = "\\r",
["\t"] = "\\t",
["/"] = "\\/",
}
for c = 0, 31 do
local ch = string.char(c)
if not ESCAPES[ch] then
ESCAPES[ch] = format("\\u%04x", c)
end
end
local function utf16(cp: number): string
if cp < 0x10000 then
return format("\\u%04x", cp)
end
cp -= 0x10000
return format("\\u%04x\\u%04x", 0xD800 + cp // 1024, 0xDC00 + cp % 1024)
end
-- asciify a UTF-8 string's non-ASCII sequences (invalid bytes become \u00XX of the byte: lossy but never throws)
local function asciiSeq(seq: string): string
local out = {}
local i, n = 1, #seq
while i <= n do
local c = byte(seq, i)
local cp, len
if c < 0xC0 then
cp, len = c, 1
elseif c < 0xE0 then
cp, len = (c % 32) * 64 + (byte(seq, i + 1) or 128) % 64, 2
elseif c < 0xF0 then
cp, len = (c % 16) * 4096 + ((byte(seq, i + 1) or 128) % 64) * 64 + (byte(seq, i + 2) or 128) % 64, 3
else
cp, len = (c % 8) * 262144 + ((byte(seq, i + 1) or 128) % 64) * 4096 + ((byte(seq, i + 2) or 128) % 64) * 64 + (byte(seq, i + 3) or 128) % 64, 4
end
table.insert(out, utf16(cp))
i += len
end
return concat(out)
end
-- string(s, ascii, slash) -> the quoted JSON string (ascii: DEL too, like Python's ensure_ascii)
local function quote(s: string, ascii: boolean?, slash: boolean?): string
local pat = if slash then '[%z\1-\31"\\/]' else '[%z\1-\31"\\]'
if string.find(s, pat) then
s = gsub(s, pat, ESCAPES)
end
if ascii and string.find(s, "[\127-\255]") then
s = gsub(s, "\127", "\\u007f")
s = gsub(s, "[\192-\255][\128-\191]*", asciiSeq)
s = gsub(s, "[\128-\191]", asciiSeq)
end
return '"' .. s .. '"'
end
Encode.quote = quote
local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" }
-- number(x) -> the shortest text that reads back as x | nil for NaN / inf
local function number(x: number): string?
if x ~= x or x == huge or x == -huge then
return nil
end
if x == floor(x) and x > -1e15 and x < 1e15 then
if x == 0 and 1 / x < 0 then
return "-0"
end
return format("%d", x)
end
for _, f in FLOAT_FORMATS do
local t = format(f, x)
if tonumber(t) == x then
return t
end
end
return format("%.17g", x)
end
Encode.number = number
local function keyLess(a: any, b: any): boolean
local ta, tb = type(a), type(b)
if ta ~= tb then
return ta == "number"
end
return a < b
end
-- kind(t, emptyObject) -> "array" (keys exactly 1..n) | "object"
local function kind(t: { [any]: any }, emptyObject: boolean): string
if Types.isObject(t) then
return "object"
end
local n = #t
if n == 0 then
if next(t) == nil then
return if emptyObject then "object" else "array"
end
return "object"
end
if next(t, n) ~= nil then
return "object"
end
local count = 0
for _ in next, t do
count += 1
end
return if count == n then "array" else "object"
end
Encode.kind = kind
type State = {
out: { string },
n: number,
indent: string?,
sort: boolean,
ascii: boolean,
slash: boolean,
nanNull: boolean,
emptyObject: boolean,
maxDepth: number,
null: any,
err: string?,
}
local function put(st: State, s: string)
local n = st.n + 1
st.out[n] = s
st.n = n
end
local function value(st: State, v: any, depth: number): boolean
local tv = type(v)
if tv == "string" then
put(st, quote(v, st.ascii, st.slash))
elseif tv == "number" then
local s = number(v)
if not s then
if not st.nanNull then
st.err = "cannot encode " .. tostring(v)
return false
end
s = "null"
end
put(st, s)
elseif tv == "boolean" then
put(st, if v then "true" else "false")
elseif v == nil or v == st.null or v == Types.null then
put(st, "null")
elseif tv == "table" then
if Types.Date.is(v) then
put(st, '"' .. tostring(v) .. '"')
return true
end
if depth >= st.maxDepth then
st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)"
return false
end
local ind = st.indent
local nl, nl2 = "", ""
if ind then
nl = "\n" .. string.rep(ind, depth + 1)
nl2 = "\n" .. string.rep(ind, depth)
end
if kind(v, st.emptyObject) == "array" then
local n = #v
if n == 0 then
put(st, "[]")
return true
end
put(st, "[")
for i = 1, n do
if i > 1 then
put(st, ",")
end
if ind then
put(st, nl)
end
if not value(st, v[i], depth + 1) then
return false
end
end
if ind then
put(st, nl2)
end
put(st, "]")
else
local keys: { any }
if Types.isObject(v) then
keys = Types.keys(v)
else
keys = {}
for k in next, v do
local tk = type(k)
if tk ~= "string" and tk ~= "number" then
st.err = "object key of type " .. tk
return false
end
table.insert(keys, k)
end
if st.sort then
table.sort(keys, keyLess)
end
end
if #keys == 0 then
put(st, "{}")
return true
end
put(st, "{")
local sep = if ind then ": " else ":"
for i, k in keys do
if i > 1 then
put(st, ",")
end
if ind then
put(st, nl)
end
local ks: string
if type(k) == "string" then
ks = k
elseif type(k) == "number" then
ks = number(k) or tostring(k)
else
st.err = "object key of type " .. type(k)
return false
end
put(st, quote(ks, st.ascii, st.slash))
put(st, sep)
if not value(st, v[k], depth + 1) then
return false
end
end
if ind then
put(st, nl2)
end
put(st, "}")
end
elseif tv == "buffer" then
st.err = "cannot encode a buffer (encode it as base64 or an array first)"
return false
else
st.err = "cannot encode a " .. tv
return false
end
return true
end
local function state(opts: Options?, nullv: any?): State
local o: Options = opts or {}
local ind: string? = nil
if type(o.indent) == "number" then
ind = if o.indent > 0 then string.rep(" ", o.indent) else nil
elseif type(o.indent) == "string" then
ind = o.indent
end
return {
out = {},
n = 0,
indent = ind,
sort = o.sortKeys ~= false,
ascii = o.ascii == true,
slash = o.escapeSlash == true,
nanNull = o.nan == "null",
emptyObject = o.emptyTable == "object",
maxDepth = o.maxDepth or 1000,
null = nullv,
err = nil,
}
end
Encode.state = state
Encode.write = value
-- encode(v, opts) -> text | nil, message
function Encode.encode(v: any, opts: Options?, nullv: any?): (string?, string?)
local st = state(opts, nullv)
if not value(st, v, 0) then
return nil, st.err
end
return concat(st.out), nil
end
return Encode
+294
View File
@@ -0,0 +1,294 @@
--!strict
-- codecs/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/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/Json/Decode")
local Encode = require("@formats/codecs/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
+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
+15
View File
@@ -56,3 +56,18 @@ do
Png.encode(img)
end)
end
do
local Json = require("@formats/codecs/Json")
local JB = require("@tests/gen/json_bench")
local v = assert(Json.decode(JB.text))
assert(Json.encode(v) == JB.compact, "json bench mismatch")
bench("json decode (indented)", 5, #JB.text, function()
Json.decode(JB.text)
end)
bench("json decode (compact)", 5, #JB.compact, function()
Json.decode(JB.compact)
end)
bench("json encode (compact, sorted)", 5, #JB.compact, function()
Json.encode(v)
end)
end
+1 -1
View File
@@ -3,7 +3,7 @@
cd "$(dirname "$0")/.." || exit 1
LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')}
LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')}
python3 -I tools/fixtures.py deflate png > /dev/null || exit 1
python3 -I tools/fixtures.py deflate png json > /dev/null || exit 1
python3 -I tools/build.py luajit > /dev/null || exit 1
"$LUAU" --codegen -O2 tools/bench.luau
"$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua
+99
View File
@@ -0,0 +1,99 @@
# Shared helpers for the data-format fixture generators (json, xml, csv, toml, yaml, msgpack, cbor, plist, ...):
# fetch(url, sha256) -> a nix store path of an unpacked tarball (official test suites, pinned by hash)
# canon(value) -> the canonical text a Luau test computes too (tests/data/_canon.luau): typed, sorted keys,
# numbers as %.17g, so Python's parse and ours compare exactly.
import os, subprocess, datetime
def fetch(url, sha256):
expr = 'builtins.fetchTarball { url = "%s"; sha256 = "%s"; }' % (url, sha256)
out = subprocess.run(["nix", "eval", "--raw", "--impure", "--expr", expr], capture_output=True, check=True)
return out.stdout.decode()
def _b(s):
if isinstance(s, str):
return s.encode("utf-8", "surrogatepass")
return bytes(s)
def canon(v):
"""null n; true t; false f; number #%d (integral, under 2^53) or #%.17g; string s<len>:<bytes>;
bytes b<len>:<bytes>; list [..]; dict {k v ...} with keys sorted by their canon bytes; dates d<rfc3339>"""
out = bytearray()
_canon(v, out)
return bytes(out)
def num(x):
x = float(x)
if x != x:
return b"#nan"
if x in (float("inf"), float("-inf")):
return b"#inf" if x > 0 else b"#-inf"
if x == int(x) and abs(x) < 2 ** 53:
return b"#%d" % int(x)
return b"#" + ("%.17g" % x).encode()
def _canon(v, out):
if v is None:
out += b"n"
elif v is True:
out += b"t"
elif v is False:
out += b"f"
elif isinstance(v, (int, float)):
out += num(v)
elif isinstance(v, str):
b = _b(v)
out += b"s%d:" % len(b) + b
elif isinstance(v, (bytes, bytearray)):
out += b"b%d:" % len(v) + bytes(v)
elif isinstance(v, (list, tuple)):
out += b"["
for x in v:
_canon(x, out)
out += b","
out += b"]"
elif isinstance(v, dict):
items = []
for k, x in v.items():
kb = bytearray()
_canon(k, kb)
items.append((bytes(kb), x))
items.sort(key=lambda p: p[0])
out += b"{"
for kb, x in items:
out += kb + b"="
_canon(x, out)
out += b","
out += b"}"
elif isinstance(v, (datetime.datetime, datetime.date, datetime.time)):
out += b"d" + date_text(v).encode()
else:
raise TypeError("canon: %r" % type(v))
def date_text(v):
"""RFC 3339 the way Types.Date prints: fraction without trailing zeros, Z for +00:00"""
def frac(us):
return ("." + ("%06d" % us).rstrip("0")) if us else ""
def tz(t):
off = t.utcoffset()
if off is None:
return ""
m = int(off.total_seconds()) // 60
if m == 0:
return "Z"
sign = "-" if m < 0 else "+"
m = abs(m)
return "%s%02d:%02d" % (sign, m // 60, m % 60)
if isinstance(v, datetime.datetime):
return "%04d-%02d-%02dT%02d:%02d:%02d%s%s" % (v.year, v.month, v.day, v.hour, v.minute, v.second,
frac(v.microsecond), tz(v))
if isinstance(v, datetime.date):
return "%04d-%02d-%02d" % (v.year, v.month, v.day)
return "%02d:%02d:%02d%s" % (v.hour, v.minute, v.second, frac(v.microsecond))
+91
View File
@@ -0,0 +1,91 @@
# codecs/Json + data/json fixtures: the JSONTestSuite parsing corpus (nst/JSONTestSuite, pinned tarball through nix)
# with Python's json verdicts and canonical values, plus a random corpus written by Python's json.dumps in several
# styles (compact sorted, insertion order, indent 2, ensure_ascii) that the tests must parse and reproduce exactly.
# tests/gen/json_suite.luau { { name, expect = "y" | "n" | "i", data, canon? } }
# tests/gen/json_corpus.luau { { canon, compact, ordered, pretty, ascii } }
# tests/gen/json_bench.luau { text, compact } (~1 MB, indent 1; compact = sorted keys)
import importlib.util, json, os
_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py"))
C = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(C)
SUITE_URL = "https://github.com/nst/JSONTestSuite/archive/1ef36fa01286573e846ac449e8683f8833c5b26a.tar.gz"
SUITE_SHA = "0zp4gbpfxac9hfzlgjmqg70w8dhql6rbrkh8dhi3rn5aan0qqv5k"
def rand_value(rng, depth=0):
v = _rand_value(rng, depth)
if isinstance(v, float) and v.is_integer():
return int(v) # Python writes 1.0, we write 1: keep integral numbers ints
return v
def _rand_value(rng, depth=0):
r = rng.random()
if depth > 4 or r < 0.45:
k = rng.randrange(9)
if k == 0:
return None
if k == 1:
return rng.random() < 0.5
if k == 2:
return rng.randrange(-10 ** 15, 10 ** 15)
if k == 3:
return rng.randrange(-1000, 1000)
if k == 4:
return round(rng.uniform(-1e6, 1e6), rng.randrange(1, 8))
if k == 5:
return rng.uniform(-1, 1) * 10 ** rng.randrange(-4, 14)
return rand_str(rng)
if r < 0.72:
return [rand_value(rng, depth + 1) for _ in range(rng.randrange(0, 7))]
d = {}
for _ in range(rng.randrange(0, 7)):
d[rand_str(rng)] = rand_value(rng, depth + 1)
return d
ALPH = "abcxyz ABC_019\"\\/\n\t\r\b\f\x01\x1f\x7féü中文\U0001f600
"
def rand_str(rng):
return "".join(rng.choice(ALPH) for _ in range(rng.randrange(0, 12)))
def generate(ctx):
root = C.fetch(SUITE_URL, SUITE_SHA)
d = os.path.join(root, "test_parsing")
cases = []
for name in sorted(os.listdir(d)):
if not name.endswith(".json"):
continue
data = open(os.path.join(d, name), "rb").read()
c = {"name": name, "expect": name[0], "data": data}
try:
v = json.loads(data.decode("utf-8", "surrogatepass"))
c["canon"] = C.canon(v)
except Exception:
pass
cases.append(c)
ctx.emit("json_suite", cases)
rng = ctx.rng(7)
corpus = []
for _ in range(300):
v = rand_value(rng)
corpus.append({
"canon": C.canon(v),
"compact": json.dumps(v, separators=(",", ":"), sort_keys=True, ensure_ascii=False),
"ordered": json.dumps(v, separators=(",", ":"), ensure_ascii=False),
"pretty": json.dumps(v, indent=2, sort_keys=True, ensure_ascii=False),
"ascii": json.dumps(v, separators=(",", ":"), sort_keys=True),
})
ctx.emit("json_corpus", corpus)
big = [rand_value(rng) for _ in range(3000)]
text = json.dumps(big, ensure_ascii=False, indent=1)
while len(text) < 1_000_000:
big = big + big
text = json.dumps(big, ensure_ascii=False, indent=1)
ctx.emit("json_bench", {"text": text, "compact": json.dumps(big, separators=(",", ":"), sort_keys=True, ensure_ascii=False)})