vec: merge ws/data (codecs/Xml, codecs/Json)
This commit is contained in:
commit
c371839331
20 files changed
+3708
-3
No files matched your search
@@ -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,
|
||||
},
|
||||
{
|
||||
name = "aseprite",
|
||||
category = "layered",
|
||||
|
||||
+279
-2
@@ -343,12 +343,289 @@ export type Archive = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Data
|
||||
-- data formats decode to plain Luau values; JSON null / YAML ~ / CBOR null is this sentinel (nil cannot sit in a
|
||||
-- table). XML decodes to XmlNode trees.
|
||||
-- table). XML decodes to XmlNode trees. Byte strings (msgpack bin, CBOR bytes, plist data) are buffers.
|
||||
local nullMeta = { __tostring = function()
|
||||
return "null"
|
||||
end }
|
||||
Types.null = table.freeze(setmetatable({}, nullMeta))
|
||||
export type XmlNode = { name: string, attrs: { [string]: string }, children: { XmlNode | string }, parent: XmlNode? }
|
||||
|
||||
-- Objects (maps) whose key order matters, and empty objects (which would otherwise read back as empty arrays), carry
|
||||
-- an "object" metatable with their key order. Decoders mark empty objects always and every object when asked
|
||||
-- (opts.ordered); encoders write an object's keys in that order (keys added later, or plain tables: sorted).
|
||||
-- local o = Types.object() o.b = 1; o.a = 2 -- or Types.object({ a = 2, b = 1 }, { "b", "a" })
|
||||
-- Types.set(o, "c", 3) -- assigns and appends "c" to the order
|
||||
-- for _, k in Types.keys(o) do ... end
|
||||
local OBJECT = { __object = true }
|
||||
local objectMeta: { [any]: { any } } = setmetatable({}, { __mode = "k" }) :: any -- object -> its key order
|
||||
-- object(t?, keys?) -> t marked as an object, keys = its key order (default: none recorded; Types.set appends)
|
||||
function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any }
|
||||
local o = t or {}
|
||||
if getmetatable(o) == nil then
|
||||
setmetatable(o, OBJECT)
|
||||
end
|
||||
objectMeta[o] = keys or {}
|
||||
return o
|
||||
end
|
||||
-- isObject(v) -> true for tables made by Types.object
|
||||
function Types.isObject(v: any): boolean
|
||||
return type(v) == "table" and objectMeta[v] ~= nil
|
||||
end
|
||||
-- set(o, k, v): o[k] = v, appending k to o's key order when new (o must be an object; a plain table just assigns)
|
||||
function Types.set(o: { [any]: any }, k: any, v: any)
|
||||
local order = objectMeta[o]
|
||||
if order and o[k] == nil and v ~= nil then
|
||||
table.insert(order, k)
|
||||
end
|
||||
o[k] = v
|
||||
end
|
||||
local function keyLess(a: any, b: any): boolean
|
||||
local ta, tb = type(a), type(b)
|
||||
if ta ~= tb then
|
||||
return ta < tb
|
||||
end
|
||||
if ta == "number" or ta == "string" then
|
||||
return a < b
|
||||
end
|
||||
return tostring(a) < tostring(b)
|
||||
end
|
||||
-- keys(t) -> the keys in order: an object's recorded order (keys since removed are skipped), then any other keys
|
||||
-- sorted (numbers before strings)
|
||||
function Types.keys(t: { [any]: any }): { any }
|
||||
local order = objectMeta[t]
|
||||
local out, seen = {}, {}
|
||||
if order then
|
||||
for _, k in order do
|
||||
if t[k] ~= nil and not seen[k] then
|
||||
seen[k] = true
|
||||
table.insert(out, k)
|
||||
end
|
||||
end
|
||||
end
|
||||
local rest = {}
|
||||
for k in next, t do
|
||||
if not seen[k] then
|
||||
table.insert(rest, k)
|
||||
end
|
||||
end
|
||||
if #rest > 0 then
|
||||
table.sort(rest, keyLess)
|
||||
table.move(rest, 1, #rest, #out + 1, out)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- Dates and times (TOML datetimes, plist <date>, CBOR tags 0 / 1, msgpack timestamps). Fields present depend on the
|
||||
-- kind: "datetime" (with offset: an instant), "datetime-local", "date-local", "time-local". offset is in minutes
|
||||
-- east of UTC (nil = local time). tostring gives RFC 3339 ("1979-05-27T07:32:00.5-07:00", "07:32:00", ...).
|
||||
export type Date = {
|
||||
kind: "datetime" | "datetime-local" | "date-local" | "time-local",
|
||||
year: number?,
|
||||
month: number?,
|
||||
day: number?,
|
||||
hour: number?,
|
||||
minute: number?,
|
||||
second: number?,
|
||||
nanosecond: number?, -- 0 .. 999999999
|
||||
offset: number?, -- minutes east of UTC
|
||||
}
|
||||
local DateMeta = {}
|
||||
local function p2(n: number): string
|
||||
return string.format("%02d", n)
|
||||
end
|
||||
local function fmtDate(d: any): string
|
||||
local s = ""
|
||||
if d.year then
|
||||
s = string.format("%04d-%02d-%02d", d.year, d.month or 1, d.day or 1)
|
||||
end
|
||||
if d.hour then
|
||||
if s ~= "" then
|
||||
s ..= "T"
|
||||
end
|
||||
s ..= p2(d.hour) .. ":" .. p2(d.minute or 0) .. ":" .. p2(d.second or 0)
|
||||
local ns = d.nanosecond or 0
|
||||
if ns > 0 then
|
||||
local f = string.format("%09d", ns)
|
||||
s ..= "." .. (string.gsub(f, "0+$", ""))
|
||||
end
|
||||
if d.offset then
|
||||
if d.offset == 0 then
|
||||
s ..= "Z"
|
||||
else
|
||||
local o = math.abs(d.offset)
|
||||
s ..= (if d.offset < 0 then "-" else "+") .. p2(o // 60) .. ":" .. p2(o % 60)
|
||||
end
|
||||
end
|
||||
end
|
||||
return s
|
||||
end
|
||||
DateMeta.__tostring = fmtDate
|
||||
DateMeta.__eq = function(a: any, b: any): boolean
|
||||
return fmtDate(a) == fmtDate(b) and a.kind == b.kind
|
||||
end
|
||||
local DateLib = {}
|
||||
-- days since 1970-01-01 of a civil date (proleptic Gregorian; Howard Hinnant's algorithm)
|
||||
local function daysFromCivil(y: number, m: number, d: number): number
|
||||
y = if m <= 2 then y - 1 else y
|
||||
local era = (if y >= 0 then y else y - 399) // 400
|
||||
local yoe = y - era * 400
|
||||
local mp = (m + 9) % 12
|
||||
local doy = (153 * mp + 2) // 5 + d - 1
|
||||
local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy
|
||||
return era * 146097 + doe - 719468
|
||||
end
|
||||
local function civilFromDays(z: number): (number, number, number)
|
||||
z += 719468
|
||||
local era = (if z >= 0 then z else z - 146096) // 146097
|
||||
local doe = z - era * 146097
|
||||
local yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365
|
||||
local y = yoe + era * 400
|
||||
local doy = doe - (365 * yoe + yoe // 4 - yoe // 100)
|
||||
local mp = (5 * doy + 2) // 153
|
||||
local d = doy - (153 * mp + 2) // 5 + 1
|
||||
local m = if mp < 10 then mp + 3 else mp - 9
|
||||
return (if m <= 2 then y + 1 else y), m, d
|
||||
end
|
||||
local MDAYS = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
|
||||
-- new(fields) -> Date (kind inferred from the fields present when not given)
|
||||
function DateLib.new(f: { [string]: any }): Date
|
||||
local d: any = {}
|
||||
for k, v in f do
|
||||
d[k] = v
|
||||
end
|
||||
if d.kind == nil then
|
||||
d.kind = if d.year and d.hour then (if d.offset then "datetime" else "datetime-local")
|
||||
elseif d.year then "date-local"
|
||||
else "time-local"
|
||||
end
|
||||
return setmetatable(d, DateMeta) :: any
|
||||
end
|
||||
-- is(v) -> true for Dates
|
||||
function DateLib.is(v: any): boolean
|
||||
return type(v) == "table" and getmetatable(v) == DateMeta
|
||||
end
|
||||
-- valid(d) -> true when the fields are in range (month 1..12, the day exists in that month, hour < 24, ...)
|
||||
function DateLib.valid(d: Date): boolean
|
||||
if d.year then
|
||||
local y, m, dd = d.year, d.month or 0, d.day or 0
|
||||
if y < 0 or y > 9999 or m < 1 or m > 12 or dd < 1 or dd > MDAYS[m] then
|
||||
return false
|
||||
end
|
||||
if m == 2 and dd == 29 and not (y % 4 == 0 and (y % 100 ~= 0 or y % 400 == 0)) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
if d.hour then
|
||||
if d.hour > 23 or (d.minute or 0) > 59 or (d.second or 0) > 60 then
|
||||
return false
|
||||
end
|
||||
end
|
||||
if d.offset and math.abs(d.offset) >= 24 * 60 then
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
-- parse(s) -> Date | nil: RFC 3339 / ISO 8601 date-times and their TOML partial forms ("1979-05-27",
|
||||
-- "07:32:00.999", "1979-05-27 07:32:00Z", lower-case t / z accepted); out-of-range fields return nil
|
||||
function DateLib.parse(s: string): Date?
|
||||
local d: any = {}
|
||||
local rest = s
|
||||
local y, mo, dd, r1 = string.match(rest, "^(%d%d%d%d)%-(%d%d)%-(%d%d)(.*)$")
|
||||
if y then
|
||||
d.year, d.month, d.day = tonumber(y), tonumber(mo), tonumber(dd)
|
||||
rest = r1
|
||||
if rest == "" then
|
||||
return if DateLib.valid(d) then DateLib.new(d) else nil
|
||||
end
|
||||
local sep = string.sub(rest, 1, 1)
|
||||
if sep ~= "T" and sep ~= "t" and sep ~= " " then
|
||||
return nil
|
||||
end
|
||||
rest = string.sub(rest, 2)
|
||||
end
|
||||
local h, mi, r2 = string.match(rest, "^(%d%d):(%d%d)(.*)$")
|
||||
if not h then
|
||||
return nil
|
||||
end
|
||||
d.hour, d.minute = tonumber(h), tonumber(mi)
|
||||
rest = r2
|
||||
local sec, r3 = string.match(rest, "^:(%d%d)(.*)$")
|
||||
if not sec then
|
||||
return nil
|
||||
end
|
||||
d.second = tonumber(sec)
|
||||
rest = r3
|
||||
local frac, r4 = string.match(rest, "^%.(%d+)(.*)$")
|
||||
if frac then
|
||||
d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9))
|
||||
rest = r4
|
||||
else
|
||||
d.nanosecond = 0
|
||||
end
|
||||
if rest ~= "" then
|
||||
if not d.year then
|
||||
return nil
|
||||
end
|
||||
if rest == "Z" or rest == "z" then
|
||||
d.offset = 0
|
||||
else
|
||||
local sign, oh, om = string.match(rest, "^([%+%-])(%d%d):(%d%d)$")
|
||||
if not sign then
|
||||
return nil
|
||||
end
|
||||
local oh_n, om_n = tonumber(oh) :: number, tonumber(om) :: number
|
||||
if oh_n > 23 or om_n > 59 then
|
||||
return nil
|
||||
end
|
||||
d.offset = (oh_n * 60 + om_n) * (if sign == "-" then -1 else 1)
|
||||
end
|
||||
end
|
||||
return if DateLib.valid(d) then DateLib.new(d) else nil
|
||||
end
|
||||
-- toUnix(d) -> seconds since 1970-01-01T00:00:00Z (fractional; local times are taken as UTC)
|
||||
function DateLib.toUnix(d: Date): number
|
||||
local days = if d.year then daysFromCivil(d.year, d.month or 1, d.day or 1) else 0
|
||||
local s = days * 86400 + (d.hour or 0) * 3600 + (d.minute or 0) * 60 + (d.second or 0) - (d.offset or 0) * 60
|
||||
return s + (d.nanosecond or 0) / 1e9
|
||||
end
|
||||
-- fromUnix(seconds, offset?) -> a "datetime" Date (offset in minutes, default 0 = UTC)
|
||||
function DateLib.fromUnix(t: number, offset: number?): Date
|
||||
local off = offset or 0
|
||||
local whole = math.floor(t)
|
||||
local ns = math.floor((t - whole) * 1e9 + 0.5)
|
||||
if ns >= 1e9 then
|
||||
whole += 1
|
||||
ns -= 1e9
|
||||
end
|
||||
local lt = whole + off * 60
|
||||
local days = lt // 86400
|
||||
local secs = lt - days * 86400
|
||||
local y, m, dd = civilFromDays(days)
|
||||
return DateLib.new({
|
||||
kind = "datetime",
|
||||
year = y,
|
||||
month = m,
|
||||
day = dd,
|
||||
hour = secs // 3600,
|
||||
minute = (secs // 60) % 60,
|
||||
second = secs % 60,
|
||||
nanosecond = ns,
|
||||
offset = off,
|
||||
})
|
||||
end
|
||||
Types.Date = table.freeze(DateLib)
|
||||
|
||||
-- XML: an element, or (name starting with "#") a "#document" / "#comment" / "#cdata" / "#pi" / "#doctype" node with
|
||||
-- its content in text. attrs is a Types.object (attribute order kept). Text children are plain strings.
|
||||
export type XmlNode = {
|
||||
name: string,
|
||||
attrs: { [string]: string },
|
||||
children: { XmlNode | string },
|
||||
parent: XmlNode?,
|
||||
text: string?, -- "#comment" / "#cdata" / "#pi" (the data after the target) / "#doctype" content
|
||||
target: string?, -- "#pi": the target
|
||||
ns: string?, -- the namespace URI (opts.namespaces)
|
||||
[string]: any,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Vector
|
||||
export type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any }
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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 = { ["&"] = "&", ["<"] = "<", [">"] = ">", ["\r"] = " " }
|
||||
local ATTR_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """, ["\t"] = "	", ["\n"] = " ", ["\r"] = " " }
|
||||
|
||||
-- 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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user