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