From 492d6662dfd6c752d6c472fa88e99972dbcdf4ee Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 01:59:16 -0500 Subject: [PATCH] codecs/text: comments to specs only --- docs/FORMATS.md | 8 +-- src/Rosetta/codecs/text/Json/Decode.luau | 33 +++------- src/Rosetta/codecs/text/Json/Encode.luau | 25 +++----- src/Rosetta/codecs/text/Json/init.luau | 35 ++-------- src/Rosetta/codecs/text/Nbt/Binary.luau | 26 +++----- src/Rosetta/codecs/text/Nbt/Snbt.luau | 19 ++---- src/Rosetta/codecs/text/Nbt/Value.luau | 24 +------ src/Rosetta/codecs/text/Nbt/init.luau | 81 ++++++++---------------- src/Rosetta/codecs/text/Text/init.luau | 9 +-- src/Rosetta/codecs/text/Url/init.luau | 25 ++------ src/Rosetta/codecs/text/Xml/Parse.luau | 49 ++++---------- src/Rosetta/codecs/text/Xml/init.luau | 57 +++-------------- 12 files changed, 97 insertions(+), 294 deletions(-) diff --git a/docs/FORMATS.md b/docs/FORMATS.md index e010ee9..b0033e2 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -256,10 +256,10 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML, - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - - codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, - - codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is - - codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, - - codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... + - codecs/text/Nbt: Minecraft's Named Binary Tag format and SNBT (Minecraft wiki "NBT format", wiki.vg "NBT"). + - codecs/text/Text: text decoding helpers: BOM stripping, Windows-1252 for text that is not UTF-8, line splitting. + - codecs/text/Url: RFC 3986 reference resolution (section 5.2), local-path classification and percent-encoding. + - codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize. New code. - **video** - codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. - codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int. diff --git a/src/Rosetta/codecs/text/Json/Decode.luau b/src/Rosetta/codecs/text/Json/Decode.luau index f161130..4a7ceb1 100644 --- a/src/Rosetta/codecs/text/Json/Decode.luau +++ b/src/Rosetta/codecs/text/Json/Decode.luau @@ -1,9 +1,7 @@ --!strict --!native --- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json. Iterative (an explicit container stack, so deep nesting --- is a LIMIT error, never a stack overflow), strict grammar (no comments, trailing commas, leading zeros, NaN, single --- quotes or raw control characters), \u escapes with surrogate pairs (lone surrogates become WTF-8 bytes). Also the --- pull tokenizer behind Json.events. Never throws: failures return nil, message, offset (0-based byte offset). +-- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json: iterative, strict grammar. +-- \u escapes with surrogate pairs; lone surrogates become WTF-8 bytes. local Text = require("@rosetta/codecs/text/Text") local Types = require("@rosetta/Types") @@ -14,10 +12,10 @@ local tonumber = tonumber local concat = table.concat export type Options = { - ordered: boolean?, -- every object is a Types.object with its key order (default false: only empty objects are) - bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their exact text (default "number") - null: any?, -- the value for null (default Types.null) - maxDepth: number?, -- nesting limit (default 1000) + ordered: boolean?, + bigInts: ("number" | "string")?, + null: any?, + maxDepth: number?, } local ESC: { [number]: string } = { @@ -31,7 +29,6 @@ local ESC: { [number]: string } = { [116] = "\t", } --- utf8 bytes of a code point (surrogates too: WTF-8) local utf8char = Text.utf8char Decode.utf8char = utf8char @@ -43,7 +40,6 @@ local function hex4(s: string, i: number): number? return tonumber(h, 16) end --- string(s, i) -> value, next | nil, message, offset. i is at the opening quote. local function str(s: string, i: number): (string?, any, number?) local j = find(s, '[%z\1-\31"\\]', i + 1) if not j then @@ -102,7 +98,6 @@ local function str(s: string, i: number): (string?, any, number?) end Decode.string = str --- number(s, i) -> value, next | nil, message, offset local function num(s: string, i: number, bigStrings: boolean): (any, any, number?) local p = i if byte(s, p) == 45 then @@ -153,8 +148,6 @@ local function num(s: string, i: number, bigStrings: boolean): (any, any, number end Decode.number = num --- decode(s, i, opts) -> value, next | nil, message, offset. Parses one value starting at i (leading whitespace --- skipped); next is the position after the value (trailing whitespace not skipped). function Decode.value(s: string, i: number, opts: Options?): (any, any, number?) local o: Options = opts or {} local ordered = o.ordered == true @@ -163,9 +156,9 @@ function Decode.value(s: string, i: number, opts: Options?): (any, any, number?) local maxDepth = o.maxDepth or 1000 local object = Types.object - local stackT: { any } = {} -- containers - local stackK: { any } = {} -- object: the pending key; array: the count - local stackO: { any } = {} -- object: its key order (or true); array: false + local stackT: { any } = {} + local stackK: { any } = {} + local stackO: { any } = {} local depth = 0 local n = #s local value: any @@ -246,7 +239,6 @@ function Decode.value(s: string, i: number, opts: Options?): (any, any, number?) end value, i = v, ni end - -- attach the value to the open containers, closing them as their ends come while haveValue do if depth == 0 then return value, i @@ -303,17 +295,13 @@ function Decode.value(s: string, i: number, opts: Options?): (any, any, number?) end end --- events: a pull tokenizer. next() -> event, value | nil at the end | "error", message, offset. Events: "object", --- "endObject", "array", "endArray", "key" (string), "value" (scalar). The grammar is checked as it goes. function Decode.events(s: string, i: number, opts: Options?): () -> (string?, any, number?) local o: Options = opts or {} local bigStrings = o.bigInts == "string" local nullv = if o.null ~= nil then o.null else Types.null local maxDepth = o.maxDepth or 1000 - local stack: { boolean } = {} -- true = object + local stack: { boolean } = {} local depth = 0 - -- state: "value" (a value expected), "first" (after { or [: value / key or close), "after" (after a value), - -- "key" (a key expected), "done", "dead" local state = "value" local n = #s local function fail(msg: string, at: number): (string, any, number) @@ -378,7 +366,6 @@ function Decode.events(s: string, i: number, opts: Options?): () -> (string?, an state = "value" return "key", k end - -- a value local after = if depth == 0 then "done" else "after" if c == 123 or c == 91 then depth += 1 diff --git a/src/Rosetta/codecs/text/Json/Encode.luau b/src/Rosetta/codecs/text/Json/Encode.luau index 8fff546..e8946ea 100644 --- a/src/Rosetta/codecs/text/Json/Encode.luau +++ b/src/Rosetta/codecs/text/Json/Encode.luau @@ -1,9 +1,6 @@ --!strict --!native --- codecs/text/Json/Encode: the serializer behind codecs/text/Json. Compact or pretty (indent), objects in their Types.object key --- order (plain tables: sorted keys), arrays for tables with keys 1..n, shortest round-trip number text, optional --- ASCII-only output. Never throws: bad values (cycles, NaN / inf, functions, non-string keys that are not numbers) --- return nil, message. +-- codecs/text/Json/Encode: the RFC 8259 serializer behind codecs/text/Json. local Types = require("@rosetta/Types") local Encode = {} @@ -13,13 +10,13 @@ local floor, huge = math.floor, math.huge local concat = table.concat export type Options = { - indent: (number | string)?, -- pretty print: spaces per level (or the indent string); default compact - sortKeys: boolean?, -- plain tables' keys sorted (default true; false = next() order, faster) - ascii: boolean?, -- escape every non-ASCII character as \uXXXX (default false: UTF-8 as is) - nan: ("error" | "null")?, -- NaN / inf: an error (default) or null - emptyTable: ("array" | "object")?, -- what a plain empty table is (default "array"; Types.object() is "{}") - maxDepth: number?, -- nesting limit (default 1000; also catches cycles) - escapeSlash: boolean?, -- write / as \/ (default false) + indent: (number | string)?, + sortKeys: boolean?, + ascii: boolean?, + nan: ("error" | "null")?, + emptyTable: ("array" | "object")?, + maxDepth: number?, + escapeSlash: boolean?, } local ESCAPES: { [string]: string } = { @@ -47,7 +44,6 @@ local function utf16(cp: number): string return format("\\u%04x\\u%04x", 0xD800 + cp // 1024, 0xDC00 + cp % 1024) end --- asciify a UTF-8 string's non-ASCII sequences (invalid bytes become \u00XX of the byte: lossy but never throws) local function asciiSeq(seq: string): string local out = {} local i, n = 1, #seq @@ -69,7 +65,7 @@ local function asciiSeq(seq: string): string return concat(out) end --- string(s, ascii, slash) -> the quoted JSON string (ascii: DEL too, like Python's ensure_ascii) +-- ascii escapes DEL too, like Python's ensure_ascii local function quote(s: string, ascii: boolean?, slash: boolean?): string local pat = if slash then '[%z\1-\31"\\/]' else '[%z\1-\31"\\]' if string.find(s, pat) then @@ -85,7 +81,6 @@ end Encode.quote = quote local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" } --- number(x) -> the shortest text that reads back as x | nil for NaN / inf local function number(x: number): string? if x ~= x or x == huge or x == -huge then return nil @@ -114,7 +109,6 @@ local function keyLess(a: any, b: any): boolean return a < b end --- kind(t, emptyObject) -> "array" (keys exactly 1..n) | "object" local function kind(t: { [any]: any }, emptyObject: boolean): string if Types.isObject(t) then return "object" @@ -295,7 +289,6 @@ end Encode.state = state Encode.write = value --- encode(v, opts) -> text | nil, message function Encode.encode(v: any, opts: Options?, nullv: any?): (string?, string?) local st = state(opts, nullv) if not value(st, v, 0) then diff --git a/src/Rosetta/codecs/text/Json/init.luau b/src/Rosetta/codecs/text/Json/init.luau index 528635e..11663e0 100644 --- a/src/Rosetta/codecs/text/Json/init.luau +++ b/src/Rosetta/codecs/text/Json/init.luau @@ -1,18 +1,5 @@ --!strict -- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. --- Values are plain Luau: objects -> tables (string keys), arrays -> arrays, null -> Types.null (opts.null), numbers --- -> doubles (opts.bigInts = "string" keeps integers past 2^53 as their text). Empty objects are Types.object() so --- they write back as {}; opts.ordered makes every object a Types.object with its key order. --- --- local Json = require("@rosetta/codecs/text/Json") --- local v, err = Json.decode('{"a": [1, 2, null]}') -- string | buffer; nil, Err on bad input --- local s = Json.encode(v, { indent = 2 }) -- string | nil, Err --- for ev, x in Json.events(text) do ... end -- pull events without building the tree --- for i, v, err in Json.lines(ndjson) do ... end -- JSON Lines / concatenated JSON values --- local w = Json.writer({ indent = 2 }); w:beginObject(); w:key("a"); w:value(1); w:endObject(); w:tostring() --- --- Streaming: decodeAt(src, pos) parses one value and returns where the next begins; events() is a pull tokenizer; --- writer() builds output incrementally and flush() hands back the text so far. Never throws. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Decode = require("@rosetta/codecs/text/Json/Decode") @@ -46,8 +33,6 @@ local function fail(msg: any, at: any, n: number): Err.Err return Err.new(code, m, at) end --- decode(src, opts?) -> value | nil, Err. One JSON text: a value with optional whitespace around it (a UTF-8 BOM is --- skipped). Note a JSON null top-level value decodes to opts.null (Types.null by default), never nil. function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err?) local s, terr = text(src) if not s then @@ -65,8 +50,6 @@ function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err? return v, nil end --- decodeAt(src, pos?, opts?) -> value, nextPos | nil, Err. One value starting at pos (1-based, default 1; leading --- whitespace skipped); nextPos is just past it. nil, nil when only whitespace is left. function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?): (any, any) local s, terr = text(src) if not s then @@ -83,8 +66,6 @@ function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?) return v, ni end --- lines(src, opts?) -> iterator: index, value (JSON Lines, or any whitespace-separated sequence of JSON values). A --- bad value gives a last index, nil, Err: for i, v, err in Json.lines(s) do if err then ... end end function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, any, Err.Err?) local s, terr = text(src) local pos = 1 @@ -112,8 +93,6 @@ function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, end end --- events(src, opts?) -> iterator: event, value. Events: "object", "endObject", "array", "endArray", "key" (the key), --- "value" (a scalar), and on bad input one final "error", Err. function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string?, any) local s, terr = text(src) if not s then @@ -138,7 +117,6 @@ function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string? end end --- encode(value, opts?) -> string | nil, Err function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?) local s, msg = Encode.encode(value, opts) if not s then @@ -147,13 +125,9 @@ function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?) return s, nil end -Json.quote = Encode.quote -- quote(s) -> '"..."' with JSON escapes -Json.number = Encode.number -- number(x) -> the shortest round-trip text (nil for NaN / inf) +Json.quote = Encode.quote +Json.number = Encode.number --- ------------------------------------------------------------------------------------------------ writer --- writer(opts?) -> a streaming Writer: beginObject / endObject / beginArray / endArray / key(k) / value(v) (any --- value, encoded whole), then tostring() for everything or flush() for the text since the last flush. Misuse (a key --- outside an object, a value where a key is due, unbalanced ends) is recorded in w.err and later calls do nothing. export type Writer = { err: Err.Err?, beginObject: (self: Writer) -> Writer, @@ -169,10 +143,10 @@ export type Writer = { function Json.writer(opts: EncodeOptions?): Writer local st = Encode.state(opts) local ind = st.indent - local kinds: { boolean } = {} -- true = object + local kinds: { boolean } = {} local counts: { number } = {} local depth = 0 - local keyDone = false -- an object's key written, its value due + local keyDone = false local flushed: { string } = {} local w: any = { err = nil } local function bad(msg: string) @@ -180,7 +154,6 @@ function Json.writer(opts: EncodeOptions?): Writer w.err = Err.new(Err.ARG, msg) end end - -- before an element: a comma / newline as needed; false when the position is wrong local function slot(isKey: boolean): boolean if w.err then return false diff --git a/src/Rosetta/codecs/text/Nbt/Binary.luau b/src/Rosetta/codecs/text/Nbt/Binary.luau index a22b579..1ecab9a 100644 --- a/src/Rosetta/codecs/text/Nbt/Binary.luau +++ b/src/Rosetta/codecs/text/Nbt/Binary.luau @@ -1,9 +1,7 @@ --!strict -- codecs/text/Nbt/Binary: binary NBT read and write, from the Minecraft wiki "NBT format" page and wiki.vg "NBT". --- New code. Three encodings: big-endian (Java Edition files; strings in Java's modified UTF-8, converted to and from --- UTF-8), little-endian (Bedrock files; UTF-8) and Bedrock's network form (little-endian with zigzag varints for int / --- long and varint lengths). All thirteen tag types; values per codecs/text/Nbt/Value. Lengths are checked against --- the bytes left before anything is allocated, and nesting is limited (opts.maxDepth, default 512 like Minecraft). +-- Java big-endian (modified UTF-8 strings), Bedrock little-endian (UTF-8), and Bedrock network NBT (little-endian, +-- zigzag varint int / long, varint lengths). local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") local Value = require("@rosetta/codecs/text/Nbt/Value") @@ -11,11 +9,11 @@ local Value = require("@rosetta/codecs/text/Nbt/Value") local Binary = {} export type Options = { - endian: ("big" | "little")?, -- default "big" (Java) - varint: boolean?, -- Bedrock network NBT (little-endian, varint ints / lengths); implies endian = "little" - nameless: boolean?, -- the root tag has no name (Java network NBT since 1.20.2) - maxDepth: number?, -- nesting limit (default 512) - name: string?, -- write: the root name (default "") + endian: ("big" | "little")?, + varint: boolean?, + nameless: boolean?, + maxDepth: number?, + name: string?, } local readu8, readi8, readu32, readi16 = buffer.readu8, buffer.readi8, buffer.readu32, buffer.readi16 @@ -27,7 +25,6 @@ local newTag = Value.TagMeta type State = { b: buffer, p: number, e: number, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number, err: string?, scratch: buffer } --- ------------------------------------------------------------------------------------------------ modified UTF-8 -- Java's DataOutput strings: U+0000 as C0 80, supplementary characters as two 3-byte surrogates (CESU-8) local function fromModified(s: string): string if not string.find(s, "[\192\237]") then @@ -89,7 +86,6 @@ end Binary.fromModified = fromModified Binary.toModified = toModified --- ------------------------------------------------------------------------------------------------ read local function fail(s: State, msg: string): nil if not s.err then s.err = msg @@ -170,7 +166,7 @@ local function len(s: State): number return i32(s) end -local function i64(s: State): (number, number) -- hi, lo +local function i64(s: State): (number, number) if s.net then local lo, hi, sh = 0, 0, 0 while true do @@ -248,7 +244,6 @@ local function tag(name: string, v: any): any return setmetatable({ type = name, value = v }, newTag) end --- the smallest encoded size of one element, to bound list lengths before allocating local MIN = { [0] = 0, 1, 2, 4, 8, 4, 8, 4, 2, 5, 1, 4, 4 } local MIN_NET = { [0] = 0, 1, 2, 1, 1, 4, 8, 1, 1, 2, 1, 1, 1 } @@ -393,7 +388,6 @@ payload = function(s: State, id: number): any return fail(s, "bad tag type " .. id) end --- read(buf, pos, limit, opts?) -> value, rootName, endPos | nil, message, at function Binary.read(b: buffer, pos: number, limit: number, opts: Options?): (any, any, number?) local o: Options = opts or {} local net = o.varint == true @@ -425,7 +419,6 @@ function Binary.read(b: buffer, pos: number, limit: number, opts: Options?): (an return v, name, s.p end --- ------------------------------------------------------------------------------------------------ write type WState = { w: Bytes.Writer, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number } local function wvaruint(w: Bytes.Writer, v: number) @@ -438,7 +431,7 @@ local function wvaruint(w: Bytes.Writer, v: number) end local function wi32(ws: WState, v: number) - v %= TWO32 -- two's complement + v %= TWO32 if ws.net then local sv = if v >= 0x80000000 then v - TWO32 else v wvaruint(ws.w, if sv >= 0 then sv * 2 else -sv * 2 - 1) @@ -671,7 +664,6 @@ wpayload = function(ws: WState, t: string, v: any): string? return nil end --- write(value, opts?) -> buffer | nil, message function Binary.write(v: any, opts: Options?): (buffer?, string?) local o: Options = opts or {} local net = o.varint == true diff --git a/src/Rosetta/codecs/text/Nbt/Snbt.luau b/src/Rosetta/codecs/text/Nbt/Snbt.luau index 39456d9..ef865de 100644 --- a/src/Rosetta/codecs/text/Nbt/Snbt.luau +++ b/src/Rosetta/codecs/text/Nbt/Snbt.luau @@ -1,11 +1,6 @@ --!strict --- codecs/text/Nbt/Snbt: stringified NBT (the text form of /data and /give), parse and print. New code, from the --- Minecraft wiki "NBT format" SNBT section (Java 1.21.5 grammar). Parses: compounds, lists, [B; ...] [I; ...] [L; ...] --- arrays, quoted strings ('...' / "..." with \\ \' \" \n \t \r \b \f \s \xNN \uNNNN \UNNNNNNNN escapes) and unquoted --- strings, numbers with b / s / i / l / f / d suffixes (any case, signed / unsigned s / u prefix), underscores, hex --- 0x and binary 0b integers, exponents, true / false (bytes 1 / 0), NaN / Infinity with a float suffix, trailing --- commas. Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes. Prints Minecraft's --- compact form (or indented); floats print as the shortest text that reads back to the same value. +-- codecs/text/Nbt/Snbt: stringified NBT, parse and print, from the Minecraft wiki "NBT format" SNBT section (1.21.5). +-- Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes. local Types = require("@rosetta/Types") local Value = require("@rosetta/codecs/text/Nbt/Value") @@ -13,8 +8,8 @@ local Snbt = {} export type ParseOptions = { maxDepth: number? } export type PrintOptions = { - indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact) - quote: string?, -- the string quote, '"' (default) or "'"; the other one is used when it needs fewer escapes + indent: (number | string)?, + quote: string?, } local byte, sub, find = string.byte, string.sub, string.find @@ -24,7 +19,6 @@ local function tag(name: string, v: any): any return setmetatable({ type = name, value = v }, Value.TagMeta) end --- ------------------------------------------------------------------------------------------------ parse type P = { s: string, i: number, n: number, err: string?, at: number, depth: number, maxDepth: number } local function fail(p: P, msg: string): nil @@ -85,7 +79,6 @@ local function quoted(p: P): string? end end --- number text -> a value, or nil when it is not a number (then it is an unquoted string) local INT_RANGE: { [string]: { number } } = { b = { -128, 127, 255 }, s = { -32768, 32767, 65535 }, @@ -135,7 +128,6 @@ local function integer(t: string): any if unsigned and sign == "-" then return nil end - -- the magnitude as (hi, lo) local hi, lo = 0, 0 for k = 1, #digits do local c = byte(digits, k) @@ -437,7 +429,6 @@ parseValue = function(p: P): any return v end --- parse(text, opts?) -> value | nil, message, position (1-based) function Snbt.parse(s: string, opts: ParseOptions?): (any, string?, number?) local p: P = { s = s, i = 1, n = #s, err = nil, at = 1, depth = 0, maxDepth = (opts and opts.maxDepth) or 512 } local v = parseValue(p) @@ -451,7 +442,6 @@ function Snbt.parse(s: string, opts: ParseOptions?): (any, string?, number?) return v, nil, nil end --- ------------------------------------------------------------------------------------------------ print local function shortest(v: number, single: boolean): string if v ~= v then return "NaN" @@ -625,7 +615,6 @@ printValue = function(pr: Pr, v: any, depth: number): string? return nil end --- print(value, opts?) -> text | nil, message function Snbt.print(v: any, opts: PrintOptions?): (string?, string?) local o: PrintOptions = opts or {} local ind = o.indent diff --git a/src/Rosetta/codecs/text/Nbt/Value.luau b/src/Rosetta/codecs/text/Nbt/Value.luau index c178e79..d01f348 100644 --- a/src/Rosetta/codecs/text/Nbt/Value.luau +++ b/src/Rosetta/codecs/text/Nbt/Value.luau @@ -1,13 +1,7 @@ --!strict -- codecs/text/Nbt/Value: the NBT value model shared by the binary and SNBT codecs. New code. --- Plain Luau values with typed numbers, so a decode / encode round trip is exact: --- int -> number string -> string byteArray -> buffer --- compound -> Types.object (key order kept) list -> array (element type in Value.listType) --- byte / short / long / float / double / intArray / longArray -> a tag { type = "", value = ... } with a --- metatable (tostring gives SNBT): long values are numbers when exact (|v| <= 2^53), else their exact decimal --- text; intArray value = { numbers }; longArray value = a buffer of little-endian two's complement int64s. --- Inputs are lenient: a plain number writes as int when integral and in int range, else double; true / false as --- byte 1 / 0; a plain table with string keys as a compound. +-- long values are numbers when |v| <= 2^53, else their exact decimal text; longArray values are buffers of +-- little-endian two's complement int64s. local Types = require("@rosetta/Types") local Value = {} @@ -37,7 +31,6 @@ export type Tag = { type: string, value: any } local TagMeta: { [string]: any } = {} Value.TagMeta = TagMeta --- the SNBT printer, filled in by codecs/text/Nbt (Value is below the printer) Value.print = function(v: any): string return tostring(v.value) end @@ -67,11 +60,8 @@ end local listTypes: { [any]: string } = setmetatable({}, { __mode = "k" }) :: any --- ------------------------------------------------------------------------------------------------ 64-bit integers local TWO32 = 4294967296 --- fromHiLo(hi, lo) -> a long value: a number when exact, else the exact decimal text (hi, lo: u32 halves of the --- two's complement int64) function Value.fromHiLo(hi: number, lo: number): number | string local s = if hi >= 0x80000000 then hi - TWO32 else hi if s >= -0x200000 and s < 0x200000 then @@ -94,7 +84,6 @@ function Value.fromHiLo(hi: number, lo: number): number | string return (if neg then "-" else "") .. table.concat(parts) end --- toHiLo(v) -> hi, lo (u32 halves) | nil: v a whole number in int64 range or its decimal text function Value.toHiLo(v: any): (number?, number?) if type(v) == "number" then if v % 1 ~= 0 or v < -9223372036854775808 or v >= 9223372036854775808 then @@ -127,7 +116,6 @@ function Value.toHiLo(v: any): (number?, number?) return nil, nil end --- ------------------------------------------------------------------------------------------------ constructors local function tag(name: string, v: any): Tag return setmetatable({ type = name, value = v }, TagMeta) :: any end @@ -140,7 +128,6 @@ end function Value.int(n: number): number return n end --- long(n | "decimal") -> a long tag (decimal text within 2^53 becomes a number) function Value.long(v: number | string): Tag if type(v) == "string" then local hi, lo = Value.toHiLo(v) @@ -151,7 +138,6 @@ function Value.long(v: number | string): Tag return tag("long", v) end local f32 = buffer.create(4) --- float(n) -> a float tag holding n rounded to single precision function Value.float(n: number): Tag buffer.writef32(f32, 0, n) return tag("float", buffer.readf32(f32, 0)) @@ -162,7 +148,6 @@ end function Value.intArray(t: { number }?): Tag return tag("intArray", t or {}) end --- longArray(values | buffer) -> a longArray tag (values: numbers / decimal texts; a buffer: 8 bytes each, LE) function Value.longArray(t: { any } | buffer | nil): Tag if type(t) == "buffer" then return tag("longArray", t) @@ -176,7 +161,6 @@ function Value.longArray(t: { any } | buffer | nil): Tag end return tag("longArray", b) end --- longs(longArray) -> { number | string }: the elements as long values function Value.longs(a: Tag): { number | string } local b: buffer = a.value local out = table.create(buffer.len(b) // 8) :: { number | string } @@ -185,7 +169,6 @@ function Value.longs(a: Tag): { number | string } end return out end --- list(typeName, items?) -> items marked as a list of that element type (an empty list keeps its type) function Value.list(name: string, items: { any }?): { any } local t = items or {} listTypes[t] = name @@ -194,7 +177,6 @@ end function Value.compound(t: { [string]: any }?, keys: { string }?): { [string]: any } return Types.object(t, keys) end --- listType(t) -> the element type name recorded for a list (decoded, or made by Value.list) function Value.listType(t: any): string? return listTypes[t] end @@ -205,7 +187,6 @@ function Value.isTag(v: any): boolean return type(v) == "table" and getmetatable(v) == TagMeta end --- typeOf(v) -> the tag name v writes as, or nil + why function Value.typeOf(v: any): (string?, string?) local tv = type(v) if tv == "number" then @@ -236,7 +217,6 @@ function Value.typeOf(v: any): (string?, string?) return nil, "cannot write a " .. tv .. " as NBT" end --- number(v) -> the numeric value of a number or numeric tag (long texts through tonumber: approximate) function Value.number(v: any): number? if type(v) == "number" then return v diff --git a/src/Rosetta/codecs/text/Nbt/init.luau b/src/Rosetta/codecs/text/Nbt/init.luau index 3e2bbb5..086f948 100644 --- a/src/Rosetta/codecs/text/Nbt/init.luau +++ b/src/Rosetta/codecs/text/Nbt/init.luau @@ -1,22 +1,6 @@ --!strict --- codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, --- model/schematic and model/mca use. New code (Minecraft wiki "NBT format", wiki.vg "NBT"). --- Binary: Java big-endian (modified UTF-8 strings), Bedrock little-endian (with or without the 8-byte level.dat --- header) and Bedrock network NBT (varints), every tag type; files may be gzip or zlib compressed (codecs/compress/ --- Deflate). SNBT: parse and print (codecs/text/Nbt/Snbt). Values are plain Luau with typed numbers --- (codecs/text/Nbt/Value): int -> number, string -> string, byteArray -> buffer, compound -> Types.object (key order --- kept), list -> array, the other numeric and array tags -> { type, value } tags, so round trips are exact. --- --- local Nbt = require("@rosetta/codecs/text/Nbt") --- local v, info = Nbt.decode(buf) -- a file: compression and edition detected; info = how it was stored --- print(v.Data.LevelName, v.Data.Time.value) -- int / string plain; long / byte / ... tags have .value --- v.Data.Difficulty = Nbt.byte(2) --- local out = Nbt.encode(v) -- written the way it was read (Nbt.info(v)), or opts --- local text = Nbt.print(v) -- SNBT: {Data:{Difficulty:2b,...}} --- local w = Nbt.parse('{pos:[I;1,2,3],name:"x"}') --- local raw, name, endPos = Nbt.read(buf, 0, nil, { endian = "little" }) -- one uncompressed tag --- --- Never throws: bad data and bad values return nil, Err. +-- codecs/text/Nbt: Minecraft's Named Binary Tag format and SNBT (Minecraft wiki "NBT format", wiki.vg "NBT"). +-- Files may be gzip or zlib compressed; a Bedrock level.dat has an 8-byte header. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") @@ -29,31 +13,31 @@ local Nbt = {} export type Tag = Value.Tag export type Info = { - name: string, -- the root tag's name + name: string, endian: "big" | "little", - varint: boolean?, -- Bedrock network NBT + varint: boolean?, compression: "gzip" | "zlib" | "none", - header: number?, -- Bedrock level.dat: the storage version from the 8-byte header + header: number?, } export type DecodeOptions = { - endian: ("big" | "little")?, -- default: detected (Java big-endian first) - varint: boolean?, -- Bedrock network NBT - nameless: boolean?, -- no root name (Java network NBT since 1.20.2) - maxDepth: number?, -- nesting limit (default 512) - maxBytes: number?, -- refuse compressed data that inflates past this (default 2^28) -} -export type EncodeOptions = { - endian: ("big" | "little")?, -- default: Nbt.info(value).endian, else "big" + endian: ("big" | "little")?, varint: boolean?, nameless: boolean?, - name: string?, -- the root name (default: Nbt.info(value).name, else "") - compression: ("gzip" | "zlib" | "none")?, -- default: Nbt.info(value).compression, else gzip for big-endian - header: number?, -- write the Bedrock level.dat header with this version - level: number?, -- deflate level 0..9 (default 6) + maxDepth: number?, + maxBytes: number?, +} +export type EncodeOptions = { + endian: ("big" | "little")?, + varint: boolean?, + nameless: boolean?, + name: string?, + compression: ("gzip" | "zlib" | "none")?, + header: number?, + level: number?, } -Nbt.TAG = Value.IDS -- name -> id -Nbt.TAG_NAMES = Value.NAMES -- id -> name +Nbt.TAG = Value.IDS +Nbt.TAG_NAMES = Value.NAMES Nbt.byte = Value.byte Nbt.short = Value.short Nbt.int = Value.int @@ -74,18 +58,15 @@ Nbt.toHiLo = Value.toHiLo local infos: { [any]: Info } = setmetatable({}, { __mode = "k" }) :: any --- info(value) -> how a decoded root was stored (nil for values not from decode) function Nbt.info(v: any): Info? return if type(v) == "table" then infos[v] else nil end --- setInfo(value, info): what encode uses as defaults function Nbt.setInfo(v: any, info: Info) if type(v) == "table" then infos[v] = info end end --- read(buf, offset?, length?, opts?) -> value, rootName, endOffset | nil, Err: one uncompressed root tag function Nbt.read(buf: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (any, any, number?) local b, o, l, aerr = Bytes.span("Nbt.read", buf, offset, length) if not b then @@ -98,7 +79,6 @@ function Nbt.read(buf: buffer | string, offset: number?, length: number?, opts: return v, name, at end --- write(value, opts?) -> buffer | nil, Err: one uncompressed root tag function Nbt.write(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) local out, e = Binary.write(v, opts :: any) if not out then @@ -107,7 +87,6 @@ function Nbt.write(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) return out, nil end --- unwrap(buf, offset?, length?, maxBytes?) -> data, start, end, compression | nil, Err: gzip / zlib detected by magic function Nbt.unwrap(buf: buffer | string, offset: number?, length: number?, maxBytes: number?): (buffer?, any, number?, string?) local b, o, l, aerr = Bytes.span("Nbt.unwrap", buf, offset, length) if not b then @@ -135,14 +114,14 @@ function Nbt.unwrap(buf: buffer | string, offset: number?, length: number?, maxB end export type Peek = { - compression: string, -- "gzip" | "zlib" | "none" + compression: string, endian: "big" | "little", - header: boolean, -- a Bedrock level.dat header - rootType: string, -- "compound" (or "list") - name: string, -- the root name - firstType: string?, -- the first child of a root compound (type and name; "end" when empty), when peeked + header: boolean, + rootType: string, + name: string, + firstType: string?, firstName: string?, - head: buffer, -- the first (up to 1024) uncompressed bytes + head: buffer, } local function plausibleName(b: buffer, p: number, n: number): string? @@ -156,8 +135,6 @@ local function plausibleName(b: buffer, p: number, n: number): string? return s end --- peek(buf, offset?, length?) -> Peek | nil: whether the bytes look like an NBT file (inflating at most 1 KiB of a --- gzip / zlib stream), and its root's name and first child: what format sniffs look at. Never fails loudly. function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? local o = offset or 0 local l = length or (buffer.len(buf) - o) @@ -204,7 +181,7 @@ function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? return nil end if ft == 0 then - res.firstType = "end" -- an empty root compound + res.firstType = "end" elseif q + 3 <= hn then local fname = plausibleName(head, q + 3, u16(q + 1)) if fname == nil and q + 3 + u16(q + 1) <= hn then @@ -224,8 +201,6 @@ function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? return at(0, "big", false) or at(0, "little", false) end --- decode(buf | string, opts?, offset?, length?) -> value, Info | nil, Err: a whole NBT file (gzip / zlib / raw; Java --- or Bedrock) function Nbt.decode(buf: buffer | string, opts: DecodeOptions?, offset: number?, length: number?): (any, any) local o: DecodeOptions = opts or {} local b, s, e, comp = Nbt.unwrap(buf, offset, length, o.maxBytes) @@ -291,7 +266,6 @@ function Nbt.decode(buf: buffer | string, opts: DecodeOptions?, offset: number?, return v, info end --- encode(value, opts?) -> buffer | nil, Err: a whole NBT file function Nbt.encode(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local info = Nbt.info(v) @@ -325,7 +299,6 @@ function Nbt.encode(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) return raw, nil end --- parse(text, opts?) -> value | nil, Err: SNBT function Nbt.parse(text: string | buffer, opts: Snbt.ParseOptions?): (any, Err.Err?) local s = if type(text) == "buffer" then buffer.tostring(text) else text if type(s) ~= "string" then @@ -338,7 +311,6 @@ function Nbt.parse(text: string | buffer, opts: Snbt.ParseOptions?): (any, Err.E return v, nil end --- print(value, opts?) -> text | nil, Err: SNBT (compact, or opts.indent) function Nbt.print(v: any, opts: Snbt.PrintOptions?): (string?, Err.Err?) local s, e = Snbt.print(v, opts) if not s then @@ -347,7 +319,6 @@ function Nbt.print(v: any, opts: Snbt.PrintOptions?): (string?, Err.Err?) return s, nil end --- get(value, path) -> the value at a dotted path ("Data.Player.Pos[1]"; list indices 0-based like Minecraft's) function Nbt.get(v: any, path: string): any local cur = v for part in string.gmatch(path, "[^%.]+") do diff --git a/src/Rosetta/codecs/text/Text/init.luau b/src/Rosetta/codecs/text/Text/init.luau index fe1e2d5..ee88261 100644 --- a/src/Rosetta/codecs/text/Text/init.luau +++ b/src/Rosetta/codecs/text/Text/init.luau @@ -1,11 +1,9 @@ --!strict --!optimize 2 --- codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is --- read as Windows-1252 (classic .m3u / .pls / .ini / .srt files), lines split on CRLF / CR / LF, trim. Absorbed from --- playlist-luau 3fc7fd3 (same author, no third-party code). Never throws. +-- codecs/text/Text: text decoding helpers: BOM stripping, Windows-1252 for text that is not UTF-8, line splitting. +-- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code). local Text = {} --- utf8char(codepoint) -> its UTF-8 bytes (no validation: the parsers check ranges first; utf8.char would throw) function Text.utf8char(c: number): string local char = string.char if c < 0x80 then @@ -31,8 +29,6 @@ function Text.trim(s: string): string return (string.match(s, "^%s*(.-)%s*$") :: string) end --- utf16(buf, offset, length, bigEndian?) -> UTF-8 text of UTF-16 code units (surrogate pairs joined, lone surrogates --- become U+FFFD; an odd last byte is ignored). Font names, 7z / PSD / Windows strings, XML in UTF-16. function Text.utf16(b: buffer, o: number, n: number, bigEndian: boolean?): string local out = {} local k = 0 @@ -59,7 +55,6 @@ function Text.utf16(b: buffer, o: number, n: number, bigEndian: boolean?): strin return table.concat(out) end --- toUtf8(text, warnings?) -> text as UTF-8: strips a BOM; text that is not valid UTF-8 is read as Windows-1252 function Text.toUtf8(text: string, warnings: { string }?): string if string.sub(text, 1, 3) == "\239\187\191" then text = string.sub(text, 4) diff --git a/src/Rosetta/codecs/text/Url/init.luau b/src/Rosetta/codecs/text/Url/init.luau index 19b359b..04f7147 100644 --- a/src/Rosetta/codecs/text/Url/init.luau +++ b/src/Rosetta/codecs/text/Url/init.luau @@ -1,10 +1,7 @@ --!strict --!optimize 2 --- codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, --- Windows / UNC / POSIX local path, relative reference) and percent-encoding of bytes that may not appear in a URI --- (raw spaces and UTF-8 in playlists). Shared by the playlist formats (m3u / HLS, pls, xspf); later DASH / glTF URIs. --- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code): Url.luau, plus locate / base from its --- init.luau. Never throws. +-- codecs/text/Url: RFC 3986 reference resolution (section 5.2), local-path classification and percent-encoding. +-- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code). local Url = {} export type Location = { url: string, playable: boolean, reason: string?, [string]: any } @@ -17,7 +14,7 @@ export type Parts = { fragment: string?, } --- Splits a URI reference into its five components (RFC 3986 appendix B). +-- RFC 3986 appendix B: the five components of a URI reference function Url.split(ref: string): Parts local scheme, rest = string.match(ref, "^([%a][%w+%.%-]*):(.*)$") if not scheme then @@ -48,7 +45,7 @@ function Url.split(ref: string): Parts return { scheme = scheme, authority = authority, path = s, query = query, fragment = fragment } end --- Recomposes components (RFC 3986 section 5.3). +-- RFC 3986 section 5.3 function Url.join(p: Parts): string local out = {} if p.scheme then @@ -99,7 +96,7 @@ function Url.removeDotSegments(path: string): string return table.concat(output) end --- Resolves a reference against an absolute base URI (RFC 3986 section 5.2.2, strict). +-- RFC 3986 section 5.2.2 (strict) function Url.resolve(ref: string, base: string): string local r, b = Url.split(ref), Url.split(base) local t: Parts = { path = "" } @@ -136,15 +133,13 @@ function Url.resolve(ref: string, base: string): string return Url.join(t) end --- Percent-encodes the bytes that may not appear in a URI (controls, space, non-ASCII, "<>\"^`{|}" and "\\"), --- leaving existing %XX escapes and the reserved delimiters alone. +-- percent-encoded: controls, space, non-ASCII, "<>\"^`{|}" and "\\"; existing %XX escapes and reserved delimiters stay function Url.encodeUnsafe(s: string): string return (string.gsub(s, "[%z\1-\32\127-\255<>\"%^`{|}\\]", function(c: string): string return string.format("%%%02X", string.byte(c)) end)) end --- Is a location a local Windows path ("C:\x", "C:/x", "\\server\share", "\x")? function Url.isWindowsPath(s: string): boolean return string.match(s, "^%a:[\\/]") ~= nil or string.match(s, "^%a:$") ~= nil @@ -152,7 +147,6 @@ function Url.isWindowsPath(s: string): boolean or string.sub(s, 1, 1) == "\\" end --- The scheme of an absolute URI (lower case), or nil. Windows drive letters are not schemes. function Url.scheme(s: string): string? if Url.isWindowsPath(s) then return nil @@ -161,9 +155,6 @@ function Url.scheme(s: string): string? return if scheme then string.lower(scheme) else nil end --- locate(raw, base?, baseScheme?) -> { url, playable, reason? }: an entry location resolved against the playlist's --- base (from Url.base). Windows paths stay as they are and are local; relative paths without a base, file: URLs and --- schemes other than http(s) are not playable (reason says why). function Url.locate(raw: string, base: string?, baseScheme: string?): Location local loc = (string.match(raw, "^%s*(.-)%s*$") :: string) if Url.isWindowsPath(loc) then @@ -172,7 +163,6 @@ function Url.locate(raw: string, base: string?, baseScheme: string?): Location local scheme = Url.scheme(loc) local url = loc if not scheme and baseScheme == "windows" and base then - -- a playlist on a Windows disk: relative entries are paths next to it local dir = string.match(base, "^(.*[\\/])") or "" return { url = dir .. loc, playable = false, reason = "local path" } end @@ -181,7 +171,6 @@ function Url.locate(raw: string, base: string?, baseScheme: string?): Location url = Url.encodeUnsafe(Url.resolve(loc, loc)) end elseif base and baseScheme then - -- a relative reference: Windows separators become URL ones url = Url.resolve(Url.encodeUnsafe((string.gsub(loc, "\\", "/"))), base) scheme = baseScheme else @@ -195,8 +184,6 @@ function Url.locate(raw: string, base: string?, baseScheme: string?): Location return { url = url, playable = false, reason = "scheme " .. tostring(scheme) } end --- base(baseUrl?, warnings?) -> base, baseScheme: the base for Url.locate from the playlist's own URL or path ("windows" --- for a Windows path); a non-absolute base is ignored (with a warning) function Url.base(baseUrl: string?, warnings: { string }?): (string?, string?) if type(baseUrl) ~= "string" or baseUrl == "" then return nil, nil diff --git a/src/Rosetta/codecs/text/Xml/Parse.luau b/src/Rosetta/codecs/text/Xml/Parse.luau index 2a47422..61de16c 100644 --- a/src/Rosetta/codecs/text/Xml/Parse.luau +++ b/src/Rosetta/codecs/text/Xml/Parse.luau @@ -1,12 +1,7 @@ --!strict --!native --- codecs/text/Xml/Parse: the XML 1.0 pull parser behind codecs/text/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. +-- codecs/text/Xml/Parse: the XML 1.0 pull parser behind codecs/text/Xml: input decoding, line-ending normalization, +-- well-formedness checks, predefined entities, character references, internal DOCTYPE entities (expansion-limited). local Text = require("@rosetta/codecs/text/Text") local Types = require("@rosetta/Types") @@ -15,11 +10,11 @@ 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) + whitespace: boolean?, + namespaces: boolean?, + entities: { [string]: string }?, + maxExpansion: number?, + maxDepth: number?, } local NAME = "^[%a_:\128-\255][%w_:%.%-\128-\255]*" @@ -68,7 +63,6 @@ local function utf16(s: string, start: number, le: boolean): (string?, string?) 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 @@ -121,7 +115,7 @@ local function xmlDecl(data: string): { [string]: string }? 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 + return nil end if (key == "version" and not match(v, "^1%.%d+$")) or (key == "encoding" and not match(v, "^%a[%w%._%-]*$")) @@ -141,17 +135,6 @@ local function xmlDecl(data: string): { [string]: string }? 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 @@ -178,7 +161,7 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) local rootSeen = false local rootDone = false local dead = false - local pending: { any }? = nil -- an "end" queued after a self-closing start + local pending: { any }? = nil local errMsg: string? = nil local errAt = 0 @@ -187,7 +170,6 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) 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 @@ -265,7 +247,6 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) 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 @@ -277,7 +258,7 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) end return sub(s, p + 1, e - 1), e + 1 end - -- an ExternalID (SYSTEM "sys" | PUBLIC "pub" "sys") at p -> publicId, systemId, next | nil + -- ExternalID: SYSTEM "sys" | PUBLIC "pub" "sys" local function externalId(p: number): (string?, string?, number?) local kw = sub(s, p, p + 5) if kw == "SYSTEM" then @@ -311,7 +292,6 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) end return nil, nil, 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 @@ -345,8 +325,6 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) end return table.concat(parts) end - -- the DOCTYPE at i (just past " (string?, any, any, 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 @@ -631,7 +608,6 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) 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) @@ -692,7 +668,7 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) return fail(errMsg :: string, errAt) end if find(raw, "[\t\n]") then - -- attribute-value normalization: literal tab / newline become spaces (references stay) + -- XML 1.0 3.3.3 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 @@ -735,14 +711,13 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) stack[depth] = nil nsStack[depth] = nil preserve[depth] = nil - pending = { name } -- depth goes down when the queued "end" is returned + pending = { name } 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 diff --git a/src/Rosetta/codecs/text/Xml/init.luau b/src/Rosetta/codecs/text/Xml/init.luau index 67f96ba..0377bb4 100644 --- a/src/Rosetta/codecs/text/Xml/init.luau +++ b/src/Rosetta/codecs/text/Xml/init.luau @@ -1,21 +1,6 @@ --!strict --- codecs/text/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("@rosetta/codecs/text/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. +-- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize. New code. +-- Not supported: external entities / DTDs, validation, entity values containing markup. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Parse = require("@rosetta/codecs/text/Xml/Parse") @@ -24,15 +9,15 @@ 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) + comments: boolean?, + cdata: boolean?, + pi: boolean?, + parents: boolean?, } 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) + indent: (number | string)?, + declaration: boolean?, + selfClose: boolean?, } local find, gsub, sub, match = string.find, string.gsub, string.sub, string.match @@ -57,8 +42,6 @@ local function errCode(msg: string, at: number, n: number): string return Err.CORRUPT end --- events(src, opts?) -> iterator: event, a, b, c (see codecs/text/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, "" @@ -87,9 +70,6 @@ function Xml.events(src: string | buffer, opts: Parse.Options?): () -> (string?, 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 @@ -144,9 +124,6 @@ function Xml.decode(src: string | buffer, opts: DecodeOptions?): (Node?, Err.Err 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 @@ -166,14 +143,12 @@ function Xml.element(name: string, attrs: { [string]: string }?, children: { any 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 @@ -182,13 +157,10 @@ function Xml.append(parent: Node, child: any): any 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 @@ -201,7 +173,6 @@ function Xml.children(node: Node, name: string?): { Node } 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 @@ -213,7 +184,6 @@ function Xml.child(node: Node, name: string?): Node? 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) @@ -230,7 +200,6 @@ function Xml.descendants(node: Node, name: string?): { 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 @@ -254,7 +223,6 @@ function Xml.text(node: any): string 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 @@ -262,14 +230,10 @@ 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) @@ -283,11 +247,9 @@ function Xml.clark(node: Node, attrName: string?): string 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 @@ -299,7 +261,6 @@ 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