Merge branch 'ws/data' into ws/3d

This commit is contained in:
4DBug committed 2026-10-31 08:46:18 -05:00
commit c84d00137d
20 files changed
+3708 -3

No files matched your search

+4
View File
@@ -6,7 +6,11 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|---|---|---|---|---|---|---|
| image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
| data | json | .json .jsonl .ndjson .geojson | yes | yes | ordered: true, streaming: true | `tests/data/json.luau` |
| data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` |
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, ...
+24
View File
@@ -26,6 +26,30 @@ local list: { Entry } = {
return require("@formats/image/png")
end,
},
{
name = "json",
category = "data",
path = "data/json",
extensions = { "json", "jsonl", "ndjson", "geojson" },
mime = { "application/json", "application/x-ndjson" },
deps = { "core/Err", "core/Bytes", "codecs/Json" },
caps = { decode = true, encode = true, ordered = true, streaming = true },
load = function()
return require("@formats/data/json")
end,
},
{
name = "xml",
category = "data",
path = "data/xml",
extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" },
mime = { "application/xml", "text/xml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml" },
caps = { decode = true, encode = true, namespaces = true, streaming = true },
load = function()
return require("@formats/data/xml")
end,
},
}
return list
+279 -2
View File
@@ -601,12 +601,289 @@ export type Archive = {
-- ------------------------------------------------------------------------------------------------ Data
-- data formats decode to plain Luau values; JSON null / YAML ~ / CBOR null is this sentinel (nil cannot sit in a
-- table). XML decodes to XmlNode trees.
-- table). XML decodes to XmlNode trees. Byte strings (msgpack bin, CBOR bytes, plist data) are buffers.
local nullMeta = { __tostring = function()
return "null"
end }
Types.null = table.freeze(setmetatable({}, nullMeta))
export type XmlNode = { name: string, attrs: { [string]: string }, children: { XmlNode | string }, parent: XmlNode? }
-- Objects (maps) whose key order matters, and empty objects (which would otherwise read back as empty arrays), carry
-- an "object" metatable with their key order. Decoders mark empty objects always and every object when asked
-- (opts.ordered); encoders write an object's keys in that order (keys added later, or plain tables: sorted).
-- local o = Types.object() o.b = 1; o.a = 2 -- or Types.object({ a = 2, b = 1 }, { "b", "a" })
-- Types.set(o, "c", 3) -- assigns and appends "c" to the order
-- for _, k in Types.keys(o) do ... end
local OBJECT = { __object = true }
local objectMeta: { [any]: { any } } = setmetatable({}, { __mode = "k" }) :: any -- object -> its key order
-- object(t?, keys?) -> t marked as an object, keys = its key order (default: none recorded; Types.set appends)
function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any }
local o = t or {}
if getmetatable(o) == nil then
setmetatable(o, OBJECT)
end
objectMeta[o] = keys or {}
return o
end
-- isObject(v) -> true for tables made by Types.object
function Types.isObject(v: any): boolean
return type(v) == "table" and objectMeta[v] ~= nil
end
-- set(o, k, v): o[k] = v, appending k to o's key order when new (o must be an object; a plain table just assigns)
function Types.set(o: { [any]: any }, k: any, v: any)
local order = objectMeta[o]
if order and o[k] == nil and v ~= nil then
table.insert(order, k)
end
o[k] = v
end
local function keyLess(a: any, b: any): boolean
local ta, tb = type(a), type(b)
if ta ~= tb then
return ta < tb
end
if ta == "number" or ta == "string" then
return a < b
end
return tostring(a) < tostring(b)
end
-- keys(t) -> the keys in order: an object's recorded order (keys since removed are skipped), then any other keys
-- sorted (numbers before strings)
function Types.keys(t: { [any]: any }): { any }
local order = objectMeta[t]
local out, seen = {}, {}
if order then
for _, k in order do
if t[k] ~= nil and not seen[k] then
seen[k] = true
table.insert(out, k)
end
end
end
local rest = {}
for k in next, t do
if not seen[k] then
table.insert(rest, k)
end
end
if #rest > 0 then
table.sort(rest, keyLess)
table.move(rest, 1, #rest, #out + 1, out)
end
return out
end
-- Dates and times (TOML datetimes, plist <date>, CBOR tags 0 / 1, msgpack timestamps). Fields present depend on the
-- kind: "datetime" (with offset: an instant), "datetime-local", "date-local", "time-local". offset is in minutes
-- east of UTC (nil = local time). tostring gives RFC 3339 ("1979-05-27T07:32:00.5-07:00", "07:32:00", ...).
export type Date = {
kind: "datetime" | "datetime-local" | "date-local" | "time-local",
year: number?,
month: number?,
day: number?,
hour: number?,
minute: number?,
second: number?,
nanosecond: number?, -- 0 .. 999999999
offset: number?, -- minutes east of UTC
}
local DateMeta = {}
local function p2(n: number): string
return string.format("%02d", n)
end
local function fmtDate(d: any): string
local s = ""
if d.year then
s = string.format("%04d-%02d-%02d", d.year, d.month or 1, d.day or 1)
end
if d.hour then
if s ~= "" then
s ..= "T"
end
s ..= p2(d.hour) .. ":" .. p2(d.minute or 0) .. ":" .. p2(d.second or 0)
local ns = d.nanosecond or 0
if ns > 0 then
local f = string.format("%09d", ns)
s ..= "." .. (string.gsub(f, "0+$", ""))
end
if d.offset then
if d.offset == 0 then
s ..= "Z"
else
local o = math.abs(d.offset)
s ..= (if d.offset < 0 then "-" else "+") .. p2(o // 60) .. ":" .. p2(o % 60)
end
end
end
return s
end
DateMeta.__tostring = fmtDate
DateMeta.__eq = function(a: any, b: any): boolean
return fmtDate(a) == fmtDate(b) and a.kind == b.kind
end
local DateLib = {}
-- days since 1970-01-01 of a civil date (proleptic Gregorian; Howard Hinnant's algorithm)
local function daysFromCivil(y: number, m: number, d: number): number
y = if m <= 2 then y - 1 else y
local era = (if y >= 0 then y else y - 399) // 400
local yoe = y - era * 400
local mp = (m + 9) % 12
local doy = (153 * mp + 2) // 5 + d - 1
local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy
return era * 146097 + doe - 719468
end
local function civilFromDays(z: number): (number, number, number)
z += 719468
local era = (if z >= 0 then z else z - 146096) // 146097
local doe = z - era * 146097
local yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365
local y = yoe + era * 400
local doy = doe - (365 * yoe + yoe // 4 - yoe // 100)
local mp = (5 * doy + 2) // 153
local d = doy - (153 * mp + 2) // 5 + 1
local m = if mp < 10 then mp + 3 else mp - 9
return (if m <= 2 then y + 1 else y), m, d
end
local MDAYS = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
-- new(fields) -> Date (kind inferred from the fields present when not given)
function DateLib.new(f: { [string]: any }): Date
local d: any = {}
for k, v in f do
d[k] = v
end
if d.kind == nil then
d.kind = if d.year and d.hour then (if d.offset then "datetime" else "datetime-local")
elseif d.year then "date-local"
else "time-local"
end
return setmetatable(d, DateMeta) :: any
end
-- is(v) -> true for Dates
function DateLib.is(v: any): boolean
return type(v) == "table" and getmetatable(v) == DateMeta
end
-- valid(d) -> true when the fields are in range (month 1..12, the day exists in that month, hour < 24, ...)
function DateLib.valid(d: Date): boolean
if d.year then
local y, m, dd = d.year, d.month or 0, d.day or 0
if y < 0 or y > 9999 or m < 1 or m > 12 or dd < 1 or dd > MDAYS[m] then
return false
end
if m == 2 and dd == 29 and not (y % 4 == 0 and (y % 100 ~= 0 or y % 400 == 0)) then
return false
end
end
if d.hour then
if d.hour > 23 or (d.minute or 0) > 59 or (d.second or 0) > 60 then
return false
end
end
if d.offset and math.abs(d.offset) >= 24 * 60 then
return false
end
return true
end
-- parse(s) -> Date | nil: RFC 3339 / ISO 8601 date-times and their TOML partial forms ("1979-05-27",
-- "07:32:00.999", "1979-05-27 07:32:00Z", lower-case t / z accepted); out-of-range fields return nil
function DateLib.parse(s: string): Date?
local d: any = {}
local rest = s
local y, mo, dd, r1 = string.match(rest, "^(%d%d%d%d)%-(%d%d)%-(%d%d)(.*)$")
if y then
d.year, d.month, d.day = tonumber(y), tonumber(mo), tonumber(dd)
rest = r1
if rest == "" then
return if DateLib.valid(d) then DateLib.new(d) else nil
end
local sep = string.sub(rest, 1, 1)
if sep ~= "T" and sep ~= "t" and sep ~= " " then
return nil
end
rest = string.sub(rest, 2)
end
local h, mi, r2 = string.match(rest, "^(%d%d):(%d%d)(.*)$")
if not h then
return nil
end
d.hour, d.minute = tonumber(h), tonumber(mi)
rest = r2
local sec, r3 = string.match(rest, "^:(%d%d)(.*)$")
if not sec then
return nil
end
d.second = tonumber(sec)
rest = r3
local frac, r4 = string.match(rest, "^%.(%d+)(.*)$")
if frac then
d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9))
rest = r4
else
d.nanosecond = 0
end
if rest ~= "" then
if not d.year then
return nil
end
if rest == "Z" or rest == "z" then
d.offset = 0
else
local sign, oh, om = string.match(rest, "^([%+%-])(%d%d):(%d%d)$")
if not sign then
return nil
end
local oh_n, om_n = tonumber(oh) :: number, tonumber(om) :: number
if oh_n > 23 or om_n > 59 then
return nil
end
d.offset = (oh_n * 60 + om_n) * (if sign == "-" then -1 else 1)
end
end
return if DateLib.valid(d) then DateLib.new(d) else nil
end
-- toUnix(d) -> seconds since 1970-01-01T00:00:00Z (fractional; local times are taken as UTC)
function DateLib.toUnix(d: Date): number
local days = if d.year then daysFromCivil(d.year, d.month or 1, d.day or 1) else 0
local s = days * 86400 + (d.hour or 0) * 3600 + (d.minute or 0) * 60 + (d.second or 0) - (d.offset or 0) * 60
return s + (d.nanosecond or 0) / 1e9
end
-- fromUnix(seconds, offset?) -> a "datetime" Date (offset in minutes, default 0 = UTC)
function DateLib.fromUnix(t: number, offset: number?): Date
local off = offset or 0
local whole = math.floor(t)
local ns = math.floor((t - whole) * 1e9 + 0.5)
if ns >= 1e9 then
whole += 1
ns -= 1e9
end
local lt = whole + off * 60
local days = lt // 86400
local secs = lt - days * 86400
local y, m, dd = civilFromDays(days)
return DateLib.new({
kind = "datetime",
year = y,
month = m,
day = dd,
hour = secs // 3600,
minute = (secs // 60) % 60,
second = secs % 60,
nanosecond = ns,
offset = off,
})
end
Types.Date = table.freeze(DateLib)
-- XML: an element, or (name starting with "#") a "#document" / "#comment" / "#cdata" / "#pi" / "#doctype" node with
-- its content in text. attrs is a Types.object (attribute order kept). Text children are plain strings.
export type XmlNode = {
name: string,
attrs: { [string]: string },
children: { XmlNode | string },
parent: XmlNode?,
text: string?, -- "#comment" / "#cdata" / "#pi" (the data after the target) / "#doctype" content
target: string?, -- "#pi": the target
ns: string?, -- the namespace URI (opts.namespaces)
[string]: any,
}
-- ------------------------------------------------------------------------------------------------ Vector
export type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any }
+433
View File
@@ -0,0 +1,433 @@
--!strict
--!native
-- codecs/Json/Decode: the RFC 8259 parser behind codecs/Json. Iterative (an explicit container stack, so deep nesting
-- is a LIMIT error, never a stack overflow), strict grammar (no comments, trailing commas, leading zeros, NaN, single
-- quotes or raw control characters), \u escapes with surrogate pairs (lone surrogates become WTF-8 bytes). Also the
-- pull tokenizer behind Json.events. Never throws: failures return nil, message, offset (0-based byte offset).
local Types = require("@formats/Types")
local Decode = {}
local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char
local tonumber = tonumber
local concat = table.concat
export type Options = {
ordered: boolean?, -- every object is a Types.object with its key order (default false: only empty objects are)
bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their exact text (default "number")
null: any?, -- the value for null (default Types.null)
maxDepth: number?, -- nesting limit (default 1000)
}
local ESC: { [number]: string } = {
[34] = '"',
[92] = "\\",
[47] = "/",
[98] = "\b",
[102] = "\f",
[110] = "\n",
[114] = "\r",
[116] = "\t",
}
-- utf8 bytes of a code point (surrogates too: WTF-8)
local function utf8char(c: number): string
if c < 0x80 then
return char(c)
elseif c < 0x800 then
return char(0xC0 + c // 64, 0x80 + c % 64)
elseif c < 0x10000 then
return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64)
end
return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64)
end
Decode.utf8char = utf8char
local function hex4(s: string, i: number): number?
local h = match(s, "^%x%x%x%x", i)
if not h then
return nil
end
return tonumber(h, 16)
end
-- string(s, i) -> value, next | nil, message, offset. i is at the opening quote.
local function str(s: string, i: number): (string?, any, number?)
local j = find(s, '[%z\1-\31"\\]', i + 1)
if not j then
return nil, "unterminated string", #s
end
local c = byte(s, j)
if c == 34 then
return sub(s, i + 1, j - 1), j + 1
end
local parts = {}
local np = 0
local start = i + 1
while true do
if c == 34 then
np += 1
parts[np] = sub(s, start, j - 1)
return concat(parts), j + 1
elseif c ~= 92 then
return nil, "control character in string", j - 1
end
np += 1
parts[np] = sub(s, start, j - 1)
local e = byte(s, j + 1)
if e == nil then
return nil, "unterminated string", #s
end
local simple = ESC[e]
if simple then
np += 1
parts[np] = simple
start = j + 2
elseif e == 117 then -- \u
local cp = hex4(s, j + 2)
if not cp then
return nil, "bad \\u escape", j - 1
end
start = j + 6
if cp >= 0xD800 and cp <= 0xDBFF and byte(s, start) == 92 and byte(s, start + 1) == 117 then
local lo = hex4(s, start + 2)
if lo and lo >= 0xDC00 and lo <= 0xDFFF then
cp = 0x10000 + (cp - 0xD800) * 1024 + (lo - 0xDC00)
start += 6
end
end
np += 1
parts[np] = utf8char(cp)
else
return nil, "bad escape", j - 1
end
j = find(s, '[%z\1-\31"\\]', start)
if not j then
return nil, "unterminated string", #s
end
c = byte(s, j)
end
end
Decode.string = str
-- number(s, i) -> value, next | nil, message, offset
local function num(s: string, i: number, bigStrings: boolean): (any, any, number?)
local p = i
if byte(s, p) == 45 then
p += 1
end
local c = byte(s, p)
if c == 48 then
p += 1
elseif c and c >= 49 and c <= 57 then
p = match(s, "^%d*()", p + 1) :: any
else
return nil, if c == nil then "truncated: expected a value" elseif p == i then "unexpected character" else "bad number", p - 1
end
local int = true
if byte(s, p) == 46 then
local q = match(s, "^%d+()", p + 1)
if not q then
return nil, "bad fraction", p
end
p = q :: any
int = false
end
c = byte(s, p)
if c == 101 or c == 69 then
p += 1
c = byte(s, p)
if c == 43 or c == 45 then
p += 1
end
local q = match(s, "^%d+()", p)
if not q then
return nil, "bad exponent", p - 1
end
p = q :: any
int = false
end
local text = sub(s, i, p - 1)
local n = tonumber(text) :: number
if n == nil then -- LuaJIT: absurd exponents (1e0066999...) -> nil; they overflow / underflow
local m, es = match(text, "^([^eE]*)[eE]([%+%-]?)")
local mv = tonumber(m) or 0
n = if mv == 0 then mv elseif es == "-" then mv * 0 else mv * math.huge
end
if int and bigStrings and p - i > 15 and (n >= 9007199254740992 or n <= -9007199254740992) then
return text, p
end
return n, p
end
Decode.number = num
-- decode(s, i, opts) -> value, next | nil, message, offset. Parses one value starting at i (leading whitespace
-- skipped); next is the position after the value (trailing whitespace not skipped).
function Decode.value(s: string, i: number, opts: Options?): (any, any, number?)
local o: Options = opts or {}
local ordered = o.ordered == true
local bigStrings = o.bigInts == "string"
local nullv = if o.null ~= nil then o.null else Types.null
local maxDepth = o.maxDepth or 1000
local object = Types.object
local stackT: { any } = {} -- containers
local stackK: { any } = {} -- object: the pending key; array: the count
local stackO: { any } = {} -- object: its key order (or true); array: false
local depth = 0
local n = #s
local value: any
while true do
i = match(s, "^[ \t\n\r]*()", i) :: any
local c = byte(s, i)
local haveValue = true
if c == 123 then -- {
depth += 1
if depth > maxDepth then
return nil, "nested deeper than " .. maxDepth, i - 1
end
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
local t = {}
c = byte(s, i)
if c == 125 then
i += 1
depth -= 1
value = object(t, {})
elseif c == 34 then
local k, ni, at = str(s, i)
if k == nil then
return nil, ni, at
end
i = match(s, "^[ \t\n\r]*()", ni) :: any
if byte(s, i) ~= 58 then
return nil, if i > n then "truncated object" else "expected ':'", i - 1
end
i += 1
stackT[depth], stackK[depth] = t, k
stackO[depth] = if ordered then {} else true
haveValue = false
else
return nil, if c == nil then "truncated object" else "expected a key", i - 1
end
elseif c == 91 then -- [
depth += 1
if depth > maxDepth then
return nil, "nested deeper than " .. maxDepth, i - 1
end
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
if byte(s, i) == 93 then
i += 1
depth -= 1
value = {}
else
stackT[depth], stackK[depth], stackO[depth] = {}, 0, false
haveValue = false
end
elseif c == 34 then
local v, ni, at = str(s, i)
if v == nil then
return nil, ni, at
end
value, i = v, ni
elseif c == 116 then
if sub(s, i, i + 3) ~= "true" then
return nil, "bad literal", i - 1
end
value, i = true, i + 4
elseif c == 102 then
if sub(s, i, i + 4) ~= "false" then
return nil, "bad literal", i - 1
end
value, i = false, i + 5
elseif c == 110 then
if sub(s, i, i + 3) ~= "null" then
return nil, "bad literal", i - 1
end
value, i = nullv, i + 4
elseif c == nil then
return nil, "truncated: expected a value", n
else
local v, ni, at = num(s, i, bigStrings)
if v == nil then
return nil, ni, at
end
value, i = v, ni
end
-- attach the value to the open containers, closing them as their ends come
while haveValue do
if depth == 0 then
return value, i
end
local t = stackT[depth]
local ord = stackO[depth]
if ord then
local k = stackK[depth]
if ord ~= true and t[k] == nil then
table.insert(ord, k)
end
t[k] = value
else
local cnt = stackK[depth] + 1
t[cnt] = value
stackK[depth] = cnt
end
i = match(s, "^[ \t\n\r]*()", i) :: any
c = byte(s, i)
if c == 44 then -- ,
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
if ord then
if byte(s, i) ~= 34 then
return nil, if i > n then "truncated object" else "expected a key", i - 1
end
local k, ni, at = str(s, i)
if k == nil then
return nil, ni, at
end
i = match(s, "^[ \t\n\r]*()", ni) :: any
if byte(s, i) ~= 58 then
return nil, if i > n then "truncated object" else "expected ':'", i - 1
end
i += 1
stackK[depth] = k
end
haveValue = false
elseif ord and c == 125 then
i += 1
value = if ord ~= true then object(t, ord) elseif next(t) == nil then object(t, {}) else t
stackT[depth] = nil
depth -= 1
elseif not ord and c == 93 then
i += 1
value = t
stackT[depth] = nil
depth -= 1
elseif c == nil then
return nil, if ord then "truncated object" else "truncated array", n
else
return nil, if ord then "expected ',' or '}'" else "expected ',' or ']'", i - 1
end
end
end
end
-- events: a pull tokenizer. next() -> event, value | nil at the end | "error", message, offset. Events: "object",
-- "endObject", "array", "endArray", "key" (string), "value" (scalar). The grammar is checked as it goes.
function Decode.events(s: string, i: number, opts: Options?): () -> (string?, any, number?)
local o: Options = opts or {}
local bigStrings = o.bigInts == "string"
local nullv = if o.null ~= nil then o.null else Types.null
local maxDepth = o.maxDepth or 1000
local stack: { boolean } = {} -- true = object
local depth = 0
-- state: "value" (a value expected), "first" (after { or [: value / key or close), "after" (after a value),
-- "key" (a key expected), "done", "dead"
local state = "value"
local n = #s
local function fail(msg: string, at: number): (string, any, number)
state = "dead"
return "error", msg, at
end
return function(): (string?, any, number?)
if state == "dead" then
return nil
end
i = match(s, "^[ \t\n\r]*()", i) :: any
local c = byte(s, i)
if state == "done" then
state = "dead"
if c ~= nil then
return "error", "trailing data", i - 1
end
return nil
end
if state == "after" then
local obj = stack[depth]
if c == 44 then
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
c = byte(s, i)
state = if obj then "key" else "value"
elseif c == (if obj then 125 else 93) then
i += 1
stack[depth] = nil
depth -= 1
state = if depth == 0 then "done" else "after"
return if obj then "endObject" else "endArray", nil
elseif c == nil then
return fail("truncated", n)
else
return fail("expected ',' or a close", i - 1)
end
end
if state == "first" then
local obj = stack[depth]
if c == (if obj then 125 else 93) then
i += 1
stack[depth] = nil
depth -= 1
state = if depth == 0 then "done" else "after"
return if obj then "endObject" else "endArray", nil
end
state = if obj then "key" else "value"
end
if state == "key" then
if c ~= 34 then
return fail(if c == nil then "truncated" else "expected a key", i - 1)
end
local k, ni, at = str(s, i)
if k == nil then
return fail(ni, at :: number)
end
i = match(s, "^[ \t\n\r]*()", ni) :: any
if byte(s, i) ~= 58 then
return fail("expected ':'", i - 1)
end
i += 1
state = "value"
return "key", k
end
-- a value
local after = if depth == 0 then "done" else "after"
if c == 123 or c == 91 then
depth += 1
if depth > maxDepth then
return fail("nested deeper than " .. maxDepth, i - 1)
end
stack[depth] = c == 123
i += 1
state = "first"
return if c == 123 then "object" else "array", nil
elseif c == 34 then
local v, ni, at = str(s, i)
if v == nil then
return fail(ni, at :: number)
end
i = ni
state = after
return "value", v
elseif c == 116 and sub(s, i, i + 3) == "true" then
i += 4
state = after
return "value", true
elseif c == 102 and sub(s, i, i + 4) == "false" then
i += 5
state = after
return "value", false
elseif c == 110 and sub(s, i, i + 3) == "null" then
i += 4
state = after
return "value", nullv
elseif c == nil then
return fail("truncated: expected a value", n)
end
local v, ni, at = num(s, i, bigStrings)
if v == nil then
return fail(ni, at :: number)
end
i = ni
state = after
return "value", v
end
end
return Decode
+310
View File
@@ -0,0 +1,310 @@
--!strict
--!native
-- codecs/Json/Encode: the serializer behind codecs/Json. Compact or pretty (indent), objects in their Types.object key
-- order (plain tables: sorted keys), arrays for tables with keys 1..n, shortest round-trip number text, optional
-- ASCII-only output. Never throws: bad values (cycles, NaN / inf, functions, non-string keys that are not numbers)
-- return nil, message.
local Types = require("@formats/Types")
local Encode = {}
local byte, format, gsub = string.byte, string.format, string.gsub
local floor, huge = math.floor, math.huge
local concat = table.concat
export type Options = {
indent: (number | string)?, -- pretty print: spaces per level (or the indent string); default compact
sortKeys: boolean?, -- plain tables' keys sorted (default true; false = next() order, faster)
ascii: boolean?, -- escape every non-ASCII character as \uXXXX (default false: UTF-8 as is)
nan: ("error" | "null")?, -- NaN / inf: an error (default) or null
emptyTable: ("array" | "object")?, -- what a plain empty table is (default "array"; Types.object() is "{}")
maxDepth: number?, -- nesting limit (default 1000; also catches cycles)
escapeSlash: boolean?, -- write / as \/ (default false)
}
local ESCAPES: { [string]: string } = {
['"'] = '\\"',
["\\"] = "\\\\",
["\b"] = "\\b",
["\f"] = "\\f",
["\n"] = "\\n",
["\r"] = "\\r",
["\t"] = "\\t",
["/"] = "\\/",
}
for c = 0, 31 do
local ch = string.char(c)
if not ESCAPES[ch] then
ESCAPES[ch] = format("\\u%04x", c)
end
end
local function utf16(cp: number): string
if cp < 0x10000 then
return format("\\u%04x", cp)
end
cp -= 0x10000
return format("\\u%04x\\u%04x", 0xD800 + cp // 1024, 0xDC00 + cp % 1024)
end
-- asciify a UTF-8 string's non-ASCII sequences (invalid bytes become \u00XX of the byte: lossy but never throws)
local function asciiSeq(seq: string): string
local out = {}
local i, n = 1, #seq
while i <= n do
local c = byte(seq, i)
local cp, len
if c < 0xC0 then
cp, len = c, 1
elseif c < 0xE0 then
cp, len = (c % 32) * 64 + (byte(seq, i + 1) or 128) % 64, 2
elseif c < 0xF0 then
cp, len = (c % 16) * 4096 + ((byte(seq, i + 1) or 128) % 64) * 64 + (byte(seq, i + 2) or 128) % 64, 3
else
cp, len = (c % 8) * 262144 + ((byte(seq, i + 1) or 128) % 64) * 4096 + ((byte(seq, i + 2) or 128) % 64) * 64 + (byte(seq, i + 3) or 128) % 64, 4
end
table.insert(out, utf16(cp))
i += len
end
return concat(out)
end
-- string(s, ascii, slash) -> the quoted JSON string (ascii: DEL too, like Python's ensure_ascii)
local function quote(s: string, ascii: boolean?, slash: boolean?): string
local pat = if slash then '[%z\1-\31"\\/]' else '[%z\1-\31"\\]'
if string.find(s, pat) then
s = gsub(s, pat, ESCAPES)
end
if ascii and string.find(s, "[\127-\255]") then
s = gsub(s, "\127", "\\u007f")
s = gsub(s, "[\192-\255][\128-\191]*", asciiSeq)
s = gsub(s, "[\128-\191]", asciiSeq)
end
return '"' .. s .. '"'
end
Encode.quote = quote
local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" }
-- number(x) -> the shortest text that reads back as x | nil for NaN / inf
local function number(x: number): string?
if x ~= x or x == huge or x == -huge then
return nil
end
if x == floor(x) and x > -1e15 and x < 1e15 then
if x == 0 and 1 / x < 0 then
return "-0"
end
return format("%d", x)
end
for _, f in FLOAT_FORMATS do
local t = format(f, x)
if tonumber(t) == x then
return t
end
end
return format("%.17g", x)
end
Encode.number = number
local function keyLess(a: any, b: any): boolean
local ta, tb = type(a), type(b)
if ta ~= tb then
return ta == "number"
end
return a < b
end
-- kind(t, emptyObject) -> "array" (keys exactly 1..n) | "object"
local function kind(t: { [any]: any }, emptyObject: boolean): string
if Types.isObject(t) then
return "object"
end
local n = #t
if n == 0 then
if next(t) == nil then
return if emptyObject then "object" else "array"
end
return "object"
end
if next(t, n) ~= nil then
return "object"
end
local count = 0
for _ in next, t do
count += 1
end
return if count == n then "array" else "object"
end
Encode.kind = kind
type State = {
out: { string },
n: number,
indent: string?,
sort: boolean,
ascii: boolean,
slash: boolean,
nanNull: boolean,
emptyObject: boolean,
maxDepth: number,
null: any,
err: string?,
}
local function put(st: State, s: string)
local n = st.n + 1
st.out[n] = s
st.n = n
end
local function value(st: State, v: any, depth: number): boolean
local tv = type(v)
if tv == "string" then
put(st, quote(v, st.ascii, st.slash))
elseif tv == "number" then
local s = number(v)
if not s then
if not st.nanNull then
st.err = "cannot encode " .. tostring(v)
return false
end
s = "null"
end
put(st, s)
elseif tv == "boolean" then
put(st, if v then "true" else "false")
elseif v == nil or v == st.null or v == Types.null then
put(st, "null")
elseif tv == "table" then
if Types.Date.is(v) then
put(st, '"' .. tostring(v) .. '"')
return true
end
if depth >= st.maxDepth then
st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)"
return false
end
local ind = st.indent
local nl, nl2 = "", ""
if ind then
nl = "\n" .. string.rep(ind, depth + 1)
nl2 = "\n" .. string.rep(ind, depth)
end
if kind(v, st.emptyObject) == "array" then
local n = #v
if n == 0 then
put(st, "[]")
return true
end
put(st, "[")
for i = 1, n do
if i > 1 then
put(st, ",")
end
if ind then
put(st, nl)
end
if not value(st, v[i], depth + 1) then
return false
end
end
if ind then
put(st, nl2)
end
put(st, "]")
else
local keys: { any }
if Types.isObject(v) then
keys = Types.keys(v)
else
keys = {}
for k in next, v do
local tk = type(k)
if tk ~= "string" and tk ~= "number" then
st.err = "object key of type " .. tk
return false
end
table.insert(keys, k)
end
if st.sort then
table.sort(keys, keyLess)
end
end
if #keys == 0 then
put(st, "{}")
return true
end
put(st, "{")
local sep = if ind then ": " else ":"
for i, k in keys do
if i > 1 then
put(st, ",")
end
if ind then
put(st, nl)
end
local ks: string
if type(k) == "string" then
ks = k
elseif type(k) == "number" then
ks = number(k) or tostring(k)
else
st.err = "object key of type " .. type(k)
return false
end
put(st, quote(ks, st.ascii, st.slash))
put(st, sep)
if not value(st, v[k], depth + 1) then
return false
end
end
if ind then
put(st, nl2)
end
put(st, "}")
end
elseif tv == "buffer" then
st.err = "cannot encode a buffer (encode it as base64 or an array first)"
return false
else
st.err = "cannot encode a " .. tv
return false
end
return true
end
local function state(opts: Options?, nullv: any?): State
local o: Options = opts or {}
local ind: string? = nil
if type(o.indent) == "number" then
ind = if o.indent > 0 then string.rep(" ", o.indent) else nil
elseif type(o.indent) == "string" then
ind = o.indent
end
return {
out = {},
n = 0,
indent = ind,
sort = o.sortKeys ~= false,
ascii = o.ascii == true,
slash = o.escapeSlash == true,
nanNull = o.nan == "null",
emptyObject = o.emptyTable == "object",
maxDepth = o.maxDepth or 1000,
null = nullv,
err = nil,
}
end
Encode.state = state
Encode.write = value
-- encode(v, opts) -> text | nil, message
function Encode.encode(v: any, opts: Options?, nullv: any?): (string?, string?)
local st = state(opts, nullv)
if not value(st, v, 0) then
return nil, st.err
end
return concat(st.out), nil
end
return Encode
+294
View File
@@ -0,0 +1,294 @@
--!strict
-- codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
-- Values are plain Luau: objects -> tables (string keys), arrays -> arrays, null -> Types.null (opts.null), numbers
-- -> doubles (opts.bigInts = "string" keeps integers past 2^53 as their text). Empty objects are Types.object() so
-- they write back as {}; opts.ordered makes every object a Types.object with its key order.
--
-- local Json = require("@formats/codecs/Json")
-- local v, err = Json.decode('{"a": [1, 2, null]}') -- string | buffer; nil, Err on bad input
-- local s = Json.encode(v, { indent = 2 }) -- string | nil, Err
-- for ev, x in Json.events(text) do ... end -- pull events without building the tree
-- for i, v, err in Json.lines(ndjson) do ... end -- JSON Lines / concatenated JSON values
-- local w = Json.writer({ indent = 2 }); w:beginObject(); w:key("a"); w:value(1); w:endObject(); w:tostring()
--
-- Streaming: decodeAt(src, pos) parses one value and returns where the next begins; events() is a pull tokenizer;
-- writer() builds output incrementally and flush() hands back the text so far. Never throws.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Decode = require("@formats/codecs/Json/Decode")
local Encode = require("@formats/codecs/Json/Encode")
local Json = {}
export type DecodeOptions = Decode.Options
export type EncodeOptions = Encode.Options
Json.null = Types.null
Json.object = Types.object
Json.keys = Types.keys
Json.set = Types.set
local function text(src: any): (string?, Err.Err?)
if type(src) == "string" then
return src, nil
elseif type(src) == "buffer" then
return buffer.tostring(src), nil
end
return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src))
end
local function fail(msg: any, at: any, n: number): Err.Err
local m = tostring(msg)
local code = if string.find(m, "truncated", 1, true) or string.find(m, "unterminated", 1, true) or (at or 0) >= n
then Err.TRUNCATED
elseif string.find(m, "nested deeper", 1, true) then Err.LIMIT
else Err.CORRUPT
return Err.new(code, m, at)
end
-- decode(src, opts?) -> value | nil, Err. One JSON text: a value with optional whitespace around it (a UTF-8 BOM is
-- skipped). Note a JSON null top-level value decodes to opts.null (Types.null by default), never nil.
function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err?)
local s, terr = text(src)
if not s then
return nil, terr
end
local i = if string.sub(s, 1, 3) == "\239\187\191" then 4 else 1
local v, ni, at = Decode.value(s, i, opts)
if v == nil then
return nil, fail(ni, at, #s)
end
local e = string.match(s, "^[ \t\n\r]*()", ni) :: any
if e <= #s then
return nil, Err.new(Err.CORRUPT, "trailing data after the value", e - 1)
end
return v, nil
end
-- decodeAt(src, pos?, opts?) -> value, nextPos | nil, Err. One value starting at pos (1-based, default 1; leading
-- whitespace skipped); nextPos is just past it. nil, nil when only whitespace is left.
function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?): (any, any)
local s, terr = text(src)
if not s then
return nil, terr
end
local i = string.match(s, "^[ \t\n\r]*()", pos or 1) :: any
if i > #s then
return nil, nil
end
local v, ni, at = Decode.value(s, i, opts)
if v == nil then
return nil, fail(ni, at, #s)
end
return v, ni
end
-- lines(src, opts?) -> iterator: index, value (JSON Lines, or any whitespace-separated sequence of JSON values). A
-- bad value gives a last index, nil, Err: for i, v, err in Json.lines(s) do if err then ... end end
function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, any, Err.Err?)
local s, terr = text(src)
local pos = 1
local index = 0
local dead = false
return function(): (number?, any, Err.Err?)
if dead then
return nil
end
index += 1
if not s then
dead = true
return index, nil, terr
end
local v, ni = Json.decodeAt(s, pos, opts)
if v == nil then
dead = true
if ni == nil then
return nil
end
return index, nil, ni
end
pos = ni
return index, v, nil
end
end
-- events(src, opts?) -> iterator: event, value. Events: "object", "endObject", "array", "endArray", "key" (the key),
-- "value" (a scalar), and on bad input one final "error", Err.
function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string?, any)
local s, terr = text(src)
if not s then
local done = false
return function(): (string?, any)
if done then
return nil, nil
end
done = true
return "error", terr
end
end
local str: string = s
local i = if string.sub(str, 1, 3) == "\239\187\191" then 4 else 1
local nextEv = Decode.events(str, i, opts)
return function(): (string?, any)
local ev, v, at = nextEv()
if ev == "error" then
return ev, fail(v, at, #str)
end
return ev, v
end
end
-- encode(value, opts?) -> string | nil, Err
function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?)
local s, msg = Encode.encode(value, opts)
if not s then
return nil, Err.new(Err.ARG, msg or "cannot encode")
end
return s, nil
end
Json.quote = Encode.quote -- quote(s) -> '"..."' with JSON escapes
Json.number = Encode.number -- number(x) -> the shortest round-trip text (nil for NaN / inf)
-- ------------------------------------------------------------------------------------------------ writer
-- writer(opts?) -> a streaming Writer: beginObject / endObject / beginArray / endArray / key(k) / value(v) (any
-- value, encoded whole), then tostring() for everything or flush() for the text since the last flush. Misuse (a key
-- outside an object, a value where a key is due, unbalanced ends) is recorded in w.err and later calls do nothing.
export type Writer = {
err: Err.Err?,
beginObject: (self: Writer) -> Writer,
endObject: (self: Writer) -> Writer,
beginArray: (self: Writer) -> Writer,
endArray: (self: Writer) -> Writer,
key: (self: Writer, k: string) -> Writer,
value: (self: Writer, v: any) -> Writer,
flush: (self: Writer) -> string,
tostring: (self: Writer) -> (string?, Err.Err?),
}
function Json.writer(opts: EncodeOptions?): Writer
local st = Encode.state(opts)
local ind = st.indent
local kinds: { boolean } = {} -- true = object
local counts: { number } = {}
local depth = 0
local keyDone = false -- an object's key written, its value due
local flushed: { string } = {}
local w: any = { err = nil }
local function bad(msg: string)
if not w.err then
w.err = Err.new(Err.ARG, msg)
end
end
-- before an element: a comma / newline as needed; false when the position is wrong
local function slot(isKey: boolean): boolean
if w.err then
return false
end
if depth == 0 then
if counts[0] and counts[0] > 0 then
bad("one top-level value only")
return false
end
counts[0] = 1
return true
end
local obj = kinds[depth]
if obj and not isKey then
if not keyDone then
bad("an object member needs a key first")
return false
end
keyDone = false
return true
end
if isKey and not obj then
bad("key outside an object")
return false
end
if isKey and keyDone then
bad("two keys in a row")
return false
end
if counts[depth] > 0 then
table.insert(st.out, ",")
end
counts[depth] += 1
if ind then
table.insert(st.out, "\n" .. string.rep(ind, depth))
end
return true
end
local function open(obj: boolean)
if slot(false) then
table.insert(st.out, if obj then "{" else "[")
depth += 1
kinds[depth], counts[depth] = obj, 0
end
return w
end
local function close(obj: boolean)
if w.err then
return w
end
if depth == 0 or kinds[depth] ~= obj or (obj and keyDone) then
bad(if obj then "unbalanced endObject" else "unbalanced endArray")
return w
end
if ind and counts[depth] > 0 then
table.insert(st.out, "\n" .. string.rep(ind, depth - 1))
end
table.insert(st.out, if obj then "}" else "]")
depth -= 1
return w
end
function w.beginObject(_self: Writer): Writer
return open(true)
end
function w.beginArray(_self: Writer): Writer
return open(false)
end
function w.endObject(_self: Writer): Writer
return close(true)
end
function w.endArray(_self: Writer): Writer
return close(false)
end
function w.key(_self: Writer, k: string): Writer
if type(k) ~= "string" then
bad("key must be a string")
elseif slot(true) then
table.insert(st.out, Encode.quote(k, st.ascii, st.slash) .. (if ind then ": " else ":"))
keyDone = true
end
return w
end
function w.value(_self: Writer, v: any): Writer
if slot(false) then
st.n = #st.out
if not Encode.write(st, v, depth) then
bad(st.err or "cannot encode")
end
end
return w
end
function w.flush(_self: Writer): string
local s = table.concat(st.out)
table.clear(st.out)
st.n = 0
table.insert(flushed, s)
return s
end
function w.tostring(_self: Writer): (string?, Err.Err?)
if w.err then
return nil, w.err
end
if depth ~= 0 then
return nil, Err.new(Err.ARG, "unclosed object / array")
end
return table.concat(flushed) .. table.concat(st.out), nil
end
return w :: Writer
end
return Json
+771
View File
@@ -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 <?xml ...?> 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 <?xml ...?> declaration
-- "doctype", raw, info raw = the text between "<!DOCTYPE" and ">"; 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 "<!DOCTYPE"): its raw text and info { name, publicId, systemId, entities }; records
-- the internal subset's general entities. nil, message on bad syntax.
local function doctype(): (string?, any)
local start = i
local p = match(s, "^[ \t\n]+()", i) :: any
if not p then
return nil, "bad DOCTYPE"
end
local name = match(s, NAME, p)
if not name then
return nil, "bad DOCTYPE name"
end
local info: any = { name = name, entities = {} }
p += #name
local q = match(s, "^[ \t\n]*()", p) :: any
if q > 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) == "<!--" then
local e = find(s, "--", q + 4, true)
if not e or byte(s, e + 2) ~= 62 then
return nil, if e then "'--' inside a comment" else "unterminated comment in DOCTYPE"
end
q = e + 3
elseif sub(s, q, q + 1) == "<?" then
local target = match(s, NAME, q + 2)
local e = find(s, "?>", q + 2, true)
if not target or not e or lower(target) == "xml" then
return nil, "bad processing instruction in DOCTYPE"
end
q = e + 2
elseif sub(s, q, q + 7) == "<!ENTITY" then
local r = match(s, "^[ \t\n]+()", q + 8) :: any
if not r then
return nil, "bad ENTITY declaration"
end
local isPe = false
if byte(s, r) == 37 then
isPe = true
r = match(s, "^[ \t\n]+()", r + 1) :: any
if not r then
return nil, "bad ENTITY declaration"
end
end
local ename = match(s, NAME, r)
if not ename then
return nil, "bad ENTITY name"
end
r = match(s, "^[ \t\n]+()", r + #ename) :: any
if not r then
return nil, "bad ENTITY declaration"
end
local val, e = literal(r)
if val then
local v = entityValue(val)
if not v then
return nil, "bad ENTITY value"
end
if not isPe and entities[ename] == nil then
entities[ename] = v
info.entities[ename] = v
end
r = e
else
local pub, _, e2 = externalId(r)
if not pub then
return nil, "bad ENTITY declaration"
end
r = e2 :: number
local nd = match(s, "^[ \t\n]+NDATA[ \t\n]+()", r)
if nd then
local nn = match(s, NAME, nd)
if not nn or isPe then
return nil, "bad NDATA"
end
r = nd + #nn
end
if not isPe then
external[ename] = true
end
end
r = match(s, "^[ \t\n]*()", r) :: any
if byte(s, r) ~= 62 then
return nil, "bad ENTITY declaration"
end
q = r + 1
elseif sub(s, q, q + 8) == "<!ELEMENT" or sub(s, q, q + 8) == "<!ATTLIST" or sub(s, q, q + 9) == "<!NOTATION" then
local kw = match(s, "^<!(%u+)", q) :: string
local r = match(s, "^[ \t\n]+()", q + 2 + #kw) :: any
if not r or not match(s, NAME, r) then
return nil, "bad " .. kw .. " declaration"
end
-- skip to the closing '>' outside quotes
while true do
local c2 = byte(s, r)
if c2 == nil then
return nil, "unterminated DOCTYPE"
elseif c2 == 34 or c2 == 39 then
local e = find(s, if c2 == 34 then '"' else "'", r + 1, true)
if not e then
return nil, "unterminated DOCTYPE"
end
r = e + 1
elseif c2 == 62 then
break
elseif c2 == 60 then
return nil, "bad " .. kw .. " declaration"
else
r += 1
end
end
q = r + 1
elseif c == nil then
return nil, "unterminated DOCTYPE"
else
return nil, "bad markup in the DOCTYPE"
end
end
q = match(s, "^[ \t\n]*()", q) :: any
end
if byte(s, q) ~= 62 then
return nil, if q > n then "unterminated DOCTYPE" else "bad DOCTYPE"
end
i = q + 1
return sub(s, start, q - 1), info
end
return function(): (string?, any, any, any)
if dead then
return nil
end
if pending then
local ev = pending
pending = nil
depth -= 1
if depth == 0 then
rootDone = true
end
return "end", ev[1]
end
while true do
if i > n then
dead = true
if depth > 0 then
return "error", "unclosed element <" .. stack[depth] .. ">", n
end
if not rootSeen then
return "error", "no root element", n
end
return nil
end
local c = byte(s, i)
if c ~= 60 then -- text
local e = find(s, "<", i, true) or (n + 1)
local raw = sub(s, i, e - 1)
local start = i
i = e
local wsOnly = not find(raw, "[^ \t\n]")
if depth == 0 then
if not wsOnly then
return fail(if rootDone then "text after the root element" else "text before the root element", start)
end
else
if find(raw, "]]>", 1, true) then
return fail("']]>' in text", start + (find(raw, "]]>", 1, true) :: number) - 1)
end
local bad = find(raw, "[%z\1-\8\11\12\14-\31]")
if bad then
return fail("control character in text", start + bad - 1)
end
if not wsOnly or keepWs or preserve[depth] then
local t = decode(raw, start, 0)
if not t then
return fail(errMsg :: string, errAt)
end
return "text", t
end
end
continue
end
local c2 = byte(s, i + 1)
if c2 == 47 then -- </
local name = match(s, NAME, i + 2)
if not name then
return fail("bad end tag", i)
end
local p = match(s, "^[ \t\n]*()", i + 2 + #name) :: any
if byte(s, p) ~= 62 then
return fail(if p > n then "unterminated end tag" else "bad end tag", p)
end
if depth == 0 or stack[depth] ~= name then
return fail("mismatched end tag </" .. name .. ">" .. (if depth > 0 then " (open: <" .. stack[depth] .. ">)" else ""), i)
end
i = p + 1
stack[depth] = nil
nsStack[depth] = nil
preserve[depth] = nil
depth -= 1
if depth == 0 then
rootDone = true
end
return "end", name
elseif c2 == 33 then -- <!
if sub(s, i + 2, i + 3) == "--" then
local e = find(s, "--", i + 4, true)
if not e then
return fail("unterminated comment", i)
end
if byte(s, e + 2) ~= 62 then
return fail(if e + 2 > n then "unterminated comment" else "'--' inside a comment", e)
end
local text = sub(s, i + 4, e - 1)
i = e + 3
return "comment", text
elseif sub(s, i + 2, i + 8) == "[CDATA[" then
if depth == 0 then
return fail("CDATA outside the root element", i)
end
local e = find(s, "]]>", i + 9, true)
if not e then
return fail("unterminated CDATA section", i)
end
local text = sub(s, i + 9, e - 1)
i = e + 3
return "cdata", text
elseif sub(s, i + 2, i + 8) == "DOCTYPE" then
if rootSeen then
return fail("DOCTYPE after the root element", i)
end
local at = i
i += 9
local raw, info = doctype()
if not raw then
return fail(info, at)
end
return "doctype", raw, info
end
return fail("bad markup declaration", i)
elseif c2 == 63 then -- <?
local target = match(s, NAME, i + 2)
if not target then
return fail("bad processing instruction", i)
end
local e = find(s, "?>", i + 2 + #target, true)
if not e then
return fail("unterminated processing instruction", i)
end
local data = sub(s, i + 2 + #target, e - 1)
if data ~= "" and not find(data, "^[ \t\n]") then
return fail("bad processing instruction", i)
end
data = match(data, "^[ \t\n]*(.-)$") :: string
local at = i
i = e + 2
if lower(target) == "xml" then
if target ~= "xml" or at ~= 1 then
return fail("misplaced XML declaration", at)
end
local decl = xmlDecl(data)
if not decl then
return fail("bad XML declaration", at)
end
return "decl", decl
end
return "pi", target, data
end
-- a start tag
local name = match(s, NAME, i + 1)
if not name then
return fail(if i + 1 > n then "truncated tag" else "bad tag name", i + 1)
end
if rootDone then
return fail("a second root element <" .. name .. ">", i)
end
local at = i
local p = i + 1 + #name
local attrs = Types.object()
local order = {}
local closed = false
local nsMap: { [string]: string }? = nil
while true do
local q = match(s, "^[ \t\n]*()", p) :: any
local cc = byte(s, q)
if cc == 62 then
p = q + 1
break
elseif cc == 47 then
if byte(s, q + 1) ~= 62 then
return fail("bad tag end", q)
end
p = q + 2
closed = true
break
elseif cc == nil then
return fail("truncated tag", q)
end
if q == p then
return fail("missing whitespace between attributes", q)
end
local an = match(s, NAME, q)
if not an then
return fail("bad attribute name", q)
end
local r = match(s, "^[ \t\n]*=[ \t\n]*()", q + #an) :: any
if not r then
return fail("attribute " .. an .. " without a value", q)
end
local qc = byte(s, r)
if qc ~= 34 and qc ~= 39 then
return fail("unquoted attribute value", r)
end
local e = find(s, if qc == 34 then '"' else "'", r + 1, true)
if not e then
return fail("unterminated attribute value", r)
end
local raw = sub(s, r + 1, e - 1)
if find(raw, "<", 1, true) then
return fail("'<' in an attribute value", r)
end
if find(raw, "[%z\1-\8\11\12\14-\31]") then
return fail("control character in an attribute value", r)
end
local v = decode(raw, r + 1, 0)
if not v then
return fail(errMsg :: string, errAt)
end
if find(raw, "[\t\n]") then
-- attribute-value normalization: literal tab / newline become spaces (references stay)
v = decode((gsub(raw, "[\t\n]", " ")), r + 1, 0) :: string
end
if attrs[an] ~= nil then
return fail("duplicate attribute " .. an, q)
end
attrs[an] = v
table.insert(order, an)
if nsOn then
if an == "xmlns" or sub(an, 1, 6) == "xmlns:" then
local m: { [string]: string } = nsMap or {}
nsMap = m
m[if an == "xmlns" then "" else sub(an, 7)] = v
end
end
p = e + 1
end
Types.object(attrs, order)
i = p
depth += 1
if depth > maxDepth then
return fail("nested deeper than " .. maxDepth, at)
end
stack[depth] = name
nsStack[depth] = nsMap :: any
local sp = attrs["xml:space"]
preserve[depth] = if sp == "preserve" then true elseif sp == "default" then false else (preserve[depth - 1] or false)
rootSeen = true
local uri: string? = nil
if nsOn then
local prefix = match(name, "^([^:]*):") or ""
uri = lookupNs(prefix)
if uri == "" then
uri = nil
end
if prefix ~= "" and uri == nil then
return fail("undeclared namespace prefix " .. prefix, at)
end
end
if closed then
stack[depth] = nil
nsStack[depth] = nil
preserve[depth] = nil
pending = { name } -- depth goes down when the queued "end" is returned
end
return "start", name, attrs, uri
end
end
end
-- lookup(nsMaps...) helper for the DOM: the namespace URI of prefix, walking an element's ancestors
function Parse.resolve(node: any, prefix: string): string?
local p = node
local key = if prefix == "" then "xmlns" else "xmlns:" .. prefix
while p do
local a = p.attrs
if a and a[key] ~= nil then
local v = a[key]
return if v == "" then nil else v
end
p = p.parent
end
if prefix == "xml" then
return "http://www.w3.org/XML/1998/namespace"
end
return nil
end
return Parse
+440
View File
@@ -0,0 +1,440 @@
--!strict
-- codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ...
-- use. New code. Supports: UTF-8 / UTF-16 / Latin-1 input, the predefined entities, character references, internal
-- DOCTYPE entities (expansion limited), CDATA, comments, processing instructions, the XML declaration, namespaces
-- (names stay qualified "prefix:local"; opts.namespaces adds each element's URI as node.ns; Xml.clark gives
-- "{uri}local"), xml:space. Not supported: external entities / DTDs, validation, entity values containing markup.
--
-- local Xml = require("@formats/codecs/Xml")
-- local doc, err = Xml.decode(text) -- a "#document" node; doc.root is the root element
-- for _, item in Xml.children(doc.root, "item") do print(item.attrs.id, Xml.text(item)) end
-- for ev, a, b in Xml.events(text) do ... end -- "start" name attrs / "end" name / "text" s / ... (SAX-like)
-- local s = Xml.encode(doc, { indent = 2 })
-- local e = Xml.element("svg", { width = "10" }, { Xml.element("rect") }) -- build trees
--
-- Nodes (Types.XmlNode): { name, attrs (a Types.object: attribute order kept), children = { node | string },
-- parent }. Text children are strings. With opts.comments / opts.cdata / opts.pi, comments, CDATA sections and
-- processing instructions are kept as "#comment" / "#cdata" / "#pi" nodes (text = the content, target = the PI
-- target); otherwise CDATA merges into the text and the others are dropped. Never throws.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Parse = require("@formats/codecs/Xml/Parse")
local Xml = {}
export type Node = Types.XmlNode
export type DecodeOptions = Parse.Options & {
comments: boolean?, -- keep comments as "#comment" nodes (default false)
cdata: boolean?, -- keep CDATA sections as "#cdata" nodes (default false: merged into the text)
pi: boolean?, -- keep processing instructions as "#pi" nodes (default false)
parents: boolean?, -- set node.parent (default true)
}
export type EncodeOptions = {
indent: (number | string)?, -- pretty print elements that hold only elements (default none)
declaration: boolean?, -- write <?xml version="1.0" encoding="UTF-8"?> (default: true for a "#document")
selfClose: boolean?, -- <a/> for empty elements (default true)
}
local find, gsub, sub, match = string.find, string.gsub, string.sub, string.match
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 errCode(msg: string, at: number, n: number): string
if find(msg, "unterminated", 1, true) or find(msg, "truncated", 1, true) or find(msg, "unclosed", 1, true) or at >= n then
return Err.TRUNCATED
elseif find(msg, "over the limit", 1, true) or find(msg, "nested deeper", 1, true) then
return Err.LIMIT
elseif find(msg, "not supported", 1, true) or find(msg, "unsupported", 1, true) then
return Err.UNSUPPORTED
end
return Err.CORRUPT
end
-- events(src, opts?) -> iterator: event, a, b, c (see codecs/Xml/Parse: "decl", "doctype", "start" name attrs ns,
-- "end" name, "text" s, "cdata" s, "comment" s, "pi" target data, and on bad input "error" Err as the last event)
function Xml.events(src: string | buffer, opts: Parse.Options?): () -> (string?, any, any, any)
local s, terr = text(src)
local u, enc = nil, ""
if s then
u, enc = Parse.toUtf8(s)
end
if not u then
local e = terr or Err.new(if find(enc, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT, enc)
local done = false
return function(): (string?, any, any, any)
if done then
return nil
end
done = true
return "error", e
end
end
local str: string = u
local nextEv = Parse.events(str, opts)
return function(): (string?, any, any, any)
local ev, a, b, c = nextEv()
if ev == "error" then
return ev, Err.new(errCode(a, b, #str), a, b)
end
return ev, a, b, c
end
end
-- decode(src, opts?) -> the "#document" node | nil, Err. doc.root = the root element; doc.declaration = { version,
-- encoding, standalone }?; doc.doctype = { raw, name, publicId, systemId, entities }?; doc.children = the root plus
-- any kept comments / PIs around it.
function Xml.decode(src: string | buffer, opts: DecodeOptions?): (Node?, Err.Err?)
local o: DecodeOptions = opts or {}
local keepComments, keepCdata, keepPi = o.comments == true, o.cdata == true, o.pi == true
local parents = o.parents ~= false
local doc: any = { name = "#document", attrs = Types.object(), children = {}, parent = nil }
local cur: any = doc
local stack = { doc }
local depth = 1
for ev, a, b, c in Xml.events(src, o) do
if ev == "start" then
local node: any = { name = a, attrs = b, children = {}, parent = if parents then cur else nil }
if c then
node.ns = c
end
table.insert(cur.children, node)
depth += 1
stack[depth] = node
cur = node
if depth == 2 then
doc.root = node
end
elseif ev == "end" then
stack[depth] = nil
depth -= 1
cur = stack[depth]
elseif ev == "text" or (ev == "cdata" and not keepCdata) then
local ch = cur.children
local last = #ch
if last > 0 and type(ch[last]) == "string" then
ch[last] ..= a
else
ch[last + 1] = a
end
elseif ev == "cdata" then
table.insert(cur.children, { name = "#cdata", attrs = Types.object(), children = {}, text = a, parent = if parents then cur else nil })
elseif ev == "comment" then
if keepComments then
table.insert(cur.children, { name = "#comment", attrs = Types.object(), children = {}, text = a, parent = if parents then cur else nil })
end
elseif ev == "pi" then
if keepPi then
table.insert(cur.children, { name = "#pi", attrs = Types.object(), children = {}, target = a, text = b, parent = if parents then cur else nil })
end
elseif ev == "decl" then
doc.declaration = a
elseif ev == "doctype" then
doc.doctype = { raw = a, name = b.name, publicId = b.publicId, systemId = b.systemId, entities = b.entities }
elseif ev == "error" then
return nil, a
end
end
return doc, nil
end
-- ------------------------------------------------------------------------------------------------ tree helpers
-- element(name, attrs?, children?) -> a new element (attrs: a plain table (written sorted) or a Types.object;
-- children: nodes or strings; their parent is set)
function Xml.element(name: string, attrs: { [string]: string }?, children: { any }?): Node
local a = attrs or Types.object()
if not Types.isObject(a) then
local keys = {}
for k in next, a do
table.insert(keys, k)
end
table.sort(keys)
a = Types.object(a, keys)
end
local node: any = { name = name, attrs = a, children = children or {} }
for _, ch in node.children do
if type(ch) == "table" then
ch.parent = node
end
end
return node
end
-- document(root, declaration?) -> a "#document" node around root
function Xml.document(root: Node, declaration: { [string]: string }?): Node
local doc: any = { name = "#document", attrs = Types.object(), children = { root }, root = root, declaration = declaration }
root.parent = doc
return doc
end
-- append(parent, child) -> child (a node or a string), parent link set
function Xml.append(parent: Node, child: any): any
table.insert(parent.children, child)
if type(child) == "table" then
child.parent = parent
end
return child
end
-- setAttr(node, name, value): set (or with nil remove) an attribute, keeping the order
function Xml.setAttr(node: Node, name: string, value: string?)
Types.set(node.attrs, name, value)
end
-- children(node, name?) -> the element children (with that qualified name, or local name when name has no prefix and
-- the child's does), in order
function Xml.children(node: Node, name: string?): { Node }
local out = {}
for _, ch in node.children do
if type(ch) == "table" and string.byte(ch.name) ~= 35 then
if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then
table.insert(out, ch)
end
end
end
return out
end
-- child(node, name?) -> the first matching element child, or nil
function Xml.child(node: Node, name: string?): Node?
for _, ch in node.children do
if type(ch) == "table" and string.byte(ch.name) ~= 35 then
if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then
return ch
end
end
end
return nil
end
-- descendants(node, name?) -> every element below node (document order), optionally filtered as children() does
function Xml.descendants(node: Node, name: string?): { Node }
local out = {}
local function walk(n: Node)
for _, ch in n.children do
if type(ch) == "table" and string.byte(ch.name) ~= 35 then
if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then
table.insert(out, ch)
end
walk(ch)
end
end
end
walk(node)
return out
end
-- text(node) -> all the character data below node, concatenated (CDATA included, comments / PIs not)
function Xml.text(node: any): string
if type(node) == "string" then
return node
end
if node.name == "#cdata" then
return node.text or ""
end
local parts = {}
local function walk(n: any)
for _, ch in n.children do
if type(ch) == "string" then
table.insert(parts, ch)
elseif ch.name == "#cdata" then
table.insert(parts, ch.text or "")
elseif string.byte(ch.name) ~= 35 then
walk(ch)
end
end
end
walk(node)
return table.concat(parts)
end
-- prefix(name) / localName(name): the parts of a qualified name ("svg:rect" -> "svg", "rect"; "rect" -> "", "rect")
function Xml.prefix(name: string): string
return match(name, "^([^:]*):") or ""
end
function Xml.localName(name: string): string
return match(name, ":(.*)$") or name
end
-- namespace(node, prefix?) -> the URI bound to prefix (default: the node's own prefix) at node, through its
-- ancestors' xmlns attributes (needs parent links)
function Xml.namespace(node: Node, prefix: string?): string?
return Parse.resolve(node, prefix or Xml.prefix(node.name))
end
-- clark(node, attrName?) -> "{uri}local" (ElementTree's notation) for the element, or for one of its attributes
-- (unprefixed attributes have no namespace)
function Xml.clark(node: Node, attrName: string?): string
local name = attrName or node.name
local prefix = Xml.prefix(name)
if attrName and prefix == "" then
return name
end
local uri = Parse.resolve(node, prefix)
if uri then
return "{" .. uri .. "}" .. Xml.localName(name)
end
return name
end
-- ------------------------------------------------------------------------------------------------ encode
local TEXT_ESC = { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ["\r"] = "&#13;" }
local ATTR_ESC = { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;", ["\t"] = "&#9;", ["\n"] = "&#10;", ["\r"] = "&#13;" }
-- escape(s) / escapeAttr(s): text / attribute-value escaping
function Xml.escape(s: string): string
return (gsub(s, "[&<>\r]", TEXT_ESC))
end
function Xml.escapeAttr(s: string): string
return (gsub(s, '[&<>"\t\n\r]', ATTR_ESC))
end
local function badName(name: any): boolean
return type(name) ~= "string" or not match(name, "^[%a_:\128-\255][%w_:%.%-\128-\255]*$")
end
-- encode(node, opts?) -> string | nil, Err. node: a "#document" or any node (an element, a comment, ...)
function Xml.encode(node: Node, opts: EncodeOptions?): (string?, Err.Err?)
local o: EncodeOptions = 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
local selfClose = o.selfClose ~= false
local out: { string } = {}
local err: string? = nil
local seen: { [any]: boolean } = {}
local write: (n: any, depth: number) -> ()
function write(n: any, depth: number)
if err then
return
end
if type(n) == "string" then
table.insert(out, Xml.escape(n))
return
end
if type(n) ~= "table" or type(n.name) ~= "string" then
err = "a child is not a node or a string"
return
end
if seen[n] then
err = "a node appears twice (a cycle?)"
return
end
seen[n] = true
local name = n.name
if name == "#comment" then
local t = n.text or ""
if find(t, "--", 1, true) or sub(t, -1) == "-" then
err = "comment text contains '--'"
return
end
table.insert(out, "<!--" .. t .. "-->")
elseif name == "#cdata" then
table.insert(out, "<![CDATA[" .. gsub(n.text or "", "]]>", "]]]]><![CDATA[>") .. "]]>")
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, "<?" .. n.target .. (if n.text and n.text ~= "" then " " .. n.text else "") .. "?>")
elseif name == "#doctype" then
table.insert(out, "<!DOCTYPE" .. (n.text or "") .. ">")
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 "></" .. name .. ">")
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, "</" .. name .. ">")
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, '<?xml version="' .. (d.version or "1.0") .. '" encoding="UTF-8"' .. (if d.standalone then ' standalone="' .. d.standalone .. '"' else "") .. "?>")
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, "<!DOCTYPE" .. raw .. ">\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
+88
View File
@@ -0,0 +1,88 @@
--!strict
-- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/Json (which see for the value mapping and options).
-- Supports: decode to plain Luau values (Types.null, ordered keys and bigInts as strings by option), encode compact or
-- pretty. JSON Lines through codecs/Json.lines. Not supported: JSON5 / comments / trailing commas.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Json = require("@formats/codecs/Json")
-- ------------------------------------------------------------------------------------------------ contract
local JsonFormat = {
name = "json",
category = "data",
extensions = { "json", "jsonl", "ndjson", "geojson" },
mime = { "application/json", "application/x-ndjson" },
deps = { "core/Err", "core/Bytes", "codecs/Json" },
caps = { decode = true, encode = true, ordered = true, streaming = true },
}
export type DecodeOptions = Json.DecodeOptions & {
lines: boolean?, -- JSON Lines: decode every value into an array (default false: one value)
}
export type EncodeOptions = Json.EncodeOptions & {
lines: boolean?, -- JSON Lines: the value must be an array, written one compact value per line
}
-- ------------------------------------------------------------------------------------------------ sniff
function JsonFormat.sniff(r: Bytes.Reader): number
local head = r:peek(64)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
local first = string.match(head, "^[ \t\r\n]*(.)")
if first == "{" then
local nxt = string.match(head, "^[^{]*{[ \t\r\n]*(.)")
return if nxt == nil or nxt == '"' or nxt == "}" then 0.6 else 0.1
elseif first == "[" then
return 0.3
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function JsonFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
if opts and opts.lines then
local out = {}
for _, v, err in Json.lines(s, opts) do
if err then
return nil, err
end
table.insert(out, v)
end
return out, nil
end
return Json.decode(s, opts)
end
-- ------------------------------------------------------------------------------------------------ encode
function JsonFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
if opts and opts.lines then
if type(value) ~= "table" then
return nil, Err.new(Err.ARG, "lines: expected an array of values")
end
local o = table.clone(opts) :: any
o.indent = nil
local parts = {}
for i, v in value do
local s, err = Json.encode(v, o)
if not s then
return nil, err
end
parts[i] = s .. "\n"
end
return buffer.fromstring(table.concat(parts)), nil
end
local s, err = Json.encode(value, opts)
if not s then
return nil, err
end
if opts and opts.indent then
s ..= "\n"
end
return buffer.fromstring(s), nil
end
return JsonFormat
+57
View File
@@ -0,0 +1,57 @@
--!strict
-- data/xml: XML 1.0 files, a thin wrapper over codecs/Xml (which see for the node shape and options). Supports:
-- decode to a "#document" XmlNode tree (doc.root = the root element), encode a document or an element. Not
-- supported: external entities / DTDs, validation.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Xml = require("@formats/codecs/Xml")
-- ------------------------------------------------------------------------------------------------ contract
local XmlFormat = {
name = "xml",
category = "data",
extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" },
mime = { "application/xml", "text/xml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml" },
caps = { decode = true, encode = true, namespaces = true, streaming = true },
}
export type DecodeOptions = Xml.DecodeOptions
export type EncodeOptions = Xml.EncodeOptions
-- ------------------------------------------------------------------------------------------------ sniff
function XmlFormat.sniff(r: Bytes.Reader): number
local head = r:peek(64)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
if string.match(head, "^<%?xml[ \t\r\n]") or string.sub(head, 1, 4) == "\255\254<\0" or string.sub(head, 1, 4) == "\254\255\0<" then
return 0.5
end
if string.match(head, "^[ \t\r\n]*<[%a!]") then
return 0.3
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function XmlFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.XmlNode?, Err.Err?)
return Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), opts)
end
-- ------------------------------------------------------------------------------------------------ encode
function XmlFormat.encode(node: Types.XmlNode, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(node) ~= "table" or type(node.name) ~= "string" then
return nil, Err.new(Err.ARG, "expected an XmlNode")
end
local s, err = Xml.encode(node, opts)
if not s then
return nil, err
end
return buffer.fromstring(s), nil
end
return XmlFormat
+210
View File
@@ -0,0 +1,210 @@
-- codecs/Json tests: the JSONTestSuite parsing corpus (y_ must parse to Python's value, n_ must fail, i_ must not
-- throw), Python json.dumps output in four styles parsed and reproduced byte for byte (compact sorted, ordered,
-- indent 2, ensure_ascii), events / lines / decodeAt / writer, options, error codes, and the fuzz pass.
-- Fixtures: tools/fixtures/json.py.
local T = require("@tests/T")
local Json = require("@formats/codecs/Json")
local Types = require("@formats/Types")
local Err = require("@formats/core/Err")
local Canon = require("@tests/data/Canon")
local Suite = require("@tests/gen/json_suite")
local Corpus = require("@tests/gen/json_corpus")
local t = T.suite("json")
-- events() rebuilt into a value (checks the pull tokenizer agrees with decode)
local function fromEvents(s: string): (any, any)
local stack, keys = {}, {}
local top: any = nil
local key: any = nil
local function add(v: any)
local cur = stack[#stack]
if cur == nil then
top = v
elseif keys[#stack] ~= false then
cur[key] = v
else
table.insert(cur, v)
end
end
for ev, v in Json.events(s) do
if ev == "error" then
return nil, v
elseif ev == "object" or ev == "array" then
local tbl = if ev == "object" then Types.object() else {}
add(tbl)
table.insert(stack, tbl)
keys[#stack] = if ev == "object" then true else false
elseif ev == "endObject" or ev == "endArray" then
keys[#stack] = nil
table.remove(stack)
elseif ev == "key" then
key = v
else
add(v)
end
end
return top, nil
end
-- 1. JSONTestSuite
local counts = { y = 0, n = 0, i = 0, iok = 0 }
for _, c in Suite do
local v, err = Json.decode(c.data)
local ev, everr = fromEvents(c.data)
if c.expect == "y" then
t:check(v ~= nil, c.name .. ": parses (" .. tostring(err) .. ")")
t:eq(Canon.of(v), c.canon, c.name .. ": value")
t:check(ev ~= nil, c.name .. ": events parse (" .. tostring(everr) .. ")")
t:eq(Canon.of(ev), c.canon, c.name .. ": events value")
-- and our output reads back the same
local s = Json.encode(v)
t:check(s ~= nil, c.name .. ": encodes")
t:eq(Canon.of(Json.decode(s :: string)), c.canon, c.name .. ": round trip")
elseif c.expect == "n" then
t:check(v == nil and Err.is(err), c.name .. ": rejected")
t:check(ev == nil, c.name .. ": events reject")
else
counts.iok += if v ~= nil then 1 else 0
end
counts[c.expect] += 1
end
t:note("JSONTestSuite: %d y_ accepted, %d n_ rejected, %d of %d i_ accepted", counts.y, counts.n, counts.iok, counts.i)
-- 2. Python's json.dumps output: parse, compare, re-encode byte for byte
for i, c in Corpus do
local v, err = Json.decode(c.compact)
t:check(v ~= nil, "corpus " .. i .. ": " .. tostring(err))
t:eq(Canon.of(v), c.canon, "corpus " .. i .. ": value")
t:eq(Json.encode(v), c.compact, "corpus " .. i .. ": compact text")
t:eq(Json.encode(v, { indent = 2 }), c.pretty, "corpus " .. i .. ": indent 2 text")
t:eq(Json.encode(v, { ascii = true }), c.ascii, "corpus " .. i .. ": ensure_ascii text")
local o = Json.decode(c.ordered, { ordered = true })
t:eq(Json.encode(o), c.ordered, "corpus " .. i .. ": ordered text")
t:eq(Canon.of(Json.decode(c.ascii)), c.canon, "corpus " .. i .. ": ascii parse")
t:eq(Canon.of(Json.decode(c.pretty)), c.canon, "corpus " .. i .. ": pretty parse")
end
-- 3. options and API
do
local v = Json.decode('[12345678901234567890, -9007199254740993, 9007199254740991, 1.5e300]', { bigInts = "string" })
t:eq(v[1], "12345678901234567890", "bigInts string")
t:eq(v[2], "-9007199254740993", "bigInts negative")
t:eq(v[3], 9007199254740991, "2^53 - 1 stays a number")
t:eq(v[4], 1.5e300, "floats stay numbers")
t:eq(Json.decode("[null]", { null = false })[1], false, "opts.null")
t:eq(Json.decode("null"), Types.null, "top-level null")
t:eq(Json.decode("\239\187\191[1]")[1], 1, "BOM skipped")
t:eq(Json.decode(buffer.fromstring(" 7 ")), 7, "buffer input")
local e = Json.decode('{"b":1,"a":{},"c":[]}')
t:eq(Json.encode(e), '{"a":{},"b":1,"c":[]}', "empty object stays an object")
local o = Json.decode('{"z":1,"a":2,"m":{"y":1,"b":2}}', { ordered = true })
t:eq(Json.encode(o), '{"z":1,"a":2,"m":{"y":1,"b":2}}', "ordered keys")
Types.set(o, "b", 3)
o.a = nil
t:eq(Json.encode(o), '{"z":1,"m":{"y":1,"b":2},"b":3}', "ordered set / remove")
t:eq(Json.encode({}, { emptyTable = "object" }), "{}", "emptyTable object")
t:eq(Json.encode({ [1] = "a", [3] = "c" }), '{"1":"a","3":"c"}', "sparse array -> object")
t:eq(Json.encode({ 1, 2, x = 1 }), '{"1":1,"2":2,"x":1}', "mixed table -> object")
t:eq(Json.encode("a/b", { escapeSlash = true }), '"a\\/b"', "escapeSlash")
t:eq(Json.encode(0 / 0, { nan = "null" }), "null", "nan null")
local _, ne = Json.encode(math.huge)
t:eq(ne and ne.code, Err.ARG, "inf is an error")
local cyc = {}
cyc.self = cyc
local _, ce = Json.encode(cyc)
t:eq(ce and ce.code, Err.ARG, "cycle is an error")
local _, fe = Json.encode({ f = print })
t:eq(fe and fe.code, Err.ARG, "function is an error")
t:eq(Json.encode(Types.Date.parse("1979-05-27T07:32:00Z")), '"1979-05-27T07:32:00Z"', "dates as strings")
for _, x in { 0.1, 1 / 3, -2.5e-8, 1e300, 123456789012345, 2 ^ 53, 5e-324, 1.7976931348623157e308 } do
t:eq(Json.decode(Json.encode(x) :: string), x, "number round trip " .. string.format("%.17g", x))
end
end
-- 4. streaming: lines, decodeAt, writer
do
local got = {}
for _, v in Json.lines('{"a":1}\n[2]\n"x"\n 3 ') do
table.insert(got, (Json.encode(v)))
end
t:eq(table.concat(got, "|"), '{"a":1}|[2]|"x"|3', "lines")
local n, last = 0, nil
for _, v, e in Json.lines("1 2 [") do
if e then
last = e
else
n += 1
end
end
t:eq(n, 2, "lines stop at the bad value")
t:eq(last and last.code, Err.TRUNCATED, "lines report the error")
local v, p = Json.decodeAt("[1] [2]", 1)
t:eq(v[1], 1, "decodeAt value")
t:eq(p, 4, "decodeAt next")
t:eq(Json.decodeAt(" ", 1), nil, "decodeAt at the end")
local w = Json.writer({ indent = 2 })
w:beginObject():key("a"):value({ 1, 2 }):key("b"):beginArray():value("x"):beginObject():endObject():endArray():endObject()
local s = w:tostring()
t:eq(s, Json.encode(Json.decode('{"a":[1,2],"b":["x",{}]}', { ordered = true }), { indent = 2 }), "writer pretty")
local w2 = Json.writer()
w2:beginArray()
local parts = {}
for i = 1, 5 do
w2:value(i)
table.insert(parts, w2:flush())
end
w2:endArray()
table.insert(parts, w2:flush())
t:eq(table.concat(parts), "[1,2,3,4,5]", "writer flush chunks")
t:eq(w2:tostring(), "[1,2,3,4,5]", "writer tostring after flushes")
local w3 = Json.writer()
w3:beginArray():key("x")
t:check(w3.err ~= nil, "writer: key in array")
local w4 = Json.writer()
w4:beginObject():value(1)
t:check(w4.err ~= nil, "writer: value without key")
local w5 = Json.writer()
w5:beginObject()
t:check(w5:tostring() == nil, "writer: unclosed")
end
-- 5. errors
local function code(s: string, opts: any?): string?
local _, e = Json.decode(s, opts)
return e and e.code
end
t:eq(code('{"a":'), Err.TRUNCATED, "truncated object")
t:eq(code('"abc'), Err.TRUNCATED, "truncated string")
t:eq(code("[1 2]"), Err.CORRUPT, "missing comma")
t:eq(code("[1] x"), Err.CORRUPT, "trailing data")
t:eq(code(string.rep("[", 50) .. string.rep("]", 50), { maxDepth = 10 }), Err.LIMIT, "maxDepth")
t:eq(code(string.rep("[", 100000)), Err.LIMIT, "100000 opening brackets")
t:eq(code(""), Err.TRUNCATED, "empty input")
local _, ae = Json.decode(42 :: any)
t:eq(ae and ae.code, Err.ARG, "bad argument")
do
local _, e = Json.decode('{"a": tru}')
t:eq(e and e.offset, 6, "error offset")
end
-- 6. fuzz
local samples = {}
for i = 1, 40 do
table.insert(samples, Corpus[i].compact)
end
for _, c in Suite do
if #samples < 120 and c.expect == "y" and #c.data < 200 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
return Json.decode(b)
end, samples)
t:fuzz("events", function(b: buffer)
for _ in Json.events(b) do
end
return nil
end, samples, { garbage = 50 })
t:done()
+197
View File
@@ -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 = '<?xml version="1.0"?>\n<!DOCTYPE r [<!ENTITY e "E&#38;#38;">]>\n<!--c--><r xmlns="urn:d" xmlns:p="urn:p" z="1" a="2"><p:x p:k="v">t<![CDATA[<c>]]>u</p:x><?go now?><y/>\n</r>'
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&#38;", "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), "t<c>u", "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("<a>&e;</a>") == nil, true, "undefined entity")
local d2 = Xml.decode('<!DOCTYPE r [<!ENTITY e "E&#38;#38;">]><r a="&e;">&e;</r>') :: 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("<a>\n <b> x </b>\n <c xml:space='preserve'> </c>\n</a>") :: 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("<a>\n <b/>\n</a>", { whitespace = true }) :: any).root.children, 3, "opts.whitespace")
-- attribute normalization and line endings
local n = Xml.decode("<a b='x\ty\r\nz&#10;'>l1\r\nl2\rl3</a>") :: 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" }), "a<b & \"c\"" })
Xml.setAttr(e, "id", "q\"\n")
t:eq(Xml.encode(e), '<svg height="5" width="10" id="q&quot;&#10;"><rect x="1"/>a&lt;b &amp; "c"</svg>', "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 }), '<?xml version="1.0" encoding="UTF-8"?>\n<r>\n <a/>\n <b>t</b>\n</r>\n', "pretty document")
t:eq(Xml.encode(Xml.element("a"), { selfClose = false }), "<a></a>", "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), "<![CDATA[a]]]]><![CDATA[>b]]>", "cdata split")
-- events
local evs = {}
for ev, a in Xml.events("<a x='1'><b>t</b><!--c--></a>") 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("<a><b></a>") 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("<?xml version='1.0' encoding='EBCDIC'?><a/>")
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("<a><b>"), Err.TRUNCATED, "unclosed")
t:eq(code("<a></b>"), Err.CORRUPT, "mismatch")
t:eq(code("<a b='1' b='2'/>"), Err.CORRUPT, "duplicate attribute")
t:eq(code(string.rep("<a>", 60) .. string.rep("</a>", 60), { maxDepth = 50 }), Err.LIMIT, "maxDepth")
t:eq(code('<!DOCTYPE r [<!ENTITY a "aaaaaaaaaa"><!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;"><!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;"><!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;"><!ENTITY e "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">]><r>&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;</r>', { maxExpansion = 100000 }), Err.LIMIT, "billion laughs")
t:eq(code('<!DOCTYPE r [<!ENTITY a "&a;">]><r>&a;</r>'), Err.CORRUPT, "recursive entity")
t:eq(code('<!DOCTYPE r [<!ENTITY x SYSTEM "file.xml">]><r>&x;</r>'), Err.UNSUPPORTED, "external entity")
t:eq(code("<p:a/>", { 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()
+86
View File
@@ -0,0 +1,86 @@
-- tests/data/Canon: the canonical text of a decoded data value, the same as tools/fixtures/_data_common.py canon() on
-- Python's parse: null n, true t, false f, numbers #%d (integral under 2^53) or #%.17g, strings s<len>:<bytes>,
-- buffers b<len>:<bytes>, arrays [x,...], objects {k=v,...} sorted by key text, dates d<rfc3339>. A module the data
-- tests require (running it alone does nothing).
local Types = require("@formats/Types")
local Canon = {}
local function num(x: number): string
if x ~= x then
return "#nan"
elseif x == math.huge then
return "#inf"
elseif x == -math.huge then
return "#-inf"
elseif x == math.floor(x) and math.abs(x) < 2 ^ 53 then
return string.format("#%d", x)
end
return "#" .. string.format("%.17g", x)
end
local function isArray(t: { [any]: any }): boolean
if Types.isObject(t) then
return false
end
local n = #t
local c = 0
for _ in next, t do
c += 1
end
return c == n
end
local function canon(v: any, out: { string })
local tv = type(v)
if v == Types.null then
table.insert(out, "n")
elseif tv == "boolean" then
table.insert(out, if v then "t" else "f")
elseif tv == "number" then
table.insert(out, num(v))
elseif tv == "string" then
table.insert(out, "s" .. #v .. ":" .. v)
elseif tv == "buffer" then
table.insert(out, "b" .. buffer.len(v) .. ":" .. buffer.tostring(v))
elseif tv == "table" and Types.Date.is(v) then
table.insert(out, "d" .. tostring(v))
elseif tv == "table" then
if isArray(v) then
table.insert(out, "[")
for i = 1, #v do
canon(v[i], out)
table.insert(out, ",")
end
table.insert(out, "]")
else
local items = {}
for k, x in next, v do
local ko = {}
canon(k, ko)
table.insert(items, { table.concat(ko), x })
end
table.sort(items, function(a, b)
return a[1] < b[1]
end)
table.insert(out, "{")
for _, it in items do
table.insert(out, it[1] .. "=")
canon(it[2], out)
table.insert(out, ",")
end
table.insert(out, "}")
end
else
table.insert(out, "?" .. tv)
end
end
-- of(v) -> the canonical text
function Canon.of(v: any): string
local out = {}
canon(v, out)
return table.concat(out)
end
return Canon
+71
View File
@@ -0,0 +1,71 @@
-- data/json tests: the contract, the format through the API (F.load / F.save / sniffing), JSON Lines, Python's
-- json.dumps corpus through the format, and the fuzz pass. The codec itself is tested in tests/codecs/json.luau.
-- Fixtures: tools/fixtures/json.py.
local T = require("@tests/T")
local F = require("@formats")
local JsonF = require("@formats/data/json")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Canon = require("@tests/data/Canon")
local Corpus = require("@tests/gen/json_corpus")
local t = T.suite("data/json")
t:eq(JsonF.name, "json", "name")
t:eq(JsonF.category, "data", "category")
t:check(JsonF.caps.decode and JsonF.caps.encode, "caps")
local function dec(s: string, opts: any?): (any, any)
return JsonF.decode(Bytes.reader(buffer.fromstring(s)), opts)
end
for i, c in Corpus do
local v, err = dec(c.pretty)
t:check(v ~= nil, "corpus " .. i .. ": " .. tostring(err))
t:eq(Canon.of(v), c.canon, "corpus " .. i)
local b = JsonF.encode(v, { indent = 2 }) :: buffer
t:eq(buffer.tostring(b), c.pretty .. "\n", "corpus " .. i .. ": encode")
end
-- through the API: sniffed, by name, saved
do
local v, err = F.load(buffer.fromstring('{"a": [1, 2], "b": null}'))
t:check(v ~= nil, "F.load sniffs json: " .. tostring(err))
t:eq(v.b, F.null, "F.null")
local v2 = F.load(buffer.fromstring("[1, 2]"), { format = "json" })
t:eq(v2[2], 2, "F.load format = json")
local s = F.saveString({ x = 1, y = { true, false } }, { format = "json" })
t:eq(s, '{"x":1,"y":[true,false]}', "F.saveString json")
local back = F.data.load(buffer.fromstring(s :: string), { format = "json" })
t:eq(back.y[1], true, "F.data.load")
end
-- JSON Lines
do
local v = dec('{"a":1}\n{"a":2}\n\n[3]\n', { lines = true })
t:eq(#v, 3, "lines decode count")
t:eq(v[2].a, 2, "lines decode value")
local b = JsonF.encode({ { a = 1 }, { 2, 3 } }, { lines = true }) :: buffer
t:eq(buffer.tostring(b), '{"a":1}\n[2,3]\n', "lines encode")
local _, e = dec("1\n[", { lines = true })
t:eq(e and e.code, Err.TRUNCATED, "lines error")
end
-- reader range: the data inside a bigger buffer
do
local big = buffer.fromstring("xx[1,2,3]yy")
local v = JsonF.decode(Bytes.reader(big, 2, 7))
t:eq(#v, 3, "reader range")
end
t:eq(JsonF.sniff(Bytes.reader(buffer.fromstring(' {"a":1}'))), 0.6, "sniff object")
t:eq(JsonF.sniff(Bytes.reader(buffer.fromstring("hello"))), 0, "sniff text")
local samples = {}
for i = 1, 30 do
table.insert(samples, Corpus[i].pretty)
end
t:fuzz("decode", function(b: buffer)
return JsonF.decode(Bytes.reader(b))
end, samples)
t:done()
+49
View File
@@ -0,0 +1,49 @@
-- data/xml tests: the contract, the format through the API (F.load / F.save / sniffing), documents from Python's
-- ElementTree fixtures decoded and re-encoded through the format, and the fuzz pass. The codec itself is tested in
-- tests/codecs/xml.luau. Fixtures: tools/fixtures/xml.py.
local T = require("@tests/T")
local F = require("@formats")
local XmlF = require("@formats/data/xml")
local Xml = require("@formats/codecs/Xml")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Docs = require("@tests/gen/xml_docs")
local t = T.suite("data/xml")
t:eq(XmlF.name, "xml", "name")
t:eq(XmlF.category, "data", "category")
t:check(XmlF.caps.decode and XmlF.caps.encode, "caps")
for i = 1, 60 do
local d = Docs[i]
local doc, err = XmlF.decode(Bytes.reader(buffer.fromstring(d.data)), { comments = true, cdata = true, whitespace = true })
t:check(doc ~= nil, "doc " .. i .. ": " .. tostring(err))
local b, eerr = XmlF.encode(doc :: any)
t:check(b ~= nil, "doc " .. i .. ": encode " .. tostring(eerr))
local again = XmlF.decode(Bytes.reader(b :: buffer), { comments = true, cdata = true, whitespace = true })
t:check(again ~= nil, "doc " .. i .. ": re-decode")
t:eq(Xml.text((again :: any).root), Xml.text((doc :: any).root), "doc " .. i .. ": same text")
end
do
local doc, err = F.load(buffer.fromstring('<?xml version="1.0"?><r><a k="v">t</a></r>'))
t:check(doc ~= nil, "F.load sniffs xml: " .. tostring(err))
t:eq(doc.root.name, "r", "root")
local s = F.saveString(doc, { format = "xml" })
t:eq(s, '<?xml version="1.0" encoding="UTF-8"?>\n<r><a k="v">t</a></r>', "F.saveString")
local _, e = XmlF.encode(5 :: any)
t:eq(e and e.code, Err.ARG, "encode argument check")
local _, e2 = F.load(buffer.fromstring("<r><a></r>"), { format = "xml" })
t:eq(e2 and e2.code, Err.CORRUPT, "error through the API")
t:eq(e2 and e2.format, "xml", "error tagged with the format")
end
local samples = {}
for i = 1, 30 do
table.insert(samples, Docs[i].data)
end
t:fuzz("decode", function(b: buffer)
return XmlF.decode(Bytes.reader(b))
end, samples)
t:done()
+30
View File
@@ -56,3 +56,33 @@ 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
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
+1 -1
View File
@@ -3,7 +3,7 @@
cd "$(dirname "$0")/.." || exit 1
LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')}
LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')}
python3 -I tools/fixtures.py deflate png > /dev/null || exit 1
python3 -I tools/fixtures.py deflate png json 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
+99
View File
@@ -0,0 +1,99 @@
# Shared helpers for the data-format fixture generators (json, xml, csv, toml, yaml, msgpack, cbor, plist, ...):
# fetch(url, sha256) -> a nix store path of an unpacked tarball (official test suites, pinned by hash)
# canon(value) -> the canonical text a Luau test computes too (tests/data/_canon.luau): typed, sorted keys,
# numbers as %.17g, so Python's parse and ours compare exactly.
import os, subprocess, datetime
def fetch(url, sha256):
expr = 'builtins.fetchTarball { url = "%s"; sha256 = "%s"; }' % (url, sha256)
out = subprocess.run(["nix", "eval", "--raw", "--impure", "--expr", expr], capture_output=True, check=True)
return out.stdout.decode()
def _b(s):
if isinstance(s, str):
return s.encode("utf-8", "surrogatepass")
return bytes(s)
def canon(v):
"""null n; true t; false f; number #%d (integral, under 2^53) or #%.17g; string s<len>:<bytes>;
bytes b<len>:<bytes>; list [..]; dict {k v ...} with keys sorted by their canon bytes; dates d<rfc3339>"""
out = bytearray()
_canon(v, out)
return bytes(out)
def num(x):
x = float(x)
if x != x:
return b"#nan"
if x in (float("inf"), float("-inf")):
return b"#inf" if x > 0 else b"#-inf"
if x == int(x) and abs(x) < 2 ** 53:
return b"#%d" % int(x)
return b"#" + ("%.17g" % x).encode()
def _canon(v, out):
if v is None:
out += b"n"
elif v is True:
out += b"t"
elif v is False:
out += b"f"
elif isinstance(v, (int, float)):
out += num(v)
elif isinstance(v, str):
b = _b(v)
out += b"s%d:" % len(b) + b
elif isinstance(v, (bytes, bytearray)):
out += b"b%d:" % len(v) + bytes(v)
elif isinstance(v, (list, tuple)):
out += b"["
for x in v:
_canon(x, out)
out += b","
out += b"]"
elif isinstance(v, dict):
items = []
for k, x in v.items():
kb = bytearray()
_canon(k, kb)
items.append((bytes(kb), x))
items.sort(key=lambda p: p[0])
out += b"{"
for kb, x in items:
out += kb + b"="
_canon(x, out)
out += b","
out += b"}"
elif isinstance(v, (datetime.datetime, datetime.date, datetime.time)):
out += b"d" + date_text(v).encode()
else:
raise TypeError("canon: %r" % type(v))
def date_text(v):
"""RFC 3339 the way Types.Date prints: fraction without trailing zeros, Z for +00:00"""
def frac(us):
return ("." + ("%06d" % us).rstrip("0")) if us else ""
def tz(t):
off = t.utcoffset()
if off is None:
return ""
m = int(off.total_seconds()) // 60
if m == 0:
return "Z"
sign = "-" if m < 0 else "+"
m = abs(m)
return "%s%02d:%02d" % (sign, m // 60, m % 60)
if isinstance(v, datetime.datetime):
return "%04d-%02d-%02dT%02d:%02d:%02d%s%s" % (v.year, v.month, v.day, v.hour, v.minute, v.second,
frac(v.microsecond), tz(v))
if isinstance(v, datetime.date):
return "%04d-%02d-%02d" % (v.year, v.month, v.day)
return "%02d:%02d:%02d%s" % (v.hour, v.minute, v.second, frac(v.microsecond))
+91
View File
@@ -0,0 +1,91 @@
# codecs/Json + data/json fixtures: the JSONTestSuite parsing corpus (nst/JSONTestSuite, pinned tarball through nix)
# with Python's json verdicts and canonical values, plus a random corpus written by Python's json.dumps in several
# styles (compact sorted, insertion order, indent 2, ensure_ascii) that the tests must parse and reproduce exactly.
# tests/gen/json_suite.luau { { name, expect = "y" | "n" | "i", data, canon? } }
# tests/gen/json_corpus.luau { { canon, compact, ordered, pretty, ascii } }
# tests/gen/json_bench.luau { text, compact } (~1 MB, indent 1; compact = sorted keys)
import importlib.util, json, os
_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py"))
C = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(C)
SUITE_URL = "https://github.com/nst/JSONTestSuite/archive/1ef36fa01286573e846ac449e8683f8833c5b26a.tar.gz"
SUITE_SHA = "0zp4gbpfxac9hfzlgjmqg70w8dhql6rbrkh8dhi3rn5aan0qqv5k"
def rand_value(rng, depth=0):
v = _rand_value(rng, depth)
if isinstance(v, float) and v.is_integer():
return int(v) # Python writes 1.0, we write 1: keep integral numbers ints
return v
def _rand_value(rng, depth=0):
r = rng.random()
if depth > 4 or r < 0.45:
k = rng.randrange(9)
if k == 0:
return None
if k == 1:
return rng.random() < 0.5
if k == 2:
return rng.randrange(-10 ** 15, 10 ** 15)
if k == 3:
return rng.randrange(-1000, 1000)
if k == 4:
return round(rng.uniform(-1e6, 1e6), rng.randrange(1, 8))
if k == 5:
return rng.uniform(-1, 1) * 10 ** rng.randrange(-4, 14)
return rand_str(rng)
if r < 0.72:
return [rand_value(rng, depth + 1) for _ in range(rng.randrange(0, 7))]
d = {}
for _ in range(rng.randrange(0, 7)):
d[rand_str(rng)] = rand_value(rng, depth + 1)
return d
ALPH = "abcxyz ABC_019\"\\/\n\t\r\b\f\x01\x1f\x7féü中文\U0001f600
"
def rand_str(rng):
return "".join(rng.choice(ALPH) for _ in range(rng.randrange(0, 12)))
def generate(ctx):
root = C.fetch(SUITE_URL, SUITE_SHA)
d = os.path.join(root, "test_parsing")
cases = []
for name in sorted(os.listdir(d)):
if not name.endswith(".json"):
continue
data = open(os.path.join(d, name), "rb").read()
c = {"name": name, "expect": name[0], "data": data}
try:
v = json.loads(data.decode("utf-8", "surrogatepass"))
c["canon"] = C.canon(v)
except Exception:
pass
cases.append(c)
ctx.emit("json_suite", cases)
rng = ctx.rng(7)
corpus = []
for _ in range(300):
v = rand_value(rng)
corpus.append({
"canon": C.canon(v),
"compact": json.dumps(v, separators=(",", ":"), sort_keys=True, ensure_ascii=False),
"ordered": json.dumps(v, separators=(",", ":"), ensure_ascii=False),
"pretty": json.dumps(v, indent=2, sort_keys=True, ensure_ascii=False),
"ascii": json.dumps(v, separators=(",", ":"), sort_keys=True),
})
ctx.emit("json_corpus", corpus)
big = [rand_value(rng) for _ in range(3000)]
text = json.dumps(big, ensure_ascii=False, indent=1)
while len(text) < 1_000_000:
big = big + big
text = json.dumps(big, ensure_ascii=False, indent=1)
ctx.emit("json_bench", {"text": text, "compact": json.dumps(big, separators=(",", ":"), sort_keys=True, ensure_ascii=False)})
+174
View File
@@ -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("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def esc_attr(t, q):
t = t.replace("&", "&amp;").replace("<", "&lt;")
return t.replace(q, "&quot;" if q == '"' else "&apos;")
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("<![CDATA[" + rand_text(rng).replace("]", "] ") + "<&>]]>")
elif r < 0.5:
parts.append("<!-- c " + rand_text(rng).replace("-", "=") + " -->")
elif r < 0.53:
parts.append("<?pi data " + rand_text(rng).replace("?", "") + "?>")
elif r < 0.58:
parts.append(rng.choice(["&ent;", "&#233;", "&#x1F600;", "&amp;", "&lt;", "&#10;"]))
else:
parts.append(gen_elem(rng, depth + 1, newdecl))
parts.append("</%s>" % name)
return "".join(parts)
def gen_doc(rng):
head = ""
if rng.random() < 0.5:
head += '<?xml version="1.0" encoding="UTF-8"?>\n'
head += '<!DOCTYPE root [\n <!ENTITY ent "entity &#38;#38; text &lt;">\n <!-- a comment -->\n]>\n'
if rng.random() < 0.3:
head += "<!-- prolog comment -->\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 = [
"<a/>", "<a></a>", "<a><b/></a>", "<a>x</b>", "<a>", "</a>", "<a/><b/>", "text<a/>", "<a/>text", "<a b='1' b='2'/>",
"<a b=1/>", "<a b='<'/>", "<a>&undefined;</a>", "<a>&#0;</a>", "<a>&#x110000;</a>", "<a>&#xD800;</a>", "<a>& </a>",
"<a><!-- x -- y --></a>", "<a><!-- x ---></a>", "<a>]]></a>", "<1a/>", "<a 1b='x'/>", "<a b='x'c='y'/>",
"<?xml version='1.0'?><a/>", " <?xml version='1.0'?><a/>", "<a/><?xml version='1.0'?>", "<a><![CDATA[x]]></a>",
"<![CDATA[x]]><a/>", "<a><![CDATA[x</a>", "<a>\x01</a>", "<a b='\x01'/>", "<a><?pi x?></a>", "<a><?pi?></a>",
"<!DOCTYPE a><a/>", "<a/><!DOCTYPE a>", "<!DOCTYPE a [<!ENTITY e 'v'>]><a>&e;</a>", "<a b='&lt;&#65;'/>",
"<a:b xmlns:a='u'/>", "<a\n b\n =\n 'c'\n/>", "<a></a >", "<a></ a>", "< a/>", "<a/ >", "<a b='x' / >",
"<a>é\U0001f600</a>", "<a>&amp;&lt;&gt;&quot;&apos;</a>", "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><a/>",
"<!-- c --><a/><!-- d -->", "<a><!----></a>", "", " ", "<a>x</a>trailing", "<a>x</a><!-- ok --> ",
]
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("<?xml") else text
c = canon(ET.fromstring(text.encode("utf-8")))
docs.append({"data": ('<?xml version="1.0" encoding="UTF-16"?>' + body).encode("utf-16"), "canon": c})
docs.append({"data": b"\xfe\xff" + ('<?xml version="1.0" encoding="UTF-16"?>' + body).encode("utf-16-be"), "canon": c})
for k in range(10):
text = "<?xml version='1.0' encoding='ISO-8859-1'?><r a='éÿ'>café ½ &#x4e2d;</r>"
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": "<root>" + "\n".join(p for p in parts if "&ent;" not in p) + "</root>"})