--!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 (default: true for a "#document") selfClose: boolean?, -- 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, "") elseif name == "#cdata" then table.insert(out, "", "]]]]>") .. "]]>") elseif name == "#pi" then if badName(n.target) or find(n.text or "", "?>", 1, true) then err = "bad processing instruction" return end table.insert(out, "") elseif name == "#doctype" then table.insert(out, "") elseif name == "#document" then for i, ch in n.children do if i > 1 and ind then table.insert(out, "\n") end write(ch, 0) end else if badName(name) then err = "bad element name " .. tostring(name) return end table.insert(out, "<" .. name) local attrs = n.attrs or {} for _, k in Types.keys(attrs) do local v = attrs[k] if badName(k) then err = "bad attribute name " .. tostring(k) return end if type(v) == "number" or type(v) == "boolean" then v = tostring(v) elseif type(v) ~= "string" then err = "attribute " .. k .. " is not a string" return end table.insert(out, " " .. k .. '="' .. Xml.escapeAttr(v) .. '"') end local ch = n.children or {} if #ch == 0 then table.insert(out, if selfClose then "/>" else ">") return end table.insert(out, ">") local pretty = ind ~= nil if pretty then for _, c in ch do if type(c) == "string" or c.name == "#cdata" then pretty = false break end end end for _, c in ch do if pretty then table.insert(out, "\n" .. string.rep(ind :: string, depth + 1)) end write(c, depth + 1) end if pretty then table.insert(out, "\n" .. string.rep(ind :: string, depth)) end table.insert(out, "") end end local decl = o.declaration if decl == nil then decl = node.name == "#document" end if decl then local d: any = node.declaration or {} table.insert(out, '") table.insert(out, "\n") end if node.name == "#document" and node.doctype then local dt: any = node.doctype local raw = dt.raw if raw == nil then raw = " " .. (dt.name or (if node.root then node.root.name else "root")) if dt.publicId then raw ..= ' PUBLIC "' .. dt.publicId .. '" "' .. (dt.systemId or "") .. '"' elseif dt.systemId then raw ..= ' SYSTEM "' .. dt.systemId .. '"' end end table.insert(out, "\n") end write(node, 0) if err then return nil, Err.new(Err.ARG, err) end if ind and node.name == "#document" then table.insert(out, "\n") end return table.concat(out), nil end return Xml