From b6f40e0a74d78de10a8d1c932060abd6667fbc56 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:30:05 -0500 Subject: [PATCH 1/3] 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. Co-Authored-By: Claude Opus 5.5 --- src/Formats/Types.luau | 281 +++++++++++++++++- src/Formats/codecs/Json/Decode.luau | 433 ++++++++++++++++++++++++++++ src/Formats/codecs/Json/Encode.luau | 310 ++++++++++++++++++++ src/Formats/codecs/Json/init.luau | 294 +++++++++++++++++++ tests/codecs/json.luau | 210 ++++++++++++++ tests/data/Canon.luau | 86 ++++++ tools/bench.luau | 15 + tools/bench.sh | 2 +- tools/fixtures/_data_common.py | 99 +++++++ tools/fixtures/json.py | 91 ++++++ 10 files changed, 1818 insertions(+), 3 deletions(-) create mode 100644 src/Formats/codecs/Json/Decode.luau create mode 100644 src/Formats/codecs/Json/Encode.luau create mode 100644 src/Formats/codecs/Json/init.luau create mode 100644 tests/codecs/json.luau create mode 100644 tests/data/Canon.luau create mode 100644 tools/fixtures/_data_common.py create mode 100644 tools/fixtures/json.py diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 9f37bd1..1d8db5c 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -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 , 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 } diff --git a/src/Formats/codecs/Json/Decode.luau b/src/Formats/codecs/Json/Decode.luau new file mode 100644 index 0000000..46b9fd2 --- /dev/null +++ b/src/Formats/codecs/Json/Decode.luau @@ -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 diff --git a/src/Formats/codecs/Json/Encode.luau b/src/Formats/codecs/Json/Encode.luau new file mode 100644 index 0000000..cf556f8 --- /dev/null +++ b/src/Formats/codecs/Json/Encode.luau @@ -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 diff --git a/src/Formats/codecs/Json/init.luau b/src/Formats/codecs/Json/init.luau new file mode 100644 index 0000000..f9b6204 --- /dev/null +++ b/src/Formats/codecs/Json/init.luau @@ -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 diff --git a/tests/codecs/json.luau b/tests/codecs/json.luau new file mode 100644 index 0000000..dacb399 --- /dev/null +++ b/tests/codecs/json.luau @@ -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() diff --git a/tests/data/Canon.luau b/tests/data/Canon.luau new file mode 100644 index 0000000..9291fb2 --- /dev/null +++ b/tests/data/Canon.luau @@ -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:, +-- buffers b:, arrays [x,...], objects {k=v,...} sorted by key text, dates d. 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 diff --git a/tools/bench.luau b/tools/bench.luau index 9f6aef7..5815060 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -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 diff --git a/tools/bench.sh b/tools/bench.sh index c5dea4a..f77a3fa 100644 --- a/tools/bench.sh +++ b/tools/bench.sh @@ -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 diff --git a/tools/fixtures/_data_common.py b/tools/fixtures/_data_common.py new file mode 100644 index 0000000..41b4291 --- /dev/null +++ b/tools/fixtures/_data_common.py @@ -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:; + bytes b:; list [..]; dict {k v ...} with keys sorted by their canon bytes; dates d""" + 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)) diff --git a/tools/fixtures/json.py b/tools/fixtures/json.py new file mode 100644 index 0000000..52776b6 --- /dev/null +++ b/tools/fixtures/json.py @@ -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)}) From 2557d3b1fe1b30e0a8d2455de475e9a8d57672b8 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:30:11 -0500 Subject: [PATCH 2/3] data: regenerate docs/FORMATS.md (codecs/Json) Co-Authored-By: Claude Opus 5.5 --- docs/FORMATS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 181230b..2d2736b 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -10,3 +10,4 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. +- codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. From 907f3650f127c9bde95c4361a324897e72aa71ba Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:38:55 -0500 Subject: [PATCH 3/3] data: codecs/Xml (XML 1.0 DOM + pull events + serializer: UTF-8/16/Latin-1, entities incl. internal DOCTYPE with expansion limit, CDATA, comments, PIs, namespaces as qualified names + node.ns / clark, xml:space); ElementTree + expat fixtures; bench lines Co-Authored-By: Claude Opus 5.5 --- docs/FORMATS.md | 1 + src/Formats/codecs/Xml/Parse.luau | 771 ++++++++++++++++++++++++++++++ src/Formats/codecs/Xml/init.luau | 440 +++++++++++++++++ tests/codecs/xml.luau | 197 ++++++++ tools/bench.luau | 15 + tools/bench.sh | 2 +- tools/fixtures/xml.py | 174 +++++++ 7 files changed, 1599 insertions(+), 1 deletion(-) create mode 100644 src/Formats/codecs/Xml/Parse.luau create mode 100644 src/Formats/codecs/Xml/init.luau create mode 100644 tests/codecs/xml.luau create mode 100644 tools/fixtures/xml.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 2d2736b..5da5c20 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -11,3 +11,4 @@ Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. - codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. +- codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... diff --git a/src/Formats/codecs/Xml/Parse.luau b/src/Formats/codecs/Xml/Parse.luau new file mode 100644 index 0000000..4a04ff3 --- /dev/null +++ b/src/Formats/codecs/Xml/Parse.luau @@ -0,0 +1,771 @@ +--!strict +--!native +-- codecs/Xml/Parse: the XML 1.0 pull parser behind codecs/Xml. Input decoding (UTF-8, UTF-16 LE / BE by BOM or +-- by the first bytes, ISO-8859-1 / US-ASCII / Windows-1252 by the declaration), line-ending normalization, the +-- well-formedness rules that matter (one root, matched tags, unique attributes, quoted values, no '<' in values, +-- legal names, character references in range, no "--" in comments, no "]]>" in text), the five predefined entities, +-- character references and internal general entities from the DOCTYPE (with an expansion limit). Not supported: +-- external entities / DTDs (references to them are errors), entity values containing markup (taken as text), +-- validation. Never throws: errors are events. +local Types = require("@formats/Types") + +local Parse = {} + +local byte, sub, find, match, char, gsub, lower = string.byte, string.sub, string.find, string.match, string.char, string.gsub, string.lower + +export type Options = { + whitespace: boolean?, -- keep whitespace-only text (default false: dropped, except inside xml:space="preserve") + namespaces: boolean?, -- resolve namespace prefixes: "start" events carry the element's URI (default false) + entities: { [string]: string }?, -- extra general entities (name -> replacement text) + maxExpansion: number?, -- total characters produced by entity expansion (default 1e7; the billion laughs guard) + maxDepth: number?, -- element nesting limit (default 10000) +} + +local NAME = "^[%a_:\128-\255][%w_:%.%-\128-\255]*" +local PREDEF: { [string]: string } = { lt = "<", gt = ">", amp = "&", quot = '"', apos = "'" } + +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 +Parse.utf8char = utf8char + +local CP1252: { [number]: number } = { + [0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020, + [0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152, + [0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022, + [0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A, + [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178, +} + +local function utf16(s: string, start: number, le: boolean): (string?, string?) + local out = table.create(#s // 2) + local n = 0 + local i = start + local len = #s + while i + 1 <= len do + local a, b = byte(s, i, i + 1) + local u = if le then a + b * 256 else a * 256 + b + i += 2 + if u >= 0xD800 and u <= 0xDBFF then + if i + 1 > len then + return nil, "truncated UTF-16 surrogate pair" + end + local c, d = byte(s, i, i + 1) + local lo = if le then c + d * 256 else c * 256 + d + if lo < 0xDC00 or lo > 0xDFFF then + return nil, "bad UTF-16 surrogate pair" + end + i += 2 + u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00) + elseif u >= 0xDC00 and u <= 0xDFFF then + return nil, "bad UTF-16 surrogate pair" + end + n += 1 + out[n] = utf8char(u) + end + if i <= len then + return nil, "odd number of bytes in UTF-16 text" + end + return table.concat(out), nil +end + +-- toUtf8(s) -> UTF-8 text (BOM removed), the encoding name | nil, message +function Parse.toUtf8(s: string): (string?, string) + local b1, b2, b3 = byte(s, 1, 3) + if b1 == 0xEF and b2 == 0xBB and b3 == 0xBF then + return sub(s, 4), "utf-8" + elseif b1 == 0xFF and b2 == 0xFE then + local t, e = utf16(s, 3, true) + return t, e or "utf-16le" + elseif b1 == 0xFE and b2 == 0xFF then + local t, e = utf16(s, 3, false) + return t, e or "utf-16be" + elseif b1 == 0x3C and b2 == 0 then + local t, e = utf16(s, 1, true) + return t, e or "utf-16le" + elseif b1 == 0 and b2 == 0x3C then + local t, e = utf16(s, 1, false) + return t, e or "utf-16be" + end + local decl = match(s, "^<%?xml[^>]-%?>") + local enc = if decl then match(decl, "encoding%s*=%s*[\"']([%w%._%-]+)[\"']") else nil + if enc then + local e = lower(enc) + if e == "utf-8" or e == "utf8" or e == "us-ascii" or e == "ascii" then + if find(s, "[\128-\255]") and not utf8.len(s) then + return nil, "invalid UTF-8" + end + return s, e + elseif e == "iso-8859-1" or e == "latin1" or e == "latin-1" or e == "iso8859-1" or e == "windows-1252" or e == "cp1252" then + local w = e == "windows-1252" or e == "cp1252" + return (gsub(s, "[\128-\255]", function(c: string): string + local v = byte(c) + return utf8char(if w then CP1252[v] or v else v) + end)), e + elseif e == "utf-16" or e == "utf-16le" or e == "utf-16be" then + return s, "utf-8" -- declared UTF-16 but read as 8-bit text: trust the bytes + end + return nil, "unsupported encoding " .. enc + end + if find(s, "[\128-\255]") and not utf8.len(s) then + return nil, "invalid UTF-8" + end + return s, "utf-8" +end + +-- the pseudo-attributes, strictly: version, then encoding?, then standalone?, each after whitespace +local function xmlDecl(data: string): { [string]: string }? + local p = 1 + local out: { [string]: string } = {} + for k, key in { "version", "encoding", "standalone" } do + local ws = match(data, "^[ \t\n]*()", p) :: any + local q, v, e = match(data, "^" .. key .. "[ \t\n]*=[ \t\n]*([\"'])(.-)%1()", ws) + if q then + if k > 1 and ws == p then + return nil -- no whitespace before + end + if (key == "version" and not match(v, "^1%.%d+$")) + or (key == "encoding" and not match(v, "^%a[%w%._%-]*$")) + or (key == "standalone" and v ~= "yes" and v ~= "no") + then + return nil + end + out[key] = v + p = e + elseif key == "version" then + return nil + end + end + if match(data, "^[ \t\n]*()", p) ~= #data + 1 then + return nil + end + return out +end + +-- the events iterator: next() -> event, a, b, c +-- "decl", { version, encoding, standalone } the declaration +-- "doctype", raw, info raw = the text between ""; info = { name, +-- publicId, systemId, entities } +-- "start", name, attrs (Types.object), ns ns: the element's namespace URI (opts.namespaces) or nil +-- "end", name +-- "text", s character data, entities decoded (whitespace-only dropped +-- unless opts.whitespace) +-- "cdata", s "comment", s "pi", target, data +-- "error", message, offset then the iterator ends +-- nil at the end of the document. +function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) + local o: Options = opts or {} + local keepWs = o.whitespace == true + local nsOn = o.namespaces == true + local maxExp = o.maxExpansion or 1e7 + local maxDepth = o.maxDepth or 10000 + local entities: { [string]: string } = {} + if o.entities then + for k, v in o.entities do + entities[k] = v + end + end + local external: { [string]: boolean } = {} + local expanded = 0 + if find(s, "\r", 1, true) then + s = gsub(gsub(s, "\r\n", "\n"), "\r", "\n") + end + local n = #s + local i = 1 + local stack: { string } = {} + local nsStack: { { [string]: string } } = {} + local preserve: { boolean } = {} + local depth = 0 + local rootSeen = false + local rootDone = false + local dead = false + local pending: { any }? = nil -- an "end" queued after a self-closing start + local errMsg: string? = nil + local errAt = 0 + + local function fail(msg: string, at: number): (string, string, number) + dead = true + return "error", msg, at - 1 + end + + -- decode entity / character references in raw text; nil on error (errMsg set) + local decode: (raw: string, at: number, level: number) -> string? + function decode(raw: string, at: number, level: number): string? + if not find(raw, "&", 1, true) then + return raw + end + local parts = {} + local np = 0 + local p = 1 + while true do + local a = find(raw, "&", p, true) + if not a then + break + end + np += 1 + parts[np] = sub(raw, p, a - 1) + local ref, e = match(raw, "^&([^;&%s<]*);()", a) + if not ref then + errMsg, errAt = "bad reference (no ';')", at + a - 1 + return nil + end + local rep: string + if byte(ref) == 35 then -- # + local cp = if byte(ref, 2) == 120 then tonumber(match(ref, "^#x(%x+)$") or "", 16) else tonumber(match(ref, "^#(%d+)$") or "") + if not cp or cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) or cp == 0xFFFE or cp == 0xFFFF then + errMsg, errAt = "bad character reference &" .. ref .. ";", at + a - 1 + return nil + end + rep = utf8char(cp) + else + local pre = PREDEF[ref] + if pre then + rep = pre + else + local ent = entities[ref] + if not ent then + errMsg = if external[ref] then "external entity &" .. ref .. "; not supported" else "undefined entity &" .. ref .. ";" + errAt = at + a - 1 + return nil + end + if level > 40 then + errMsg, errAt = "entity references nested too deeply (recursive?)", at + a - 1 + return nil + end + local r = decode(ent, at + a - 1, level + 1) + if not r then + return nil + end + rep = r + end + end + expanded += #rep + if expanded > maxExp then + errMsg, errAt = "entity expansion over the limit", at + a - 1 + return nil + end + np += 1 + parts[np] = rep + p = e :: any + end + np += 1 + parts[np] = sub(raw, p) + return table.concat(parts) + end + + local function lookupNs(prefix: string): string? + for d = depth, 1, -1 do + local m = nsStack[d] + if m and m[prefix] ~= nil then + return m[prefix] + end + end + if prefix == "xml" then + return "http://www.w3.org/XML/1998/namespace" + end + return nil + end + + -- a quoted literal at p -> its content, the position after it | nil + local function literal(p: number): (string?, number) + local q = byte(s, p) + if q ~= 34 and q ~= 39 then + return nil, p + end + local e = find(s, if q == 34 then '"' else "'", p + 1, true) + if not e then + return nil, p + end + return sub(s, p + 1, e - 1), e + 1 + end + -- an ExternalID (SYSTEM "sys" | PUBLIC "pub" "sys") at p -> publicId, systemId, next | nil + local function externalId(p: number): (string?, string?, number?) + local kw = sub(s, p, p + 5) + if kw == "SYSTEM" then + local q = match(s, "^[ \t\n]+()", p + 6) :: any + if not q then + return nil + end + local sys, e = literal(q) + if not sys then + return nil + end + return "", sys, e + elseif kw == "PUBLIC" then + local q = match(s, "^[ \t\n]+()", p + 6) :: any + if not q then + return nil + end + local pub, e = literal(q) + if not pub or find(pub, "[^ \r\n%w%-'()+,./:=?;!*#@$_%%]") then + return nil + end + local r = match(s, "^[ \t\n]+()", e) :: any + if not r then + return nil + end + local sys, e2 = literal(r) + if not sys then + return nil + end + return pub, sys, e2 + end + return nil + end + -- check an entity value's references and expand its character references (the rest expand when used) + local function entityValue(v: string): string? + if find(v, "%", 1, true) then + return nil -- parameter-entity references are not allowed in the internal subset's markup + end + local p = 1 + local parts = {} + while true do + local a = find(v, "&", p, true) + if not a then + table.insert(parts, sub(v, p)) + break + end + table.insert(parts, sub(v, p, a - 1)) + local hex = match(v, "^&#x(%x+);", a) + local dec = match(v, "^&#(%d+);", a) + if hex or dec then + local cp = tonumber(hex or dec, if hex then 16 else 10) :: number + if cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) then + return nil + end + table.insert(parts, utf8char(cp)) + p = (find(v, ";", a, true) :: number) + 1 + else + local name = match(v, "^&([%a_:\128-\255][%w_:%.%-\128-\255]*);", a) + if not name then + return nil + end + table.insert(parts, "&" .. name .. ";") + p = a + #name + 2 + end + end + return table.concat(parts) + end + -- the DOCTYPE at i (just past " p and (sub(s, q, q + 5) == "SYSTEM" or sub(s, q, q + 5) == "PUBLIC") then + local pub, sys, e = externalId(q) + if not pub then + return nil, "bad DOCTYPE external id" + end + info.publicId = if pub ~= "" then pub else nil + info.systemId = sys + q = match(s, "^[ \t\n]*()", e) :: any + end + if byte(s, q) == 91 then -- the internal subset + q += 1 + while true do + q = match(s, "^[ \t\n]*()", q) :: any + local c = byte(s, q) + if c == 93 then + q += 1 + break + elseif c == 37 then -- %name; + local pe = match(s, "^%%[%a_:\128-\255][%w_:%.%-\128-\255]*;()", q) + if not pe then + return nil, "bad parameter-entity reference" + end + q = pe :: any + elseif sub(s, q, q + 3) == "") + elseif name == "#cdata" then + table.insert(out, "", "]]]]>") .. "]]>") + elseif name == "#pi" then + if badName(n.target) or find(n.text or "", "?>", 1, true) then + err = "bad processing instruction" + return + end + table.insert(out, "") + elseif name == "#doctype" then + table.insert(out, "") + elseif name == "#document" then + for i, ch in n.children do + if i > 1 and ind then + table.insert(out, "\n") + end + write(ch, 0) + end + else + if badName(name) then + err = "bad element name " .. tostring(name) + return + end + table.insert(out, "<" .. name) + local attrs = n.attrs or {} + for _, k in Types.keys(attrs) do + local v = attrs[k] + if badName(k) then + err = "bad attribute name " .. tostring(k) + return + end + if type(v) == "number" or type(v) == "boolean" then + v = tostring(v) + elseif type(v) ~= "string" then + err = "attribute " .. k .. " is not a string" + return + end + table.insert(out, " " .. k .. '="' .. Xml.escapeAttr(v) .. '"') + end + local ch = n.children or {} + if #ch == 0 then + table.insert(out, if selfClose then "/>" else ">") + return + end + table.insert(out, ">") + local pretty = ind ~= nil + if pretty then + for _, c in ch do + if type(c) == "string" or c.name == "#cdata" then + pretty = false + break + end + end + end + for _, c in ch do + if pretty then + table.insert(out, "\n" .. string.rep(ind :: string, depth + 1)) + end + write(c, depth + 1) + end + if pretty then + table.insert(out, "\n" .. string.rep(ind :: string, depth)) + end + table.insert(out, "") + end + end + + local decl = o.declaration + if decl == nil then + decl = node.name == "#document" + end + if decl then + local d: any = node.declaration or {} + table.insert(out, '") + table.insert(out, "\n") + end + if node.name == "#document" and node.doctype then + local dt: any = node.doctype + local raw = dt.raw + if raw == nil then + raw = " " .. (dt.name or (if node.root then node.root.name else "root")) + if dt.publicId then + raw ..= ' PUBLIC "' .. dt.publicId .. '" "' .. (dt.systemId or "") .. '"' + elseif dt.systemId then + raw ..= ' SYSTEM "' .. dt.systemId .. '"' + end + end + table.insert(out, "\n") + end + write(node, 0) + if err then + return nil, Err.new(Err.ARG, err) + end + if ind and node.name == "#document" then + table.insert(out, "\n") + end + return table.concat(out), nil +end + +return Xml diff --git a/tests/codecs/xml.luau b/tests/codecs/xml.luau new file mode 100644 index 0000000..dac3f32 --- /dev/null +++ b/tests/codecs/xml.luau @@ -0,0 +1,197 @@ +-- codecs/Xml tests: random documents (namespaces, escapes, CDATA, comments, PIs, DOCTYPE entities, UTF-16, Latin-1) +-- against Python's ElementTree trees; encode -> decode round trips; well-formedness verdicts against expat +-- (hand-written cases and random mutations); events, helpers, options, error codes; the fuzz pass. +-- Fixtures: tools/fixtures/xml.py. +local T = require("@tests/T") +local Xml = require("@formats/codecs/Xml") +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") +local Docs = require("@tests/gen/xml_docs") +local Wf = require("@tests/gen/xml_wf") + +local t = T.suite("xml") + +-- ElementTree's view of an element (tools/fixtures/xml.py canon): Clark names, xmlns attributes dropped, text / tail +local function s(x: string?): string + x = x or "" + return #(x :: string) .. ":" .. (x :: string) +end +local function canon(e: any, tail: string?): string + local out = { "(" .. s(Xml.clark(e)) } + local keys = {} + local vals = {} + for _, k in Types.keys(e.attrs) do + if k ~= "xmlns" and string.sub(k, 1, 6) ~= "xmlns:" then + local ck = Xml.clark(e, k) + table.insert(keys, ck) + vals[ck] = e.attrs[k] + end + end + table.sort(keys) + for _, k in keys do + table.insert(out, "|" .. s(k) .. "=" .. s(vals[k])) + end + -- text: strings before the first element child; each child's tail: strings after it + local text = {} + local i = 1 + local ch = e.children + while i <= #ch and (type(ch[i]) == "string" or ch[i].name == "#cdata") do + table.insert(text, Xml.text(ch[i])) + i += 1 + end + table.insert(out, "|t" .. s(table.concat(text))) + while i <= #ch do + local c = ch[i] + i += 1 + local tl = {} + while i <= #ch and (type(ch[i]) == "string" or ch[i].name == "#cdata") do + table.insert(tl, Xml.text(ch[i])) + i += 1 + end + table.insert(out, canon(c, table.concat(tl))) + end + return table.concat(out) .. ")t" .. s(tail) +end + +-- 1. documents vs ElementTree, and round trips +for i, d in Docs do + local doc, err = Xml.decode(d.data, { whitespace = true }) + t:check(doc, "doc " .. i .. ": " .. tostring(err)) + t:eq(canon((doc :: any).root), d.canon, "doc " .. i .. ": tree") + -- keep everything, encode, decode again: the same tree + local full = Xml.decode(d.data, { whitespace = true, comments = true, cdata = true, pi = true }) :: any + local out, eerr = Xml.encode(full) + t:check(out, "doc " .. i .. ": encodes (" .. tostring(eerr) .. ")") + local again, aerr = Xml.decode(out :: string, { whitespace = true }) + t:check(again, "doc " .. i .. ": re-decodes (" .. tostring(aerr) .. ")") + t:eq(canon((again :: any).root), d.canon, "doc " .. i .. ": round trip") + local pretty = Xml.encode(full, { indent = 2 }) :: string + t:check(Xml.decode(pretty), "doc " .. i .. ": pretty output parses") + -- the namespace option agrees with the clark helper + local nsdoc = Xml.decode(d.data, { namespaces = true }) :: any + local root = nsdoc.root + local want = string.match(Xml.clark(root), "^{([^}]*)}") + t:eq(root.ns, want, "doc " .. i .. ": node.ns") +end + +-- 2. well-formedness against expat +local agree, total, accepted, rejected = 0, 0, 0, 0 +for i, c in Wf do + local doc = Xml.decode(c.data) + local ok = doc ~= nil + total += 1 + if ok == c.ok then + agree += 1 + elseif i <= 60 then + t:check(false, "wf case " .. i .. " " .. string.format("%q", c.data) .. ": expat says " .. tostring(c.ok)) + end + if c.ok then + accepted += 1 + else + rejected += 1 + end +end +t:note("well-formedness: %d of %d verdicts agree with expat (%d well-formed, %d not)", agree, total, accepted, rejected) +t:check(agree >= total * 0.99, "well-formedness agreement >= 99%") + +-- 3. API details +do + local src = '\n]>\nt]]>u\n' + local doc = Xml.decode(src, { comments = true, cdata = true, pi = true, namespaces = true }) :: any + t:eq(doc.declaration.version, "1.0", "declaration") + t:eq(doc.doctype.name, "r", "doctype name") + t:eq(doc.doctype.entities.e, "E&", "doctype entities (char refs expanded once)") + t:eq(doc.children[1].name, "#comment", "prolog comment kept") + local r = doc.root + t:eq(table.concat(Types.keys(r.attrs), ","), "xmlns,xmlns:p,z,a", "attribute order") + t:eq(r.ns, "urn:d", "default namespace") + local x = Xml.child(r, "x") :: any + t:eq(x.name, "p:x", "child by local name") + t:eq(x.ns, "urn:p", "prefixed namespace") + t:eq(Xml.clark(x, "p:k"), "{urn:p}k", "attribute clark") + t:eq(x.children[2].name, "#cdata", "cdata node") + t:eq(Xml.text(x), "tu", "text with cdata") + t:eq(r.children[2].name, "#pi", "pi node") + t:eq(r.children[2].target .. "|" .. r.children[2].text, "go|now", "pi target / data") + t:eq(#Xml.children(r), 2, "element children") + t:eq(#Xml.descendants(doc), 3, "descendants") + t:eq(x.parent, r, "parent link") + t:eq(Xml.decode("&e;") == nil, true, "undefined entity") + local d2 = Xml.decode(']>&e;') :: any + t:eq(d2.root.attrs.a, "E&", "entity in attribute") + t:eq(Xml.text(d2.root), "E&", "entity in text") + -- whitespace handling + local w = Xml.decode("\n x \n \n") :: any + t:eq(#w.root.children, 2, "whitespace-only text dropped") + t:eq(Xml.text(w.root.children[1]), " x ", "other text kept as is") + t:eq(w.root.children[2].children[1], " ", "xml:space preserve") + t:eq(#(Xml.decode("\n \n", { whitespace = true }) :: any).root.children, 3, "opts.whitespace") + -- attribute normalization and line endings + local n = Xml.decode("l1\r\nl2\rl3") :: any + t:eq(n.root.attrs.b, "x y z\n", "attribute value normalization") + t:eq(Xml.text(n.root), "l1\nl2\nl3", "line endings") + -- builders and encode + local e = Xml.element("svg", { width = "10", height = "5" }, { Xml.element("rect", { x = "1" }), "aa<b & "c"', "encode element") + local d3 = Xml.document(Xml.element("r", nil, { Xml.element("a"), Xml.element("b", nil, { "t" }) })) + t:eq(Xml.encode(d3, { indent = 2 }), '\n\n \n t\n\n', "pretty document") + t:eq(Xml.encode(Xml.element("a"), { selfClose = false }), "", "selfClose false") + local _, be = Xml.encode(Xml.element("1bad")) + t:eq(be and be.code, Err.ARG, "bad name on encode") + local cyc = Xml.element("a") + table.insert(cyc.children, cyc) + local _, ce = Xml.encode(cyc) + t:eq(ce and ce.code, Err.ARG, "cycle on encode") + t:eq(Xml.encode({ name = "#cdata", attrs = Types.object(), children = {}, text = "a]]>b" } :: any), "b]]>", "cdata split") + -- events + local evs = {} + for ev, a in Xml.events("t") do + table.insert(evs, ev .. (if type(a) == "string" then ":" .. a else "")) + end + t:eq(table.concat(evs, " "), "start:a start:b text:t end:b comment:c end:a", "events") + local last + for ev, a in Xml.events("") do + last = { ev, a } + end + t:eq(last[1], "error", "events error") + t:eq(last[2].code, Err.CORRUPT, "events error code") + -- UTF-16 without BOM and encodings + local u16 = buffer.create(8) + for k, ch in { 60, 0, 97, 0, 47, 0, 62, 0 } do + buffer.writeu8(u16, k - 1, ch) + end + t:eq((Xml.decode(u16) :: any).root.name, "a", "UTF-16LE without BOM") + local _, ue = Xml.decode("") + t:eq(ue and ue.code, Err.UNSUPPORTED, "unsupported encoding") +end + +-- 4. errors and limits +local function code(src: string, opts: any?): string? + local _, e = Xml.decode(src, opts) + return e and e.code +end +t:eq(code(""), Err.TRUNCATED, "unclosed") +t:eq(code(""), Err.CORRUPT, "mismatch") +t:eq(code(""), Err.CORRUPT, "duplicate attribute") +t:eq(code(string.rep("", 60) .. string.rep("", 60), { maxDepth = 50 }), Err.LIMIT, "maxDepth") +t:eq(code(']>&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;', { maxExpansion = 100000 }), Err.LIMIT, "billion laughs") +t:eq(code(']>&a;'), Err.CORRUPT, "recursive entity") +t:eq(code(']>&x;'), Err.UNSUPPORTED, "external entity") +t:eq(code("", { namespaces = true }), Err.CORRUPT, "undeclared prefix") +local _, ae = Xml.decode(5 :: any) +t:eq(ae and ae.code, Err.ARG, "bad argument") + +-- 5. fuzz +local samples = {} +for i = 1, 40 do + table.insert(samples, Docs[i].data) +end +t:fuzz("decode", function(b: buffer) + return Xml.decode(b, { comments = true, namespaces = true }) +end, samples) +t:fuzz("encode(decode)", function(b: buffer) + local d = Xml.decode(b, { comments = true, cdata = true, pi = true }) + return d and Xml.encode(d, { indent = 1 }) +end, samples, { garbage = 20 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 5815060..eb68b0a 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -71,3 +71,18 @@ do Json.encode(v) end) end +do + local Xml = require("@formats/codecs/Xml") + local XB = require("@tests/gen/xml_bench") + local doc = assert(Xml.decode(XB.text)) + bench("xml decode (DOM)", 5, #XB.text, function() + Xml.decode(XB.text) + end) + bench("xml events", 5, #XB.text, function() + for _ in Xml.events(XB.text) do + end + end) + bench("xml encode", 5, #XB.text, function() + Xml.encode(doc) + end) +end diff --git a/tools/bench.sh b/tools/bench.sh index f77a3fa..31f663a 100644 --- a/tools/bench.sh +++ b/tools/bench.sh @@ -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 json > /dev/null || exit 1 +python3 -I tools/fixtures.py deflate png json xml > /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 diff --git a/tools/fixtures/xml.py b/tools/fixtures/xml.py new file mode 100644 index 0000000..14cf720 --- /dev/null +++ b/tools/fixtures/xml.py @@ -0,0 +1,174 @@ +# codecs/Xml + data/xml fixtures: random documents (namespaces, attributes with every escape, CDATA, comments, PIs, +# entities from an internal DOCTYPE, mixed content) written by hand, then parsed by Python's xml.etree (expat) for the +# reference tree; the same documents re-encoded as UTF-16 and Latin-1; and well-formedness cases (hand-written plus +# random mutations) with expat's verdict. +# tests/gen/xml_docs.luau { { data, canon } } canon: see canon() below (the test computes the same) +# tests/gen/xml_wf.luau { { data, ok } } ok: expat accepts it +# tests/gen/xml_bench.luau { text } (~1 MB) +import xml.etree.ElementTree as ET +from xml.parsers import expat + +NS = [("", None), ("a", "urn:a"), ("b", "http://example.com/b")] +TAGS = ["item", "x", "Data", "set-1", "q.r", "_u", "élément", "名"] +TXT = "ab <>&\"' é中\U0001f600\t\n ]]" + + +def s(x): + x = x or "" + b = x.encode("utf-8", "surrogatepass") + return b"%d:" % len(b) + b + + +def canon(e): + out = b"(" + s(e.tag) + for k in sorted(e.attrib): + out += b"|" + s(k) + b"=" + s(e.attrib[k]) + out += b"|t" + s(e.text) + for c in e: + out += canon(c) + return out + b")t" + s(e.tail) + + +def esc_text(t): + return t.replace("&", "&").replace("<", "<").replace(">", ">") + + +def esc_attr(t, q): + t = t.replace("&", "&").replace("<", "<") + return t.replace(q, """ if q == '"' else "'") + + +def rand_text(rng): + return "".join(rng.choice(TXT) for _ in range(rng.randrange(0, 10))) + + +def gen_elem(rng, depth, declared): + prefix = rng.choice([p for p in declared]) + local = rng.choice(TAGS) + name = (prefix + ":" + local) if prefix else local + attrs = [] + newdecl = set(declared) + if depth > 0 and rng.random() < 0.15: + p, uri = rng.choice(NS[1:]) + attrs.append(("xmlns:" + p, uri)) + newdecl.add(p) + if rng.random() < 0.1: + attrs.append(("xmlns", "urn:default%d" % rng.randrange(3))) + used = set(a for a, _ in attrs) + for _ in range(rng.randrange(0, 4)): + an = rng.choice(["id", "k", "v-1", "é", "x.y"]) + if rng.random() < 0.2 and len(newdecl) > 1: + an = rng.choice([p for p in newdecl if p]) + ":" + an + if an in used: + continue + used.add(an) + attrs.append((an, rand_text(rng))) + parts = ["<" + name] + for k, v in attrs: + q = rng.choice("\"'") + parts.append(" %s=%s%s%s" % (k, q, esc_attr(v, q), q)) + if depth > 4 or rng.random() < 0.15: + parts.append(rng.choice(["/>", " />"])) + return "".join(parts) + parts.append(">") + for _ in range(rng.randrange(0, 5)): + r = rng.random() + if r < 0.35: + parts.append(esc_text(rand_text(rng))) + elif r < 0.45: + parts.append("]]>") + elif r < 0.5: + parts.append("") + elif r < 0.53: + parts.append("") + elif r < 0.58: + parts.append(rng.choice(["&ent;", "é", "😀", "&", "<", " "])) + else: + parts.append(gen_elem(rng, depth + 1, newdecl)) + parts.append("" % name) + return "".join(parts) + + +def gen_doc(rng): + head = "" + if rng.random() < 0.5: + head += '\n' + head += '\n \n]>\n' + if rng.random() < 0.3: + head += "\n" + declared = {""} + body = gen_elem(rng, 0, declared) + # the root must declare every prefix it may use: declare all at the root + root_decl = " ".join('xmlns:%s="%s"' % (p, u) for p, u in NS[1:]) + i = body.index(">") if not body.startswith("<") else 0 + name_end = 1 + while body[name_end] not in " />": + name_end += 1 + body = body[:name_end] + " " + root_decl + body[name_end:] + return head + body + ("\n" if rng.random() < 0.5 else "") + + +def expat_ok(data): + p = expat.ParserCreate() + try: + p.Parse(data, True) + return True + except Exception: # ExpatError, or LookupError for an unknown encoding name + return False + + +WF = [ + "", "", "", "x", "", "", "", "text", "text", "", + "", "", "&undefined;", "�", "�", "�", "& ", + "", "", "]]>", "<1a/>", "", "", + "", " ", "", "", + "", "", "\x01", "", "", "", + "", "", "]>&e;", "", + "", "", "", "", "< a/>", "", "", + "é\U0001f600", "&<>"'", "", + "", "", "", " ", "xtrailing", "x ", +] + + +def generate(ctx): + rng = ctx.rng(11) + docs = [] + for k in range(250): + text = gen_doc(rng) + root = ET.fromstring(text.encode("utf-8")) + docs.append({"data": text.encode("utf-8"), "canon": canon(root)}) + # other encodings: UTF-16 (BOM, both byte orders) and Latin-1 + for k in range(10): + text = gen_doc(rng) + body = text.split("?>", 1)[1] if text.startswith("' + body).encode("utf-16"), "canon": c}) + docs.append({"data": b"\xfe\xff" + ('' + body).encode("utf-16-be"), "canon": c}) + for k in range(10): + text = "café ½ 中" + data = text.encode("latin-1") + docs.append({"data": data, "canon": canon(ET.fromstring(data))}) + ctx.emit("xml_docs", docs) + + wf = [{"data": d.encode("utf-8"), "ok": expat_ok(d.encode("utf-8"))} for d in WF] + # mutations of valid documents: delete / duplicate / replace one markup character + for k in range(400): + text = gen_doc(rng).encode("utf-8") + b = bytearray(text) + for _ in range(rng.randrange(1, 3)): + pos = rng.randrange(len(b)) + op = rng.randrange(3) + ch = rng.choice(b"<>/&;='\"![]-? ") + if op == 0: + del b[pos] + elif op == 1: + b.insert(pos, ch) + else: + b[pos] = ch + wf.append({"data": bytes(b), "ok": expat_ok(bytes(b))}) + ctx.emit("xml_wf", wf) + + parts = [] + while sum(map(len, parts)) < 1_000_000: + parts.append(gen_elem(rng, 1, {""})) + ctx.emit("xml_bench", {"text": "" + "\n".join(p for p in parts if "&ent;" not in p) + ""})