data: codecs/Xml (XML 1.0 DOM + pull events + serializer: UTF-8/16/Latin-1, entities incl. internal DOCTYPE with expansion limit, CDATA, comments, PIs, namespaces as qualified names + node.ns / clark, xml:space); ElementTree + expat fixtures; bench lines

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 08:38:55 -05:00
1 parent 2557d3b1fe
commit 907f3650f1
7 files changed
+1599 -1

No files matched your search

+1
View File
@@ -11,3 +11,4 @@ Codecs (layer 1, shared by formats; not loadable on their own):
- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
- codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
- codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ...
+771
View File
@@ -0,0 +1,771 @@
--!strict
--!native
-- codecs/Xml/Parse: the XML 1.0 pull parser behind codecs/Xml. Input decoding (UTF-8, UTF-16 LE / BE by BOM or
-- by the first bytes, ISO-8859-1 / US-ASCII / Windows-1252 by the declaration), line-ending normalization, the
-- well-formedness rules that matter (one root, matched tags, unique attributes, quoted values, no '<' in values,
-- legal names, character references in range, no "--" in comments, no "]]>" in text), the five predefined entities,
-- character references and internal general entities from the DOCTYPE (with an expansion limit). Not supported:
-- external entities / DTDs (references to them are errors), entity values containing markup (taken as text),
-- validation. Never throws: errors are events.
local Types = require("@formats/Types")
local Parse = {}
local byte, sub, find, match, char, gsub, lower = string.byte, string.sub, string.find, string.match, string.char, string.gsub, string.lower
export type Options = {
whitespace: boolean?, -- keep whitespace-only text (default false: dropped, except inside xml:space="preserve")
namespaces: boolean?, -- resolve namespace prefixes: "start" events carry the element's URI (default false)
entities: { [string]: string }?, -- extra general entities (name -> replacement text)
maxExpansion: number?, -- total characters produced by entity expansion (default 1e7; the billion laughs guard)
maxDepth: number?, -- element nesting limit (default 10000)
}
local NAME = "^[%a_:\128-\255][%w_:%.%-\128-\255]*"
local PREDEF: { [string]: string } = { lt = "<", gt = ">", amp = "&", quot = '"', apos = "'" }
local function utf8char(c: number): string
if c < 0x80 then
return char(c)
elseif c < 0x800 then
return char(0xC0 + c // 64, 0x80 + c % 64)
elseif c < 0x10000 then
return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64)
end
return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64)
end
Parse.utf8char = utf8char
local CP1252: { [number]: number } = {
[0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020,
[0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152,
[0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022,
[0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A,
[0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178,
}
local function utf16(s: string, start: number, le: boolean): (string?, string?)
local out = table.create(#s // 2)
local n = 0
local i = start
local len = #s
while i + 1 <= len do
local a, b = byte(s, i, i + 1)
local u = if le then a + b * 256 else a * 256 + b
i += 2
if u >= 0xD800 and u <= 0xDBFF then
if i + 1 > len then
return nil, "truncated UTF-16 surrogate pair"
end
local c, d = byte(s, i, i + 1)
local lo = if le then c + d * 256 else c * 256 + d
if lo < 0xDC00 or lo > 0xDFFF then
return nil, "bad UTF-16 surrogate pair"
end
i += 2
u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00)
elseif u >= 0xDC00 and u <= 0xDFFF then
return nil, "bad UTF-16 surrogate pair"
end
n += 1
out[n] = utf8char(u)
end
if i <= len then
return nil, "odd number of bytes in UTF-16 text"
end
return table.concat(out), nil
end
-- toUtf8(s) -> UTF-8 text (BOM removed), the encoding name | nil, message
function Parse.toUtf8(s: string): (string?, string)
local b1, b2, b3 = byte(s, 1, 3)
if b1 == 0xEF and b2 == 0xBB and b3 == 0xBF then
return sub(s, 4), "utf-8"
elseif b1 == 0xFF and b2 == 0xFE then
local t, e = utf16(s, 3, true)
return t, e or "utf-16le"
elseif b1 == 0xFE and b2 == 0xFF then
local t, e = utf16(s, 3, false)
return t, e or "utf-16be"
elseif b1 == 0x3C and b2 == 0 then
local t, e = utf16(s, 1, true)
return t, e or "utf-16le"
elseif b1 == 0 and b2 == 0x3C then
local t, e = utf16(s, 1, false)
return t, e or "utf-16be"
end
local decl = match(s, "^<%?xml[^>]-%?>")
local enc = if decl then match(decl, "encoding%s*=%s*[\"']([%w%._%-]+)[\"']") else nil
if enc then
local e = lower(enc)
if e == "utf-8" or e == "utf8" or e == "us-ascii" or e == "ascii" then
if find(s, "[\128-\255]") and not utf8.len(s) then
return nil, "invalid UTF-8"
end
return s, e
elseif e == "iso-8859-1" or e == "latin1" or e == "latin-1" or e == "iso8859-1" or e == "windows-1252" or e == "cp1252" then
local w = e == "windows-1252" or e == "cp1252"
return (gsub(s, "[\128-\255]", function(c: string): string
local v = byte(c)
return utf8char(if w then CP1252[v] or v else v)
end)), e
elseif e == "utf-16" or e == "utf-16le" or e == "utf-16be" then
return s, "utf-8" -- declared UTF-16 but read as 8-bit text: trust the bytes
end
return nil, "unsupported encoding " .. enc
end
if find(s, "[\128-\255]") and not utf8.len(s) then
return nil, "invalid UTF-8"
end
return s, "utf-8"
end
-- the <?xml ...?> pseudo-attributes, strictly: version, then encoding?, then standalone?, each after whitespace
local function xmlDecl(data: string): { [string]: string }?
local p = 1
local out: { [string]: string } = {}
for k, key in { "version", "encoding", "standalone" } do
local ws = match(data, "^[ \t\n]*()", p) :: any
local q, v, e = match(data, "^" .. key .. "[ \t\n]*=[ \t\n]*([\"'])(.-)%1()", ws)
if q then
if k > 1 and ws == p then
return nil -- no whitespace before
end
if (key == "version" and not match(v, "^1%.%d+$"))
or (key == "encoding" and not match(v, "^%a[%w%._%-]*$"))
or (key == "standalone" and v ~= "yes" and v ~= "no")
then
return nil
end
out[key] = v
p = e
elseif key == "version" then
return nil
end
end
if match(data, "^[ \t\n]*()", p) ~= #data + 1 then
return nil
end
return out
end
-- the events iterator: next() -> event, a, b, c
-- "decl", { version, encoding, standalone } the <?xml ...?> declaration
-- "doctype", raw, info raw = the text between "<!DOCTYPE" and ">"; info = { name,
-- publicId, systemId, entities }
-- "start", name, attrs (Types.object), ns ns: the element's namespace URI (opts.namespaces) or nil
-- "end", name
-- "text", s character data, entities decoded (whitespace-only dropped
-- unless opts.whitespace)
-- "cdata", s "comment", s "pi", target, data
-- "error", message, offset then the iterator ends
-- nil at the end of the document.
function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any)
local o: Options = opts or {}
local keepWs = o.whitespace == true
local nsOn = o.namespaces == true
local maxExp = o.maxExpansion or 1e7
local maxDepth = o.maxDepth or 10000
local entities: { [string]: string } = {}
if o.entities then
for k, v in o.entities do
entities[k] = v
end
end
local external: { [string]: boolean } = {}
local expanded = 0
if find(s, "\r", 1, true) then
s = gsub(gsub(s, "\r\n", "\n"), "\r", "\n")
end
local n = #s
local i = 1
local stack: { string } = {}
local nsStack: { { [string]: string } } = {}
local preserve: { boolean } = {}
local depth = 0
local rootSeen = false
local rootDone = false
local dead = false
local pending: { any }? = nil -- an "end" queued after a self-closing start
local errMsg: string? = nil
local errAt = 0
local function fail(msg: string, at: number): (string, string, number)
dead = true
return "error", msg, at - 1
end
-- decode entity / character references in raw text; nil on error (errMsg set)
local decode: (raw: string, at: number, level: number) -> string?
function decode(raw: string, at: number, level: number): string?
if not find(raw, "&", 1, true) then
return raw
end
local parts = {}
local np = 0
local p = 1
while true do
local a = find(raw, "&", p, true)
if not a then
break
end
np += 1
parts[np] = sub(raw, p, a - 1)
local ref, e = match(raw, "^&([^;&%s<]*);()", a)
if not ref then
errMsg, errAt = "bad reference (no ';')", at + a - 1
return nil
end
local rep: string
if byte(ref) == 35 then -- #
local cp = if byte(ref, 2) == 120 then tonumber(match(ref, "^#x(%x+)$") or "", 16) else tonumber(match(ref, "^#(%d+)$") or "")
if not cp or cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) or cp == 0xFFFE or cp == 0xFFFF then
errMsg, errAt = "bad character reference &" .. ref .. ";", at + a - 1
return nil
end
rep = utf8char(cp)
else
local pre = PREDEF[ref]
if pre then
rep = pre
else
local ent = entities[ref]
if not ent then
errMsg = if external[ref] then "external entity &" .. ref .. "; not supported" else "undefined entity &" .. ref .. ";"
errAt = at + a - 1
return nil
end
if level > 40 then
errMsg, errAt = "entity references nested too deeply (recursive?)", at + a - 1
return nil
end
local r = decode(ent, at + a - 1, level + 1)
if not r then
return nil
end
rep = r
end
end
expanded += #rep
if expanded > maxExp then
errMsg, errAt = "entity expansion over the limit", at + a - 1
return nil
end
np += 1
parts[np] = rep
p = e :: any
end
np += 1
parts[np] = sub(raw, p)
return table.concat(parts)
end
local function lookupNs(prefix: string): string?
for d = depth, 1, -1 do
local m = nsStack[d]
if m and m[prefix] ~= nil then
return m[prefix]
end
end
if prefix == "xml" then
return "http://www.w3.org/XML/1998/namespace"
end
return nil
end
-- a quoted literal at p -> its content, the position after it | nil
local function literal(p: number): (string?, number)
local q = byte(s, p)
if q ~= 34 and q ~= 39 then
return nil, p
end
local e = find(s, if q == 34 then '"' else "'", p + 1, true)
if not e then
return nil, p
end
return sub(s, p + 1, e - 1), e + 1
end
-- an ExternalID (SYSTEM "sys" | PUBLIC "pub" "sys") at p -> publicId, systemId, next | nil
local function externalId(p: number): (string?, string?, number?)
local kw = sub(s, p, p + 5)
if kw == "SYSTEM" then
local q = match(s, "^[ \t\n]+()", p + 6) :: any
if not q then
return nil
end
local sys, e = literal(q)
if not sys then
return nil
end
return "", sys, e
elseif kw == "PUBLIC" then
local q = match(s, "^[ \t\n]+()", p + 6) :: any
if not q then
return nil
end
local pub, e = literal(q)
if not pub or find(pub, "[^ \r\n%w%-'()+,./:=?;!*#@$_%%]") then
return nil
end
local r = match(s, "^[ \t\n]+()", e) :: any
if not r then
return nil
end
local sys, e2 = literal(r)
if not sys then
return nil
end
return pub, sys, e2
end
return nil
end
-- check an entity value's references and expand its character references (the rest expand when used)
local function entityValue(v: string): string?
if find(v, "%", 1, true) then
return nil -- parameter-entity references are not allowed in the internal subset's markup
end
local p = 1
local parts = {}
while true do
local a = find(v, "&", p, true)
if not a then
table.insert(parts, sub(v, p))
break
end
table.insert(parts, sub(v, p, a - 1))
local hex = match(v, "^&#x(%x+);", a)
local dec = match(v, "^&#(%d+);", a)
if hex or dec then
local cp = tonumber(hex or dec, if hex then 16 else 10) :: number
if cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) then
return nil
end
table.insert(parts, utf8char(cp))
p = (find(v, ";", a, true) :: number) + 1
else
local name = match(v, "^&([%a_:\128-\255][%w_:%.%-\128-\255]*);", a)
if not name then
return nil
end
table.insert(parts, "&" .. name .. ";")
p = a + #name + 2
end
end
return table.concat(parts)
end
-- the DOCTYPE at i (just past "<!DOCTYPE"): its raw text and info { name, publicId, systemId, entities }; records
-- the internal subset's general entities. nil, message on bad syntax.
local function doctype(): (string?, any)
local start = i
local p = match(s, "^[ \t\n]+()", i) :: any
if not p then
return nil, "bad DOCTYPE"
end
local name = match(s, NAME, p)
if not name then
return nil, "bad DOCTYPE name"
end
local info: any = { name = name, entities = {} }
p += #name
local q = match(s, "^[ \t\n]*()", p) :: any
if q > p and (sub(s, q, q + 5) == "SYSTEM" or sub(s, q, q + 5) == "PUBLIC") then
local pub, sys, e = externalId(q)
if not pub then
return nil, "bad DOCTYPE external id"
end
info.publicId = if pub ~= "" then pub else nil
info.systemId = sys
q = match(s, "^[ \t\n]*()", e) :: any
end
if byte(s, q) == 91 then -- the internal subset
q += 1
while true do
q = match(s, "^[ \t\n]*()", q) :: any
local c = byte(s, q)
if c == 93 then
q += 1
break
elseif c == 37 then -- %name;
local pe = match(s, "^%%[%a_:\128-\255][%w_:%.%-\128-\255]*;()", q)
if not pe then
return nil, "bad parameter-entity reference"
end
q = pe :: any
elseif sub(s, q, q + 3) == "<!--" then
local e = find(s, "--", q + 4, true)
if not e or byte(s, e + 2) ~= 62 then
return nil, if e then "'--' inside a comment" else "unterminated comment in DOCTYPE"
end
q = e + 3
elseif sub(s, q, q + 1) == "<?" then
local target = match(s, NAME, q + 2)
local e = find(s, "?>", q + 2, true)
if not target or not e or lower(target) == "xml" then
return nil, "bad processing instruction in DOCTYPE"
end
q = e + 2
elseif sub(s, q, q + 7) == "<!ENTITY" then
local r = match(s, "^[ \t\n]+()", q + 8) :: any
if not r then
return nil, "bad ENTITY declaration"
end
local isPe = false
if byte(s, r) == 37 then
isPe = true
r = match(s, "^[ \t\n]+()", r + 1) :: any
if not r then
return nil, "bad ENTITY declaration"
end
end
local ename = match(s, NAME, r)
if not ename then
return nil, "bad ENTITY name"
end
r = match(s, "^[ \t\n]+()", r + #ename) :: any
if not r then
return nil, "bad ENTITY declaration"
end
local val, e = literal(r)
if val then
local v = entityValue(val)
if not v then
return nil, "bad ENTITY value"
end
if not isPe and entities[ename] == nil then
entities[ename] = v
info.entities[ename] = v
end
r = e
else
local pub, _, e2 = externalId(r)
if not pub then
return nil, "bad ENTITY declaration"
end
r = e2 :: number
local nd = match(s, "^[ \t\n]+NDATA[ \t\n]+()", r)
if nd then
local nn = match(s, NAME, nd)
if not nn or isPe then
return nil, "bad NDATA"
end
r = nd + #nn
end
if not isPe then
external[ename] = true
end
end
r = match(s, "^[ \t\n]*()", r) :: any
if byte(s, r) ~= 62 then
return nil, "bad ENTITY declaration"
end
q = r + 1
elseif sub(s, q, q + 8) == "<!ELEMENT" or sub(s, q, q + 8) == "<!ATTLIST" or sub(s, q, q + 9) == "<!NOTATION" then
local kw = match(s, "^<!(%u+)", q) :: string
local r = match(s, "^[ \t\n]+()", q + 2 + #kw) :: any
if not r or not match(s, NAME, r) then
return nil, "bad " .. kw .. " declaration"
end
-- skip to the closing '>' outside quotes
while true do
local c2 = byte(s, r)
if c2 == nil then
return nil, "unterminated DOCTYPE"
elseif c2 == 34 or c2 == 39 then
local e = find(s, if c2 == 34 then '"' else "'", r + 1, true)
if not e then
return nil, "unterminated DOCTYPE"
end
r = e + 1
elseif c2 == 62 then
break
elseif c2 == 60 then
return nil, "bad " .. kw .. " declaration"
else
r += 1
end
end
q = r + 1
elseif c == nil then
return nil, "unterminated DOCTYPE"
else
return nil, "bad markup in the DOCTYPE"
end
end
q = match(s, "^[ \t\n]*()", q) :: any
end
if byte(s, q) ~= 62 then
return nil, if q > n then "unterminated DOCTYPE" else "bad DOCTYPE"
end
i = q + 1
return sub(s, start, q - 1), info
end
return function(): (string?, any, any, any)
if dead then
return nil
end
if pending then
local ev = pending
pending = nil
depth -= 1
if depth == 0 then
rootDone = true
end
return "end", ev[1]
end
while true do
if i > n then
dead = true
if depth > 0 then
return "error", "unclosed element <" .. stack[depth] .. ">", n
end
if not rootSeen then
return "error", "no root element", n
end
return nil
end
local c = byte(s, i)
if c ~= 60 then -- text
local e = find(s, "<", i, true) or (n + 1)
local raw = sub(s, i, e - 1)
local start = i
i = e
local wsOnly = not find(raw, "[^ \t\n]")
if depth == 0 then
if not wsOnly then
return fail(if rootDone then "text after the root element" else "text before the root element", start)
end
else
if find(raw, "]]>", 1, true) then
return fail("']]>' in text", start + (find(raw, "]]>", 1, true) :: number) - 1)
end
local bad = find(raw, "[%z\1-\8\11\12\14-\31]")
if bad then
return fail("control character in text", start + bad - 1)
end
if not wsOnly or keepWs or preserve[depth] then
local t = decode(raw, start, 0)
if not t then
return fail(errMsg :: string, errAt)
end
return "text", t
end
end
continue
end
local c2 = byte(s, i + 1)
if c2 == 47 then -- </
local name = match(s, NAME, i + 2)
if not name then
return fail("bad end tag", i)
end
local p = match(s, "^[ \t\n]*()", i + 2 + #name) :: any
if byte(s, p) ~= 62 then
return fail(if p > n then "unterminated end tag" else "bad end tag", p)
end
if depth == 0 or stack[depth] ~= name then
return fail("mismatched end tag </" .. name .. ">" .. (if depth > 0 then " (open: <" .. stack[depth] .. ">)" else ""), i)
end
i = p + 1
stack[depth] = nil
nsStack[depth] = nil
preserve[depth] = nil
depth -= 1
if depth == 0 then
rootDone = true
end
return "end", name
elseif c2 == 33 then -- <!
if sub(s, i + 2, i + 3) == "--" then
local e = find(s, "--", i + 4, true)
if not e then
return fail("unterminated comment", i)
end
if byte(s, e + 2) ~= 62 then
return fail(if e + 2 > n then "unterminated comment" else "'--' inside a comment", e)
end
local text = sub(s, i + 4, e - 1)
i = e + 3
return "comment", text
elseif sub(s, i + 2, i + 8) == "[CDATA[" then
if depth == 0 then
return fail("CDATA outside the root element", i)
end
local e = find(s, "]]>", i + 9, true)
if not e then
return fail("unterminated CDATA section", i)
end
local text = sub(s, i + 9, e - 1)
i = e + 3
return "cdata", text
elseif sub(s, i + 2, i + 8) == "DOCTYPE" then
if rootSeen then
return fail("DOCTYPE after the root element", i)
end
local at = i
i += 9
local raw, info = doctype()
if not raw then
return fail(info, at)
end
return "doctype", raw, info
end
return fail("bad markup declaration", i)
elseif c2 == 63 then -- <?
local target = match(s, NAME, i + 2)
if not target then
return fail("bad processing instruction", i)
end
local e = find(s, "?>", i + 2 + #target, true)
if not e then
return fail("unterminated processing instruction", i)
end
local data = sub(s, i + 2 + #target, e - 1)
if data ~= "" and not find(data, "^[ \t\n]") then
return fail("bad processing instruction", i)
end
data = match(data, "^[ \t\n]*(.-)$") :: string
local at = i
i = e + 2
if lower(target) == "xml" then
if target ~= "xml" or at ~= 1 then
return fail("misplaced XML declaration", at)
end
local decl = xmlDecl(data)
if not decl then
return fail("bad XML declaration", at)
end
return "decl", decl
end
return "pi", target, data
end
-- a start tag
local name = match(s, NAME, i + 1)
if not name then
return fail(if i + 1 > n then "truncated tag" else "bad tag name", i + 1)
end
if rootDone then
return fail("a second root element <" .. name .. ">", i)
end
local at = i
local p = i + 1 + #name
local attrs = Types.object()
local order = {}
local closed = false
local nsMap: { [string]: string }? = nil
while true do
local q = match(s, "^[ \t\n]*()", p) :: any
local cc = byte(s, q)
if cc == 62 then
p = q + 1
break
elseif cc == 47 then
if byte(s, q + 1) ~= 62 then
return fail("bad tag end", q)
end
p = q + 2
closed = true
break
elseif cc == nil then
return fail("truncated tag", q)
end
if q == p then
return fail("missing whitespace between attributes", q)
end
local an = match(s, NAME, q)
if not an then
return fail("bad attribute name", q)
end
local r = match(s, "^[ \t\n]*=[ \t\n]*()", q + #an) :: any
if not r then
return fail("attribute " .. an .. " without a value", q)
end
local qc = byte(s, r)
if qc ~= 34 and qc ~= 39 then
return fail("unquoted attribute value", r)
end
local e = find(s, if qc == 34 then '"' else "'", r + 1, true)
if not e then
return fail("unterminated attribute value", r)
end
local raw = sub(s, r + 1, e - 1)
if find(raw, "<", 1, true) then
return fail("'<' in an attribute value", r)
end
if find(raw, "[%z\1-\8\11\12\14-\31]") then
return fail("control character in an attribute value", r)
end
local v = decode(raw, r + 1, 0)
if not v then
return fail(errMsg :: string, errAt)
end
if find(raw, "[\t\n]") then
-- attribute-value normalization: literal tab / newline become spaces (references stay)
v = decode((gsub(raw, "[\t\n]", " ")), r + 1, 0) :: string
end
if attrs[an] ~= nil then
return fail("duplicate attribute " .. an, q)
end
attrs[an] = v
table.insert(order, an)
if nsOn then
if an == "xmlns" or sub(an, 1, 6) == "xmlns:" then
local m: { [string]: string } = nsMap or {}
nsMap = m
m[if an == "xmlns" then "" else sub(an, 7)] = v
end
end
p = e + 1
end
Types.object(attrs, order)
i = p
depth += 1
if depth > maxDepth then
return fail("nested deeper than " .. maxDepth, at)
end
stack[depth] = name
nsStack[depth] = nsMap :: any
local sp = attrs["xml:space"]
preserve[depth] = if sp == "preserve" then true elseif sp == "default" then false else (preserve[depth - 1] or false)
rootSeen = true
local uri: string? = nil
if nsOn then
local prefix = match(name, "^([^:]*):") or ""
uri = lookupNs(prefix)
if uri == "" then
uri = nil
end
if prefix ~= "" and uri == nil then
return fail("undeclared namespace prefix " .. prefix, at)
end
end
if closed then
stack[depth] = nil
nsStack[depth] = nil
preserve[depth] = nil
pending = { name } -- depth goes down when the queued "end" is returned
end
return "start", name, attrs, uri
end
end
end
-- lookup(nsMaps...) helper for the DOM: the namespace URI of prefix, walking an element's ancestors
function Parse.resolve(node: any, prefix: string): string?
local p = node
local key = if prefix == "" then "xmlns" else "xmlns:" .. prefix
while p do
local a = p.attrs
if a and a[key] ~= nil then
local v = a[key]
return if v == "" then nil else v
end
p = p.parent
end
if prefix == "xml" then
return "http://www.w3.org/XML/1998/namespace"
end
return nil
end
return Parse
+440
View File
@@ -0,0 +1,440 @@
--!strict
-- codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ...
-- use. New code. Supports: UTF-8 / UTF-16 / Latin-1 input, the predefined entities, character references, internal
-- DOCTYPE entities (expansion limited), CDATA, comments, processing instructions, the XML declaration, namespaces
-- (names stay qualified "prefix:local"; opts.namespaces adds each element's URI as node.ns; Xml.clark gives
-- "{uri}local"), xml:space. Not supported: external entities / DTDs, validation, entity values containing markup.
--
-- local Xml = require("@formats/codecs/Xml")
-- local doc, err = Xml.decode(text) -- a "#document" node; doc.root is the root element
-- for _, item in Xml.children(doc.root, "item") do print(item.attrs.id, Xml.text(item)) end
-- for ev, a, b in Xml.events(text) do ... end -- "start" name attrs / "end" name / "text" s / ... (SAX-like)
-- local s = Xml.encode(doc, { indent = 2 })
-- local e = Xml.element("svg", { width = "10" }, { Xml.element("rect") }) -- build trees
--
-- Nodes (Types.XmlNode): { name, attrs (a Types.object: attribute order kept), children = { node | string },
-- parent }. Text children are strings. With opts.comments / opts.cdata / opts.pi, comments, CDATA sections and
-- processing instructions are kept as "#comment" / "#cdata" / "#pi" nodes (text = the content, target = the PI
-- target); otherwise CDATA merges into the text and the others are dropped. Never throws.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Parse = require("@formats/codecs/Xml/Parse")
local Xml = {}
export type Node = Types.XmlNode
export type DecodeOptions = Parse.Options & {
comments: boolean?, -- keep comments as "#comment" nodes (default false)
cdata: boolean?, -- keep CDATA sections as "#cdata" nodes (default false: merged into the text)
pi: boolean?, -- keep processing instructions as "#pi" nodes (default false)
parents: boolean?, -- set node.parent (default true)
}
export type EncodeOptions = {
indent: (number | string)?, -- pretty print elements that hold only elements (default none)
declaration: boolean?, -- write <?xml version="1.0" encoding="UTF-8"?> (default: true for a "#document")
selfClose: boolean?, -- <a/> for empty elements (default true)
}
local find, gsub, sub, match = string.find, string.gsub, string.sub, string.match
local function text(src: any): (string?, Err.Err?)
if type(src) == "string" then
return src, nil
elseif type(src) == "buffer" then
return buffer.tostring(src), nil
end
return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src))
end
local function errCode(msg: string, at: number, n: number): string
if find(msg, "unterminated", 1, true) or find(msg, "truncated", 1, true) or find(msg, "unclosed", 1, true) or at >= n then
return Err.TRUNCATED
elseif find(msg, "over the limit", 1, true) or find(msg, "nested deeper", 1, true) then
return Err.LIMIT
elseif find(msg, "not supported", 1, true) or find(msg, "unsupported", 1, true) then
return Err.UNSUPPORTED
end
return Err.CORRUPT
end
-- events(src, opts?) -> iterator: event, a, b, c (see codecs/Xml/Parse: "decl", "doctype", "start" name attrs ns,
-- "end" name, "text" s, "cdata" s, "comment" s, "pi" target data, and on bad input "error" Err as the last event)
function Xml.events(src: string | buffer, opts: Parse.Options?): () -> (string?, any, any, any)
local s, terr = text(src)
local u, enc = nil, ""
if s then
u, enc = Parse.toUtf8(s)
end
if not u then
local e = terr or Err.new(if find(enc, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT, enc)
local done = false
return function(): (string?, any, any, any)
if done then
return nil
end
done = true
return "error", e
end
end
local str: string = u
local nextEv = Parse.events(str, opts)
return function(): (string?, any, any, any)
local ev, a, b, c = nextEv()
if ev == "error" then
return ev, Err.new(errCode(a, b, #str), a, b)
end
return ev, a, b, c
end
end
-- decode(src, opts?) -> the "#document" node | nil, Err. doc.root = the root element; doc.declaration = { version,
-- encoding, standalone }?; doc.doctype = { raw, name, publicId, systemId, entities }?; doc.children = the root plus
-- any kept comments / PIs around it.
function Xml.decode(src: string | buffer, opts: DecodeOptions?): (Node?, Err.Err?)
local o: DecodeOptions = opts or {}
local keepComments, keepCdata, keepPi = o.comments == true, o.cdata == true, o.pi == true
local parents = o.parents ~= false
local doc: any = { name = "#document", attrs = Types.object(), children = {}, parent = nil }
local cur: any = doc
local stack = { doc }
local depth = 1
for ev, a, b, c in Xml.events(src, o) do
if ev == "start" then
local node: any = { name = a, attrs = b, children = {}, parent = if parents then cur else nil }
if c then
node.ns = c
end
table.insert(cur.children, node)
depth += 1
stack[depth] = node
cur = node
if depth == 2 then
doc.root = node
end
elseif ev == "end" then
stack[depth] = nil
depth -= 1
cur = stack[depth]
elseif ev == "text" or (ev == "cdata" and not keepCdata) then
local ch = cur.children
local last = #ch
if last > 0 and type(ch[last]) == "string" then
ch[last] ..= a
else
ch[last + 1] = a
end
elseif ev == "cdata" then
table.insert(cur.children, { name = "#cdata", attrs = Types.object(), children = {}, text = a, parent = if parents then cur else nil })
elseif ev == "comment" then
if keepComments then
table.insert(cur.children, { name = "#comment", attrs = Types.object(), children = {}, text = a, parent = if parents then cur else nil })
end
elseif ev == "pi" then
if keepPi then
table.insert(cur.children, { name = "#pi", attrs = Types.object(), children = {}, target = a, text = b, parent = if parents then cur else nil })
end
elseif ev == "decl" then
doc.declaration = a
elseif ev == "doctype" then
doc.doctype = { raw = a, name = b.name, publicId = b.publicId, systemId = b.systemId, entities = b.entities }
elseif ev == "error" then
return nil, a
end
end
return doc, nil
end
-- ------------------------------------------------------------------------------------------------ tree helpers
-- element(name, attrs?, children?) -> a new element (attrs: a plain table (written sorted) or a Types.object;
-- children: nodes or strings; their parent is set)
function Xml.element(name: string, attrs: { [string]: string }?, children: { any }?): Node
local a = attrs or Types.object()
if not Types.isObject(a) then
local keys = {}
for k in next, a do
table.insert(keys, k)
end
table.sort(keys)
a = Types.object(a, keys)
end
local node: any = { name = name, attrs = a, children = children or {} }
for _, ch in node.children do
if type(ch) == "table" then
ch.parent = node
end
end
return node
end
-- document(root, declaration?) -> a "#document" node around root
function Xml.document(root: Node, declaration: { [string]: string }?): Node
local doc: any = { name = "#document", attrs = Types.object(), children = { root }, root = root, declaration = declaration }
root.parent = doc
return doc
end
-- append(parent, child) -> child (a node or a string), parent link set
function Xml.append(parent: Node, child: any): any
table.insert(parent.children, child)
if type(child) == "table" then
child.parent = parent
end
return child
end
-- setAttr(node, name, value): set (or with nil remove) an attribute, keeping the order
function Xml.setAttr(node: Node, name: string, value: string?)
Types.set(node.attrs, name, value)
end
-- children(node, name?) -> the element children (with that qualified name, or local name when name has no prefix and
-- the child's does), in order
function Xml.children(node: Node, name: string?): { Node }
local out = {}
for _, ch in node.children do
if type(ch) == "table" and string.byte(ch.name) ~= 35 then
if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then
table.insert(out, ch)
end
end
end
return out
end
-- child(node, name?) -> the first matching element child, or nil
function Xml.child(node: Node, name: string?): Node?
for _, ch in node.children do
if type(ch) == "table" and string.byte(ch.name) ~= 35 then
if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then
return ch
end
end
end
return nil
end
-- descendants(node, name?) -> every element below node (document order), optionally filtered as children() does
function Xml.descendants(node: Node, name: string?): { Node }
local out = {}
local function walk(n: Node)
for _, ch in n.children do
if type(ch) == "table" and string.byte(ch.name) ~= 35 then
if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then
table.insert(out, ch)
end
walk(ch)
end
end
end
walk(node)
return out
end
-- text(node) -> all the character data below node, concatenated (CDATA included, comments / PIs not)
function Xml.text(node: any): string
if type(node) == "string" then
return node
end
if node.name == "#cdata" then
return node.text or ""
end
local parts = {}
local function walk(n: any)
for _, ch in n.children do
if type(ch) == "string" then
table.insert(parts, ch)
elseif ch.name == "#cdata" then
table.insert(parts, ch.text or "")
elseif string.byte(ch.name) ~= 35 then
walk(ch)
end
end
end
walk(node)
return table.concat(parts)
end
-- prefix(name) / localName(name): the parts of a qualified name ("svg:rect" -> "svg", "rect"; "rect" -> "", "rect")
function Xml.prefix(name: string): string
return match(name, "^([^:]*):") or ""
end
function Xml.localName(name: string): string
return match(name, ":(.*)$") or name
end
-- namespace(node, prefix?) -> the URI bound to prefix (default: the node's own prefix) at node, through its
-- ancestors' xmlns attributes (needs parent links)
function Xml.namespace(node: Node, prefix: string?): string?
return Parse.resolve(node, prefix or Xml.prefix(node.name))
end
-- clark(node, attrName?) -> "{uri}local" (ElementTree's notation) for the element, or for one of its attributes
-- (unprefixed attributes have no namespace)
function Xml.clark(node: Node, attrName: string?): string
local name = attrName or node.name
local prefix = Xml.prefix(name)
if attrName and prefix == "" then
return name
end
local uri = Parse.resolve(node, prefix)
if uri then
return "{" .. uri .. "}" .. Xml.localName(name)
end
return name
end
-- ------------------------------------------------------------------------------------------------ encode
local TEXT_ESC = { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ["\r"] = "&#13;" }
local ATTR_ESC = { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;", ["\t"] = "&#9;", ["\n"] = "&#10;", ["\r"] = "&#13;" }
-- escape(s) / escapeAttr(s): text / attribute-value escaping
function Xml.escape(s: string): string
return (gsub(s, "[&<>\r]", TEXT_ESC))
end
function Xml.escapeAttr(s: string): string
return (gsub(s, '[&<>"\t\n\r]', ATTR_ESC))
end
local function badName(name: any): boolean
return type(name) ~= "string" or not match(name, "^[%a_:\128-\255][%w_:%.%-\128-\255]*$")
end
-- encode(node, opts?) -> string | nil, Err. node: a "#document" or any node (an element, a comment, ...)
function Xml.encode(node: Node, opts: EncodeOptions?): (string?, Err.Err?)
local o: EncodeOptions = opts or {}
local ind: string? = nil
if type(o.indent) == "number" then
ind = if o.indent > 0 then string.rep(" ", o.indent) else nil
elseif type(o.indent) == "string" then
ind = o.indent
end
local selfClose = o.selfClose ~= false
local out: { string } = {}
local err: string? = nil
local seen: { [any]: boolean } = {}
local write: (n: any, depth: number) -> ()
function write(n: any, depth: number)
if err then
return
end
if type(n) == "string" then
table.insert(out, Xml.escape(n))
return
end
if type(n) ~= "table" or type(n.name) ~= "string" then
err = "a child is not a node or a string"
return
end
if seen[n] then
err = "a node appears twice (a cycle?)"
return
end
seen[n] = true
local name = n.name
if name == "#comment" then
local t = n.text or ""
if find(t, "--", 1, true) or sub(t, -1) == "-" then
err = "comment text contains '--'"
return
end
table.insert(out, "<!--" .. t .. "-->")
elseif name == "#cdata" then
table.insert(out, "<![CDATA[" .. gsub(n.text or "", "]]>", "]]]]><![CDATA[>") .. "]]>")
elseif name == "#pi" then
if badName(n.target) or find(n.text or "", "?>", 1, true) then
err = "bad processing instruction"
return
end
table.insert(out, "<?" .. n.target .. (if n.text and n.text ~= "" then " " .. n.text else "") .. "?>")
elseif name == "#doctype" then
table.insert(out, "<!DOCTYPE" .. (n.text or "") .. ">")
elseif name == "#document" then
for i, ch in n.children do
if i > 1 and ind then
table.insert(out, "\n")
end
write(ch, 0)
end
else
if badName(name) then
err = "bad element name " .. tostring(name)
return
end
table.insert(out, "<" .. name)
local attrs = n.attrs or {}
for _, k in Types.keys(attrs) do
local v = attrs[k]
if badName(k) then
err = "bad attribute name " .. tostring(k)
return
end
if type(v) == "number" or type(v) == "boolean" then
v = tostring(v)
elseif type(v) ~= "string" then
err = "attribute " .. k .. " is not a string"
return
end
table.insert(out, " " .. k .. '="' .. Xml.escapeAttr(v) .. '"')
end
local ch = n.children or {}
if #ch == 0 then
table.insert(out, if selfClose then "/>" else "></" .. name .. ">")
return
end
table.insert(out, ">")
local pretty = ind ~= nil
if pretty then
for _, c in ch do
if type(c) == "string" or c.name == "#cdata" then
pretty = false
break
end
end
end
for _, c in ch do
if pretty then
table.insert(out, "\n" .. string.rep(ind :: string, depth + 1))
end
write(c, depth + 1)
end
if pretty then
table.insert(out, "\n" .. string.rep(ind :: string, depth))
end
table.insert(out, "</" .. name .. ">")
end
end
local decl = o.declaration
if decl == nil then
decl = node.name == "#document"
end
if decl then
local d: any = node.declaration or {}
table.insert(out, '<?xml version="' .. (d.version or "1.0") .. '" encoding="UTF-8"' .. (if d.standalone then ' standalone="' .. d.standalone .. '"' else "") .. "?>")
table.insert(out, "\n")
end
if node.name == "#document" and node.doctype then
local dt: any = node.doctype
local raw = dt.raw
if raw == nil then
raw = " " .. (dt.name or (if node.root then node.root.name else "root"))
if dt.publicId then
raw ..= ' PUBLIC "' .. dt.publicId .. '" "' .. (dt.systemId or "") .. '"'
elseif dt.systemId then
raw ..= ' SYSTEM "' .. dt.systemId .. '"'
end
end
table.insert(out, "<!DOCTYPE" .. raw .. ">\n")
end
write(node, 0)
if err then
return nil, Err.new(Err.ARG, err)
end
if ind and node.name == "#document" then
table.insert(out, "\n")
end
return table.concat(out), nil
end
return Xml
+197
View File
@@ -0,0 +1,197 @@
-- codecs/Xml tests: random documents (namespaces, escapes, CDATA, comments, PIs, DOCTYPE entities, UTF-16, Latin-1)
-- against Python's ElementTree trees; encode -> decode round trips; well-formedness verdicts against expat
-- (hand-written cases and random mutations); events, helpers, options, error codes; the fuzz pass.
-- Fixtures: tools/fixtures/xml.py.
local T = require("@tests/T")
local Xml = require("@formats/codecs/Xml")
local Types = require("@formats/Types")
local Err = require("@formats/core/Err")
local Docs = require("@tests/gen/xml_docs")
local Wf = require("@tests/gen/xml_wf")
local t = T.suite("xml")
-- ElementTree's view of an element (tools/fixtures/xml.py canon): Clark names, xmlns attributes dropped, text / tail
local function s(x: string?): string
x = x or ""
return #(x :: string) .. ":" .. (x :: string)
end
local function canon(e: any, tail: string?): string
local out = { "(" .. s(Xml.clark(e)) }
local keys = {}
local vals = {}
for _, k in Types.keys(e.attrs) do
if k ~= "xmlns" and string.sub(k, 1, 6) ~= "xmlns:" then
local ck = Xml.clark(e, k)
table.insert(keys, ck)
vals[ck] = e.attrs[k]
end
end
table.sort(keys)
for _, k in keys do
table.insert(out, "|" .. s(k) .. "=" .. s(vals[k]))
end
-- text: strings before the first element child; each child's tail: strings after it
local text = {}
local i = 1
local ch = e.children
while i <= #ch and (type(ch[i]) == "string" or ch[i].name == "#cdata") do
table.insert(text, Xml.text(ch[i]))
i += 1
end
table.insert(out, "|t" .. s(table.concat(text)))
while i <= #ch do
local c = ch[i]
i += 1
local tl = {}
while i <= #ch and (type(ch[i]) == "string" or ch[i].name == "#cdata") do
table.insert(tl, Xml.text(ch[i]))
i += 1
end
table.insert(out, canon(c, table.concat(tl)))
end
return table.concat(out) .. ")t" .. s(tail)
end
-- 1. documents vs ElementTree, and round trips
for i, d in Docs do
local doc, err = Xml.decode(d.data, { whitespace = true })
t:check(doc, "doc " .. i .. ": " .. tostring(err))
t:eq(canon((doc :: any).root), d.canon, "doc " .. i .. ": tree")
-- keep everything, encode, decode again: the same tree
local full = Xml.decode(d.data, { whitespace = true, comments = true, cdata = true, pi = true }) :: any
local out, eerr = Xml.encode(full)
t:check(out, "doc " .. i .. ": encodes (" .. tostring(eerr) .. ")")
local again, aerr = Xml.decode(out :: string, { whitespace = true })
t:check(again, "doc " .. i .. ": re-decodes (" .. tostring(aerr) .. ")")
t:eq(canon((again :: any).root), d.canon, "doc " .. i .. ": round trip")
local pretty = Xml.encode(full, { indent = 2 }) :: string
t:check(Xml.decode(pretty), "doc " .. i .. ": pretty output parses")
-- the namespace option agrees with the clark helper
local nsdoc = Xml.decode(d.data, { namespaces = true }) :: any
local root = nsdoc.root
local want = string.match(Xml.clark(root), "^{([^}]*)}")
t:eq(root.ns, want, "doc " .. i .. ": node.ns")
end
-- 2. well-formedness against expat
local agree, total, accepted, rejected = 0, 0, 0, 0
for i, c in Wf do
local doc = Xml.decode(c.data)
local ok = doc ~= nil
total += 1
if ok == c.ok then
agree += 1
elseif i <= 60 then
t:check(false, "wf case " .. i .. " " .. string.format("%q", c.data) .. ": expat says " .. tostring(c.ok))
end
if c.ok then
accepted += 1
else
rejected += 1
end
end
t:note("well-formedness: %d of %d verdicts agree with expat (%d well-formed, %d not)", agree, total, accepted, rejected)
t:check(agree >= total * 0.99, "well-formedness agreement >= 99%")
-- 3. API details
do
local src = '<?xml version="1.0"?>\n<!DOCTYPE r [<!ENTITY e "E&#38;#38;">]>\n<!--c--><r xmlns="urn:d" xmlns:p="urn:p" z="1" a="2"><p:x p:k="v">t<![CDATA[<c>]]>u</p:x><?go now?><y/>\n</r>'
local doc = Xml.decode(src, { comments = true, cdata = true, pi = true, namespaces = true }) :: any
t:eq(doc.declaration.version, "1.0", "declaration")
t:eq(doc.doctype.name, "r", "doctype name")
t:eq(doc.doctype.entities.e, "E&#38;", "doctype entities (char refs expanded once)")
t:eq(doc.children[1].name, "#comment", "prolog comment kept")
local r = doc.root
t:eq(table.concat(Types.keys(r.attrs), ","), "xmlns,xmlns:p,z,a", "attribute order")
t:eq(r.ns, "urn:d", "default namespace")
local x = Xml.child(r, "x") :: any
t:eq(x.name, "p:x", "child by local name")
t:eq(x.ns, "urn:p", "prefixed namespace")
t:eq(Xml.clark(x, "p:k"), "{urn:p}k", "attribute clark")
t:eq(x.children[2].name, "#cdata", "cdata node")
t:eq(Xml.text(x), "t<c>u", "text with cdata")
t:eq(r.children[2].name, "#pi", "pi node")
t:eq(r.children[2].target .. "|" .. r.children[2].text, "go|now", "pi target / data")
t:eq(#Xml.children(r), 2, "element children")
t:eq(#Xml.descendants(doc), 3, "descendants")
t:eq(x.parent, r, "parent link")
t:eq(Xml.decode("<a>&e;</a>") == nil, true, "undefined entity")
local d2 = Xml.decode('<!DOCTYPE r [<!ENTITY e "E&#38;#38;">]><r a="&e;">&e;</r>') :: any
t:eq(d2.root.attrs.a, "E&", "entity in attribute")
t:eq(Xml.text(d2.root), "E&", "entity in text")
-- whitespace handling
local w = Xml.decode("<a>\n <b> x </b>\n <c xml:space='preserve'> </c>\n</a>") :: any
t:eq(#w.root.children, 2, "whitespace-only text dropped")
t:eq(Xml.text(w.root.children[1]), " x ", "other text kept as is")
t:eq(w.root.children[2].children[1], " ", "xml:space preserve")
t:eq(#(Xml.decode("<a>\n <b/>\n</a>", { whitespace = true }) :: any).root.children, 3, "opts.whitespace")
-- attribute normalization and line endings
local n = Xml.decode("<a b='x\ty\r\nz&#10;'>l1\r\nl2\rl3</a>") :: any
t:eq(n.root.attrs.b, "x y z\n", "attribute value normalization")
t:eq(Xml.text(n.root), "l1\nl2\nl3", "line endings")
-- builders and encode
local e = Xml.element("svg", { width = "10", height = "5" }, { Xml.element("rect", { x = "1" }), "a<b & \"c\"" })
Xml.setAttr(e, "id", "q\"\n")
t:eq(Xml.encode(e), '<svg height="5" width="10" id="q&quot;&#10;"><rect x="1"/>a&lt;b &amp; "c"</svg>', "encode element")
local d3 = Xml.document(Xml.element("r", nil, { Xml.element("a"), Xml.element("b", nil, { "t" }) }))
t:eq(Xml.encode(d3, { indent = 2 }), '<?xml version="1.0" encoding="UTF-8"?>\n<r>\n <a/>\n <b>t</b>\n</r>\n', "pretty document")
t:eq(Xml.encode(Xml.element("a"), { selfClose = false }), "<a></a>", "selfClose false")
local _, be = Xml.encode(Xml.element("1bad"))
t:eq(be and be.code, Err.ARG, "bad name on encode")
local cyc = Xml.element("a")
table.insert(cyc.children, cyc)
local _, ce = Xml.encode(cyc)
t:eq(ce and ce.code, Err.ARG, "cycle on encode")
t:eq(Xml.encode({ name = "#cdata", attrs = Types.object(), children = {}, text = "a]]>b" } :: any), "<![CDATA[a]]]]><![CDATA[>b]]>", "cdata split")
-- events
local evs = {}
for ev, a in Xml.events("<a x='1'><b>t</b><!--c--></a>") do
table.insert(evs, ev .. (if type(a) == "string" then ":" .. a else ""))
end
t:eq(table.concat(evs, " "), "start:a start:b text:t end:b comment:c end:a", "events")
local last
for ev, a in Xml.events("<a><b></a>") do
last = { ev, a }
end
t:eq(last[1], "error", "events error")
t:eq(last[2].code, Err.CORRUPT, "events error code")
-- UTF-16 without BOM and encodings
local u16 = buffer.create(8)
for k, ch in { 60, 0, 97, 0, 47, 0, 62, 0 } do
buffer.writeu8(u16, k - 1, ch)
end
t:eq((Xml.decode(u16) :: any).root.name, "a", "UTF-16LE without BOM")
local _, ue = Xml.decode("<?xml version='1.0' encoding='EBCDIC'?><a/>")
t:eq(ue and ue.code, Err.UNSUPPORTED, "unsupported encoding")
end
-- 4. errors and limits
local function code(src: string, opts: any?): string?
local _, e = Xml.decode(src, opts)
return e and e.code
end
t:eq(code("<a><b>"), Err.TRUNCATED, "unclosed")
t:eq(code("<a></b>"), Err.CORRUPT, "mismatch")
t:eq(code("<a b='1' b='2'/>"), Err.CORRUPT, "duplicate attribute")
t:eq(code(string.rep("<a>", 60) .. string.rep("</a>", 60), { maxDepth = 50 }), Err.LIMIT, "maxDepth")
t:eq(code('<!DOCTYPE r [<!ENTITY a "aaaaaaaaaa"><!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;"><!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;"><!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;"><!ENTITY e "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">]><r>&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;</r>', { maxExpansion = 100000 }), Err.LIMIT, "billion laughs")
t:eq(code('<!DOCTYPE r [<!ENTITY a "&a;">]><r>&a;</r>'), Err.CORRUPT, "recursive entity")
t:eq(code('<!DOCTYPE r [<!ENTITY x SYSTEM "file.xml">]><r>&x;</r>'), Err.UNSUPPORTED, "external entity")
t:eq(code("<p:a/>", { namespaces = true }), Err.CORRUPT, "undeclared prefix")
local _, ae = Xml.decode(5 :: any)
t:eq(ae and ae.code, Err.ARG, "bad argument")
-- 5. fuzz
local samples = {}
for i = 1, 40 do
table.insert(samples, Docs[i].data)
end
t:fuzz("decode", function(b: buffer)
return Xml.decode(b, { comments = true, namespaces = true })
end, samples)
t:fuzz("encode(decode)", function(b: buffer)
local d = Xml.decode(b, { comments = true, cdata = true, pi = true })
return d and Xml.encode(d, { indent = 1 })
end, samples, { garbage = 20 })
t:done()
+15
View File
@@ -71,3 +71,18 @@ do
Json.encode(v) Json.encode(v)
end) end)
end end
do
local Xml = require("@formats/codecs/Xml")
local XB = require("@tests/gen/xml_bench")
local doc = assert(Xml.decode(XB.text))
bench("xml decode (DOM)", 5, #XB.text, function()
Xml.decode(XB.text)
end)
bench("xml events", 5, #XB.text, function()
for _ in Xml.events(XB.text) do
end
end)
bench("xml encode", 5, #XB.text, function()
Xml.encode(doc)
end)
end
+1 -1
View File
@@ -3,7 +3,7 @@
cd "$(dirname "$0")/.." || exit 1 cd "$(dirname "$0")/.." || exit 1
LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')} LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')}
LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')} LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')}
python3 -I tools/fixtures.py deflate png json > /dev/null || exit 1 python3 -I tools/fixtures.py deflate png json xml > /dev/null || exit 1
python3 -I tools/build.py luajit > /dev/null || exit 1 python3 -I tools/build.py luajit > /dev/null || exit 1
"$LUAU" --codegen -O2 tools/bench.luau "$LUAU" --codegen -O2 tools/bench.luau
"$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua "$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua
+174
View File
@@ -0,0 +1,174 @@
# codecs/Xml + data/xml fixtures: random documents (namespaces, attributes with every escape, CDATA, comments, PIs,
# entities from an internal DOCTYPE, mixed content) written by hand, then parsed by Python's xml.etree (expat) for the
# reference tree; the same documents re-encoded as UTF-16 and Latin-1; and well-formedness cases (hand-written plus
# random mutations) with expat's verdict.
# tests/gen/xml_docs.luau { { data, canon } } canon: see canon() below (the test computes the same)
# tests/gen/xml_wf.luau { { data, ok } } ok: expat accepts it
# tests/gen/xml_bench.luau { text } (~1 MB)
import xml.etree.ElementTree as ET
from xml.parsers import expat
NS = [("", None), ("a", "urn:a"), ("b", "http://example.com/b")]
TAGS = ["item", "x", "Data", "set-1", "q.r", "_u", "élément", "名"]
TXT = "ab <>&\"' é中\U0001f600\t\n ]]"
def s(x):
x = x or ""
b = x.encode("utf-8", "surrogatepass")
return b"%d:" % len(b) + b
def canon(e):
out = b"(" + s(e.tag)
for k in sorted(e.attrib):
out += b"|" + s(k) + b"=" + s(e.attrib[k])
out += b"|t" + s(e.text)
for c in e:
out += canon(c)
return out + b")t" + s(e.tail)
def esc_text(t):
return t.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def esc_attr(t, q):
t = t.replace("&", "&amp;").replace("<", "&lt;")
return t.replace(q, "&quot;" if q == '"' else "&apos;")
def rand_text(rng):
return "".join(rng.choice(TXT) for _ in range(rng.randrange(0, 10)))
def gen_elem(rng, depth, declared):
prefix = rng.choice([p for p in declared])
local = rng.choice(TAGS)
name = (prefix + ":" + local) if prefix else local
attrs = []
newdecl = set(declared)
if depth > 0 and rng.random() < 0.15:
p, uri = rng.choice(NS[1:])
attrs.append(("xmlns:" + p, uri))
newdecl.add(p)
if rng.random() < 0.1:
attrs.append(("xmlns", "urn:default%d" % rng.randrange(3)))
used = set(a for a, _ in attrs)
for _ in range(rng.randrange(0, 4)):
an = rng.choice(["id", "k", "v-1", "é", "x.y"])
if rng.random() < 0.2 and len(newdecl) > 1:
an = rng.choice([p for p in newdecl if p]) + ":" + an
if an in used:
continue
used.add(an)
attrs.append((an, rand_text(rng)))
parts = ["<" + name]
for k, v in attrs:
q = rng.choice("\"'")
parts.append(" %s=%s%s%s" % (k, q, esc_attr(v, q), q))
if depth > 4 or rng.random() < 0.15:
parts.append(rng.choice(["/>", " />"]))
return "".join(parts)
parts.append(">")
for _ in range(rng.randrange(0, 5)):
r = rng.random()
if r < 0.35:
parts.append(esc_text(rand_text(rng)))
elif r < 0.45:
parts.append("<![CDATA[" + rand_text(rng).replace("]", "] ") + "<&>]]>")
elif r < 0.5:
parts.append("<!-- c " + rand_text(rng).replace("-", "=") + " -->")
elif r < 0.53:
parts.append("<?pi data " + rand_text(rng).replace("?", "") + "?>")
elif r < 0.58:
parts.append(rng.choice(["&ent;", "&#233;", "&#x1F600;", "&amp;", "&lt;", "&#10;"]))
else:
parts.append(gen_elem(rng, depth + 1, newdecl))
parts.append("</%s>" % name)
return "".join(parts)
def gen_doc(rng):
head = ""
if rng.random() < 0.5:
head += '<?xml version="1.0" encoding="UTF-8"?>\n'
head += '<!DOCTYPE root [\n <!ENTITY ent "entity &#38;#38; text &lt;">\n <!-- a comment -->\n]>\n'
if rng.random() < 0.3:
head += "<!-- prolog comment -->\n"
declared = {""}
body = gen_elem(rng, 0, declared)
# the root must declare every prefix it may use: declare all at the root
root_decl = " ".join('xmlns:%s="%s"' % (p, u) for p, u in NS[1:])
i = body.index(">") if not body.startswith("<") else 0
name_end = 1
while body[name_end] not in " />":
name_end += 1
body = body[:name_end] + " " + root_decl + body[name_end:]
return head + body + ("\n" if rng.random() < 0.5 else "")
def expat_ok(data):
p = expat.ParserCreate()
try:
p.Parse(data, True)
return True
except Exception: # ExpatError, or LookupError for an unknown encoding name
return False
WF = [
"<a/>", "<a></a>", "<a><b/></a>", "<a>x</b>", "<a>", "</a>", "<a/><b/>", "text<a/>", "<a/>text", "<a b='1' b='2'/>",
"<a b=1/>", "<a b='<'/>", "<a>&undefined;</a>", "<a>&#0;</a>", "<a>&#x110000;</a>", "<a>&#xD800;</a>", "<a>& </a>",
"<a><!-- x -- y --></a>", "<a><!-- x ---></a>", "<a>]]></a>", "<1a/>", "<a 1b='x'/>", "<a b='x'c='y'/>",
"<?xml version='1.0'?><a/>", " <?xml version='1.0'?><a/>", "<a/><?xml version='1.0'?>", "<a><![CDATA[x]]></a>",
"<![CDATA[x]]><a/>", "<a><![CDATA[x</a>", "<a>\x01</a>", "<a b='\x01'/>", "<a><?pi x?></a>", "<a><?pi?></a>",
"<!DOCTYPE a><a/>", "<a/><!DOCTYPE a>", "<!DOCTYPE a [<!ENTITY e 'v'>]><a>&e;</a>", "<a b='&lt;&#65;'/>",
"<a:b xmlns:a='u'/>", "<a\n b\n =\n 'c'\n/>", "<a></a >", "<a></ a>", "< a/>", "<a/ >", "<a b='x' / >",
"<a>é\U0001f600</a>", "<a>&amp;&lt;&gt;&quot;&apos;</a>", "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><a/>",
"<!-- c --><a/><!-- d -->", "<a><!----></a>", "", " ", "<a>x</a>trailing", "<a>x</a><!-- ok --> ",
]
def generate(ctx):
rng = ctx.rng(11)
docs = []
for k in range(250):
text = gen_doc(rng)
root = ET.fromstring(text.encode("utf-8"))
docs.append({"data": text.encode("utf-8"), "canon": canon(root)})
# other encodings: UTF-16 (BOM, both byte orders) and Latin-1
for k in range(10):
text = gen_doc(rng)
body = text.split("?>", 1)[1] if text.startswith("<?xml") else text
c = canon(ET.fromstring(text.encode("utf-8")))
docs.append({"data": ('<?xml version="1.0" encoding="UTF-16"?>' + body).encode("utf-16"), "canon": c})
docs.append({"data": b"\xfe\xff" + ('<?xml version="1.0" encoding="UTF-16"?>' + body).encode("utf-16-be"), "canon": c})
for k in range(10):
text = "<?xml version='1.0' encoding='ISO-8859-1'?><r a='éÿ'>café ½ &#x4e2d;</r>"
data = text.encode("latin-1")
docs.append({"data": data, "canon": canon(ET.fromstring(data))})
ctx.emit("xml_docs", docs)
wf = [{"data": d.encode("utf-8"), "ok": expat_ok(d.encode("utf-8"))} for d in WF]
# mutations of valid documents: delete / duplicate / replace one markup character
for k in range(400):
text = gen_doc(rng).encode("utf-8")
b = bytearray(text)
for _ in range(rng.randrange(1, 3)):
pos = rng.randrange(len(b))
op = rng.randrange(3)
ch = rng.choice(b"<>/&;='\"![]-? ")
if op == 0:
del b[pos]
elif op == 1:
b.insert(pos, ch)
else:
b[pos] = ch
wf.append({"data": bytes(b), "ok": expat_ok(bytes(b))})
ctx.emit("xml_wf", wf)
parts = []
while sum(map(len, parts)) < 1_000_000:
parts.append(gen_elem(rng, 1, {""}))
ctx.emit("xml_bench", {"text": "<root>" + "\n".join(p for p in parts if "&ent;" not in p) + "</root>"})