rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings

This commit is contained in:
4DBug committed 2026-11-01 01:19:16 -05:00
1 parent 2956576d7f
commit 22ddcd78fa
941 files changed
+3364 -3364

No files matched your search

+425
View File
@@ -0,0 +1,425 @@
--!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).
local Text = require("@rosetta/codecs/text/Text")
local Types = require("@rosetta/Types")
local Decode = {}
local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char
local tonumber = tonumber
local concat = table.concat
export type Options = {
ordered: boolean?, -- every object is a Types.object with its key order (default false: only empty objects are)
bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their exact text (default "number")
null: any?, -- the value for null (default Types.null)
maxDepth: number?, -- nesting limit (default 1000)
}
local ESC: { [number]: string } = {
[34] = '"',
[92] = "\\",
[47] = "/",
[98] = "\b",
[102] = "\f",
[110] = "\n",
[114] = "\r",
[116] = "\t",
}
-- utf8 bytes of a code point (surrogates too: WTF-8)
local utf8char = Text.utf8char
Decode.utf8char = utf8char
local function hex4(s: string, i: number): number?
local h = match(s, "^%x%x%x%x", i)
if not h then
return nil
end
return tonumber(h, 16)
end
-- string(s, i) -> value, next | nil, message, offset. i is at the opening quote.
local function str(s: string, i: number): (string?, any, number?)
local j = find(s, '[%z\1-\31"\\]', i + 1)
if not j then
return nil, "unterminated string", #s
end
local c = byte(s, j)
if c == 34 then
return sub(s, i + 1, j - 1), j + 1
end
local parts = {}
local np = 0
local start = i + 1
while true do
if c == 34 then
np += 1
parts[np] = sub(s, start, j - 1)
return concat(parts), j + 1
elseif c ~= 92 then
return nil, "control character in string", j - 1
end
np += 1
parts[np] = sub(s, start, j - 1)
local e = byte(s, j + 1)
if e == nil then
return nil, "unterminated string", #s
end
local simple = ESC[e]
if simple then
np += 1
parts[np] = simple
start = j + 2
elseif e == 117 then -- \u
local cp = hex4(s, j + 2)
if not cp then
return nil, "bad \\u escape", j - 1
end
start = j + 6
if cp >= 0xD800 and cp <= 0xDBFF and byte(s, start) == 92 and byte(s, start + 1) == 117 then
local lo = hex4(s, start + 2)
if lo and lo >= 0xDC00 and lo <= 0xDFFF then
cp = 0x10000 + (cp - 0xD800) * 1024 + (lo - 0xDC00)
start += 6
end
end
np += 1
parts[np] = utf8char(cp)
else
return nil, "bad escape", j - 1
end
j = find(s, '[%z\1-\31"\\]', start)
if not j then
return nil, "unterminated string", #s
end
c = byte(s, j)
end
end
Decode.string = str
-- number(s, i) -> value, next | nil, message, offset
local function num(s: string, i: number, bigStrings: boolean): (any, any, number?)
local p = i
if byte(s, p) == 45 then
p += 1
end
local c = byte(s, p)
if c == 48 then
p += 1
elseif c and c >= 49 and c <= 57 then
p = match(s, "^%d*()", p + 1) :: any
else
return nil, if c == nil then "truncated: expected a value" elseif p == i then "unexpected character" else "bad number", p - 1
end
local int = true
if byte(s, p) == 46 then
local q = match(s, "^%d+()", p + 1)
if not q then
return nil, "bad fraction", p
end
p = q :: any
int = false
end
c = byte(s, p)
if c == 101 or c == 69 then
p += 1
c = byte(s, p)
if c == 43 or c == 45 then
p += 1
end
local q = match(s, "^%d+()", p)
if not q then
return nil, "bad exponent", p - 1
end
p = q :: any
int = false
end
local text = sub(s, i, p - 1)
local n = tonumber(text) :: number
if n == nil then -- LuaJIT: absurd exponents (1e0066999...) -> nil; they overflow / underflow
local m, es = match(text, "^([^eE]*)[eE]([%+%-]?)")
local mv = tonumber(m) or 0
n = if mv == 0 then mv elseif es == "-" then mv * 0 else mv * math.huge
end
if int and bigStrings and p - i > 15 and (n >= 9007199254740992 or n <= -9007199254740992) then
return text, p
end
return n, p
end
Decode.number = num
-- decode(s, i, opts) -> value, next | nil, message, offset. Parses one value starting at i (leading whitespace
-- skipped); next is the position after the value (trailing whitespace not skipped).
function Decode.value(s: string, i: number, opts: Options?): (any, any, number?)
local o: Options = opts or {}
local ordered = o.ordered == true
local bigStrings = o.bigInts == "string"
local nullv = if o.null ~= nil then o.null else Types.null
local maxDepth = o.maxDepth or 1000
local object = Types.object
local stackT: { any } = {} -- containers
local stackK: { any } = {} -- object: the pending key; array: the count
local stackO: { any } = {} -- object: its key order (or true); array: false
local depth = 0
local n = #s
local value: any
while true do
i = match(s, "^[ \t\n\r]*()", i) :: any
local c = byte(s, i)
local haveValue = true
if c == 123 then -- {
depth += 1
if depth > maxDepth then
return nil, "nested deeper than " .. maxDepth, i - 1
end
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
local t = {}
c = byte(s, i)
if c == 125 then
i += 1
depth -= 1
value = object(t, {})
elseif c == 34 then
local k, ni, at = str(s, i)
if k == nil then
return nil, ni, at
end
i = match(s, "^[ \t\n\r]*()", ni) :: any
if byte(s, i) ~= 58 then
return nil, if i > n then "truncated object" else "expected ':'", i - 1
end
i += 1
stackT[depth], stackK[depth] = t, k
stackO[depth] = if ordered then {} else true
haveValue = false
else
return nil, if c == nil then "truncated object" else "expected a key", i - 1
end
elseif c == 91 then -- [
depth += 1
if depth > maxDepth then
return nil, "nested deeper than " .. maxDepth, i - 1
end
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
if byte(s, i) == 93 then
i += 1
depth -= 1
value = {}
else
stackT[depth], stackK[depth], stackO[depth] = {}, 0, false
haveValue = false
end
elseif c == 34 then
local v, ni, at = str(s, i)
if v == nil then
return nil, ni, at
end
value, i = v, ni
elseif c == 116 then
if sub(s, i, i + 3) ~= "true" then
return nil, "bad literal", i - 1
end
value, i = true, i + 4
elseif c == 102 then
if sub(s, i, i + 4) ~= "false" then
return nil, "bad literal", i - 1
end
value, i = false, i + 5
elseif c == 110 then
if sub(s, i, i + 3) ~= "null" then
return nil, "bad literal", i - 1
end
value, i = nullv, i + 4
elseif c == nil then
return nil, "truncated: expected a value", n
else
local v, ni, at = num(s, i, bigStrings)
if v == nil then
return nil, ni, at
end
value, i = v, ni
end
-- attach the value to the open containers, closing them as their ends come
while haveValue do
if depth == 0 then
return value, i
end
local t = stackT[depth]
local ord = stackO[depth]
if ord then
local k = stackK[depth]
if ord ~= true and t[k] == nil then
table.insert(ord, k)
end
t[k] = value
else
local cnt = stackK[depth] + 1
t[cnt] = value
stackK[depth] = cnt
end
i = match(s, "^[ \t\n\r]*()", i) :: any
c = byte(s, i)
if c == 44 then -- ,
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
if ord then
if byte(s, i) ~= 34 then
return nil, if i > n then "truncated object" else "expected a key", i - 1
end
local k, ni, at = str(s, i)
if k == nil then
return nil, ni, at
end
i = match(s, "^[ \t\n\r]*()", ni) :: any
if byte(s, i) ~= 58 then
return nil, if i > n then "truncated object" else "expected ':'", i - 1
end
i += 1
stackK[depth] = k
end
haveValue = false
elseif ord and c == 125 then
i += 1
value = if ord ~= true then object(t, ord) elseif next(t) == nil then object(t, {}) else t
stackT[depth] = nil
depth -= 1
elseif not ord and c == 93 then
i += 1
value = t
stackT[depth] = nil
depth -= 1
elseif c == nil then
return nil, if ord then "truncated object" else "truncated array", n
else
return nil, if ord then "expected ',' or '}'" else "expected ',' or ']'", i - 1
end
end
end
end
-- events: a pull tokenizer. next() -> event, value | nil at the end | "error", message, offset. Events: "object",
-- "endObject", "array", "endArray", "key" (string), "value" (scalar). The grammar is checked as it goes.
function Decode.events(s: string, i: number, opts: Options?): () -> (string?, any, number?)
local o: Options = opts or {}
local bigStrings = o.bigInts == "string"
local nullv = if o.null ~= nil then o.null else Types.null
local maxDepth = o.maxDepth or 1000
local stack: { boolean } = {} -- true = object
local depth = 0
-- state: "value" (a value expected), "first" (after { or [: value / key or close), "after" (after a value),
-- "key" (a key expected), "done", "dead"
local state = "value"
local n = #s
local function fail(msg: string, at: number): (string, any, number)
state = "dead"
return "error", msg, at
end
return function(): (string?, any, number?)
if state == "dead" then
return nil
end
i = match(s, "^[ \t\n\r]*()", i) :: any
local c = byte(s, i)
if state == "done" then
state = "dead"
if c ~= nil then
return "error", "trailing data", i - 1
end
return nil
end
if state == "after" then
local obj = stack[depth]
if c == 44 then
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
c = byte(s, i)
state = if obj then "key" else "value"
elseif c == (if obj then 125 else 93) then
i += 1
stack[depth] = nil
depth -= 1
state = if depth == 0 then "done" else "after"
return if obj then "endObject" else "endArray", nil
elseif c == nil then
return fail("truncated", n)
else
return fail("expected ',' or a close", i - 1)
end
end
if state == "first" then
local obj = stack[depth]
if c == (if obj then 125 else 93) then
i += 1
stack[depth] = nil
depth -= 1
state = if depth == 0 then "done" else "after"
return if obj then "endObject" else "endArray", nil
end
state = if obj then "key" else "value"
end
if state == "key" then
if c ~= 34 then
return fail(if c == nil then "truncated" else "expected a key", i - 1)
end
local k, ni, at = str(s, i)
if k == nil then
return fail(ni, at :: number)
end
i = match(s, "^[ \t\n\r]*()", ni) :: any
if byte(s, i) ~= 58 then
return fail("expected ':'", i - 1)
end
i += 1
state = "value"
return "key", k
end
-- a value
local after = if depth == 0 then "done" else "after"
if c == 123 or c == 91 then
depth += 1
if depth > maxDepth then
return fail("nested deeper than " .. maxDepth, i - 1)
end
stack[depth] = c == 123
i += 1
state = "first"
return if c == 123 then "object" else "array", nil
elseif c == 34 then
local v, ni, at = str(s, i)
if v == nil then
return fail(ni, at :: number)
end
i = ni
state = after
return "value", v
elseif c == 116 and sub(s, i, i + 3) == "true" then
i += 4
state = after
return "value", true
elseif c == 102 and sub(s, i, i + 4) == "false" then
i += 5
state = after
return "value", false
elseif c == 110 and sub(s, i, i + 3) == "null" then
i += 4
state = after
return "value", nullv
elseif c == nil then
return fail("truncated: expected a value", n)
end
local v, ni, at = num(s, i, bigStrings)
if v == nil then
return fail(ni, at :: number)
end
i = ni
state = after
return "value", v
end
end
return Decode
+307
View File
@@ -0,0 +1,307 @@
--!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.
local Types = require("@rosetta/Types")
local Encode = {}
local byte, format, gsub = string.byte, string.format, string.gsub
local floor, huge = math.floor, math.huge
local concat = table.concat
export type Options = {
indent: (number | string)?, -- pretty print: spaces per level (or the indent string); default compact
sortKeys: boolean?, -- plain tables' keys sorted (default true; false = next() order, faster)
ascii: boolean?, -- escape every non-ASCII character as \uXXXX (default false: UTF-8 as is)
nan: ("error" | "null")?, -- NaN / inf: an error (default) or null
emptyTable: ("array" | "object")?, -- what a plain empty table is (default "array"; Types.object() is "{}")
maxDepth: number?, -- nesting limit (default 1000; also catches cycles)
escapeSlash: boolean?, -- write / as \/ (default false)
}
local ESCAPES: { [string]: string } = {
['"'] = '\\"',
["\\"] = "\\\\",
["\b"] = "\\b",
["\f"] = "\\f",
["\n"] = "\\n",
["\r"] = "\\r",
["\t"] = "\\t",
["/"] = "\\/",
}
for c = 0, 31 do
local ch = string.char(c)
if not ESCAPES[ch] then
ESCAPES[ch] = format("\\u%04x", c)
end
end
local function utf16(cp: number): string
if cp < 0x10000 then
return format("\\u%04x", cp)
end
cp -= 0x10000
return format("\\u%04x\\u%04x", 0xD800 + cp // 1024, 0xDC00 + cp % 1024)
end
-- asciify a UTF-8 string's non-ASCII sequences (invalid bytes become \u00XX of the byte: lossy but never throws)
local function asciiSeq(seq: string): string
local out = {}
local i, n = 1, #seq
while i <= n do
local c = byte(seq, i)
local cp, len
if c < 0xC0 then
cp, len = c, 1
elseif c < 0xE0 then
cp, len = (c % 32) * 64 + (byte(seq, i + 1) or 128) % 64, 2
elseif c < 0xF0 then
cp, len = (c % 16) * 4096 + ((byte(seq, i + 1) or 128) % 64) * 64 + (byte(seq, i + 2) or 128) % 64, 3
else
cp, len = (c % 8) * 262144 + ((byte(seq, i + 1) or 128) % 64) * 4096 + ((byte(seq, i + 2) or 128) % 64) * 64 + (byte(seq, i + 3) or 128) % 64, 4
end
table.insert(out, utf16(cp))
i += len
end
return concat(out)
end
-- string(s, ascii, slash) -> the quoted JSON string (ascii: DEL too, like Python's ensure_ascii)
local function quote(s: string, ascii: boolean?, slash: boolean?): string
local pat = if slash then '[%z\1-\31"\\/]' else '[%z\1-\31"\\]'
if string.find(s, pat) then
s = gsub(s, pat, ESCAPES)
end
if ascii and string.find(s, "[\127-\255]") then
s = gsub(s, "\127", "\\u007f")
s = gsub(s, "[\192-\255][\128-\191]*", asciiSeq)
s = gsub(s, "[\128-\191]", asciiSeq)
end
return '"' .. s .. '"'
end
Encode.quote = quote
local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" }
-- number(x) -> the shortest text that reads back as x | nil for NaN / inf
local function number(x: number): string?
if x ~= x or x == huge or x == -huge then
return nil
end
if x == floor(x) and x > -1e15 and x < 1e15 then
if x == 0 and 1 / x < 0 then
return "-0"
end
return format("%d", x)
end
for _, f in FLOAT_FORMATS do
local t = format(f, x)
if tonumber(t) == x then
return t
end
end
return format("%.17g", x)
end
Encode.number = number
local function keyLess(a: any, b: any): boolean
local ta, tb = type(a), type(b)
if ta ~= tb then
return ta == "number"
end
return a < b
end
-- kind(t, emptyObject) -> "array" (keys exactly 1..n) | "object"
local function kind(t: { [any]: any }, emptyObject: boolean): string
if Types.isObject(t) then
return "object"
end
local n = #t
if n == 0 then
if next(t) == nil then
return if emptyObject then "object" else "array"
end
return "object"
end
local count = 0
for _ in next, t do
count += 1
end
return if count == n then "array" else "object"
end
Encode.kind = kind
type State = {
out: { string },
n: number,
indent: string?,
sort: boolean,
ascii: boolean,
slash: boolean,
nanNull: boolean,
emptyObject: boolean,
maxDepth: number,
null: any,
err: string?,
}
local function put(st: State, s: string)
local n = st.n + 1
st.out[n] = s
st.n = n
end
local function value(st: State, v: any, depth: number): boolean
local tv = type(v)
if tv == "string" then
put(st, quote(v, st.ascii, st.slash))
elseif tv == "number" then
local s = number(v)
if not s then
if not st.nanNull then
st.err = "cannot encode " .. tostring(v)
return false
end
s = "null"
end
put(st, s)
elseif tv == "boolean" then
put(st, if v then "true" else "false")
elseif v == nil or v == st.null or v == Types.null then
put(st, "null")
elseif tv == "table" then
if Types.Date.is(v) then
put(st, '"' .. tostring(v) .. '"')
return true
end
if depth >= st.maxDepth then
st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)"
return false
end
local ind = st.indent
local nl, nl2 = "", ""
if ind then
nl = "\n" .. string.rep(ind, depth + 1)
nl2 = "\n" .. string.rep(ind, depth)
end
if kind(v, st.emptyObject) == "array" then
local n = #v
if n == 0 then
put(st, "[]")
return true
end
put(st, "[")
for i = 1, n do
if i > 1 then
put(st, ",")
end
if ind then
put(st, nl)
end
if not value(st, v[i], depth + 1) then
return false
end
end
if ind then
put(st, nl2)
end
put(st, "]")
else
local keys: { any }
if Types.isObject(v) then
keys = Types.keys(v)
else
keys = {}
for k in next, v do
local tk = type(k)
if tk ~= "string" and tk ~= "number" then
st.err = "object key of type " .. tk
return false
end
table.insert(keys, k)
end
if st.sort then
table.sort(keys, keyLess)
end
end
if #keys == 0 then
put(st, "{}")
return true
end
put(st, "{")
local sep = if ind then ": " else ":"
for i, k in keys do
if i > 1 then
put(st, ",")
end
if ind then
put(st, nl)
end
local ks: string
if type(k) == "string" then
ks = k
elseif type(k) == "number" then
ks = number(k) or tostring(k)
else
st.err = "object key of type " .. type(k)
return false
end
put(st, quote(ks, st.ascii, st.slash))
put(st, sep)
if not value(st, v[k], depth + 1) then
return false
end
end
if ind then
put(st, nl2)
end
put(st, "}")
end
elseif tv == "buffer" then
st.err = "cannot encode a buffer (encode it as base64 or an array first)"
return false
else
st.err = "cannot encode a " .. tv
return false
end
return true
end
local function state(opts: Options?, nullv: any?): State
local o: Options = opts or {}
local ind: string? = nil
if type(o.indent) == "number" then
ind = if o.indent > 0 then string.rep(" ", o.indent) else nil
elseif type(o.indent) == "string" then
ind = o.indent
end
return {
out = {},
n = 0,
indent = ind,
sort = o.sortKeys ~= false,
ascii = o.ascii == true,
slash = o.escapeSlash == true,
nanNull = o.nan == "null",
emptyObject = o.emptyTable == "object",
maxDepth = o.maxDepth or 1000,
null = nullv,
err = nil,
}
end
Encode.state = state
Encode.write = value
-- encode(v, opts) -> text | nil, message
function Encode.encode(v: any, opts: Options?, nullv: any?): (string?, string?)
local st = state(opts, nullv)
if not value(st, v, 0) then
return nil, st.err
end
return concat(st.out), nil
end
return Encode
+294
View File
@@ -0,0 +1,294 @@
--!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")
local Encode = require("@rosetta/codecs/text/Json/Encode")
local Json = {}
export type DecodeOptions = Decode.Options
export type EncodeOptions = Encode.Options
Json.null = Types.null
Json.object = Types.object
Json.keys = Types.keys
Json.set = Types.set
local function text(src: any): (string?, Err.Err?)
if type(src) == "string" then
return src, nil
elseif type(src) == "buffer" then
return buffer.tostring(src), nil
end
return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src))
end
local function fail(msg: any, at: any, n: number): Err.Err
local m = tostring(msg)
local code = if string.find(m, "truncated", 1, true) or string.find(m, "unterminated", 1, true) or (at or 0) >= n
then Err.TRUNCATED
elseif string.find(m, "nested deeper", 1, true) then Err.LIMIT
else Err.CORRUPT
return Err.new(code, m, at)
end
-- decode(src, opts?) -> value | nil, Err. One JSON text: a value with optional whitespace around it (a UTF-8 BOM is
-- skipped). Note a JSON null top-level value decodes to opts.null (Types.null by default), never nil.
function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err?)
local s, terr = text(src)
if not s then
return nil, terr
end
local i = if string.sub(s, 1, 3) == "\239\187\191" then 4 else 1
local v, ni, at = Decode.value(s, i, opts)
if v == nil then
return nil, fail(ni, at, #s)
end
local e = string.match(s, "^[ \t\n\r]*()", ni) :: any
if e <= #s then
return nil, Err.new(Err.CORRUPT, "trailing data after the value", e - 1)
end
return v, nil
end
-- decodeAt(src, pos?, opts?) -> value, nextPos | nil, Err. One value starting at pos (1-based, default 1; leading
-- whitespace skipped); nextPos is just past it. nil, nil when only whitespace is left.
function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?): (any, any)
local s, terr = text(src)
if not s then
return nil, terr
end
local i = string.match(s, "^[ \t\n\r]*()", pos or 1) :: any
if i > #s then
return nil, nil
end
local v, ni, at = Decode.value(s, i, opts)
if v == nil then
return nil, fail(ni, at, #s)
end
return v, ni
end
-- lines(src, opts?) -> iterator: index, value (JSON Lines, or any whitespace-separated sequence of JSON values). A
-- bad value gives a last index, nil, Err: for i, v, err in Json.lines(s) do if err then ... end end
function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, any, Err.Err?)
local s, terr = text(src)
local pos = 1
local index = 0
local dead = false
return function(): (number?, any, Err.Err?)
if dead then
return nil
end
index += 1
if not s then
dead = true
return index, nil, terr
end
local v, ni = Json.decodeAt(s, pos, opts)
if v == nil then
dead = true
if ni == nil then
return nil
end
return index, nil, ni
end
pos = ni
return index, v, nil
end
end
-- events(src, opts?) -> iterator: event, value. Events: "object", "endObject", "array", "endArray", "key" (the key),
-- "value" (a scalar), and on bad input one final "error", Err.
function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string?, any)
local s, terr = text(src)
if not s then
local done = false
return function(): (string?, any)
if done then
return nil, nil
end
done = true
return "error", terr
end
end
local str: string = s
local i = if string.sub(str, 1, 3) == "\239\187\191" then 4 else 1
local nextEv = Decode.events(str, i, opts)
return function(): (string?, any)
local ev, v, at = nextEv()
if ev == "error" then
return ev, fail(v, at, #str)
end
return ev, v
end
end
-- encode(value, opts?) -> string | nil, Err
function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?)
local s, msg = Encode.encode(value, opts)
if not s then
return nil, Err.new(Err.ARG, msg or "cannot encode")
end
return s, nil
end
Json.quote = Encode.quote -- quote(s) -> '"..."' with JSON escapes
Json.number = Encode.number -- number(x) -> the shortest round-trip text (nil for NaN / inf)
-- ------------------------------------------------------------------------------------------------ writer
-- writer(opts?) -> a streaming Writer: beginObject / endObject / beginArray / endArray / key(k) / value(v) (any
-- value, encoded whole), then tostring() for everything or flush() for the text since the last flush. Misuse (a key
-- outside an object, a value where a key is due, unbalanced ends) is recorded in w.err and later calls do nothing.
export type Writer = {
err: Err.Err?,
beginObject: (self: Writer) -> Writer,
endObject: (self: Writer) -> Writer,
beginArray: (self: Writer) -> Writer,
endArray: (self: Writer) -> Writer,
key: (self: Writer, k: string) -> Writer,
value: (self: Writer, v: any) -> Writer,
flush: (self: Writer) -> string,
tostring: (self: Writer) -> (string?, Err.Err?),
}
function Json.writer(opts: EncodeOptions?): Writer
local st = Encode.state(opts)
local ind = st.indent
local kinds: { boolean } = {} -- true = object
local counts: { number } = {}
local depth = 0
local keyDone = false -- an object's key written, its value due
local flushed: { string } = {}
local w: any = { err = nil }
local function bad(msg: string)
if not w.err then
w.err = Err.new(Err.ARG, msg)
end
end
-- before an element: a comma / newline as needed; false when the position is wrong
local function slot(isKey: boolean): boolean
if w.err then
return false
end
if depth == 0 then
if counts[0] and counts[0] > 0 then
bad("one top-level value only")
return false
end
counts[0] = 1
return true
end
local obj = kinds[depth]
if obj and not isKey then
if not keyDone then
bad("an object member needs a key first")
return false
end
keyDone = false
return true
end
if isKey and not obj then
bad("key outside an object")
return false
end
if isKey and keyDone then
bad("two keys in a row")
return false
end
if counts[depth] > 0 then
table.insert(st.out, ",")
end
counts[depth] += 1
if ind then
table.insert(st.out, "\n" .. string.rep(ind, depth))
end
return true
end
local function open(obj: boolean)
if slot(false) then
table.insert(st.out, if obj then "{" else "[")
depth += 1
kinds[depth], counts[depth] = obj, 0
end
return w
end
local function close(obj: boolean)
if w.err then
return w
end
if depth == 0 or kinds[depth] ~= obj or (obj and keyDone) then
bad(if obj then "unbalanced endObject" else "unbalanced endArray")
return w
end
if ind and counts[depth] > 0 then
table.insert(st.out, "\n" .. string.rep(ind, depth - 1))
end
table.insert(st.out, if obj then "}" else "]")
depth -= 1
return w
end
function w.beginObject(_self: Writer): Writer
return open(true)
end
function w.beginArray(_self: Writer): Writer
return open(false)
end
function w.endObject(_self: Writer): Writer
return close(true)
end
function w.endArray(_self: Writer): Writer
return close(false)
end
function w.key(_self: Writer, k: string): Writer
if type(k) ~= "string" then
bad("key must be a string")
elseif slot(true) then
table.insert(st.out, Encode.quote(k, st.ascii, st.slash) .. (if ind then ": " else ":"))
keyDone = true
end
return w
end
function w.value(_self: Writer, v: any): Writer
if slot(false) then
st.n = #st.out
if not Encode.write(st, v, depth) then
bad(st.err or "cannot encode")
end
end
return w
end
function w.flush(_self: Writer): string
local s = table.concat(st.out)
table.clear(st.out)
st.n = 0
table.insert(flushed, s)
return s
end
function w.tostring(_self: Writer): (string?, Err.Err?)
if w.err then
return nil, w.err
end
if depth ~= 0 then
return nil, Err.new(Err.ARG, "unclosed object / array")
end
return table.concat(flushed) .. table.concat(st.out), nil
end
return w :: Writer
end
return Json
+698
View File
@@ -0,0 +1,698 @@
--!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).
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
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 "")
}
local readu8, readi8, readu32, readi16 = buffer.readu8, buffer.readi8, buffer.readu32, buffer.readi16
local readf32, readf64, writeu32, readstring = buffer.readf32, buffer.readf64, buffer.writeu32, buffer.readstring
local byteswap = bit32.byteswap
local TWO32 = 4294967296
local NAMES, IDS = Value.NAMES, Value.IDS
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
return s
end
local out = {}
local i, n = 1, #s
while i <= n do
local c = string.byte(s, i)
if c == 0xC0 and string.byte(s, i + 1) == 0x80 then
table.insert(out, "\0")
i += 2
elseif c == 0xED and i + 5 <= n then
local b2, b3, c4, b5, b6 = string.byte(s, i + 1, i + 5)
if b2 >= 0xA0 and b2 <= 0xAF and c4 == 0xED and b5 >= 0xB0 and b5 <= 0xBF then
local hiS = 0xD000 + (b2 - 0x80) * 64 + (b3 - 0x80)
local loS = 0xD000 + (b5 - 0x80) * 64 + (b6 - 0x80)
table.insert(out, utf8.char(0x10000 + (hiS - 0xD800) * 1024 + (loS - 0xDC00)))
i += 6
else
table.insert(out, string.char(c))
i += 1
end
else
local j = string.find(s, "[\192\237]", i + 1) or n + 1
table.insert(out, string.sub(s, i, j - 1))
i = j
end
end
return table.concat(out)
end
local function toModified(s: string): string
if not string.find(s, "[%z\240-\244]") then
return s
end
local out = {}
local i, n = 1, #s
while i <= n do
local c = string.byte(s, i)
if c == 0 then
table.insert(out, "\192\128")
i += 1
elseif c >= 0xF0 and c <= 0xF4 and i + 3 <= n then
local b2, b3, b4 = string.byte(s, i + 1, i + 3)
local cp = (c - 0xF0) * 262144 + (b2 - 0x80) * 4096 + (b3 - 0x80) * 64 + (b4 - 0x80) - 0x10000
local hiS, loS = 0xD800 + cp // 1024, 0xDC00 + cp % 1024
table.insert(out, string.char(0xED, 0x80 + (hiS - 0xD000) // 64, 0x80 + hiS % 64))
table.insert(out, string.char(0xED, 0x80 + (loS - 0xD000) // 64, 0x80 + loS % 64))
i += 4
else
local j = string.find(s, "[%z\240-\244]", i + 1) or n + 1
table.insert(out, string.sub(s, i, j - 1))
i = j
end
end
return table.concat(out)
end
Binary.fromModified = fromModified
Binary.toModified = toModified
-- ------------------------------------------------------------------------------------------------ read
local function fail(s: State, msg: string): nil
if not s.err then
s.err = msg
end
s.p = s.e
return nil
end
local function need(s: State, n: number): boolean
if s.p + n > s.e then
fail(s, "truncated")
return false
end
return true
end
local function u8(s: State): number
if not need(s, 1) then
return 0
end
local v = readu8(s.b, s.p)
s.p += 1
return v
end
local function varuint(s: State): number -- up to 32 bits (5 bytes)
local v, mul = 0, 1
for _ = 1, 5 do
if not need(s, 1) then
return 0
end
local c = readu8(s.b, s.p)
s.p += 1
v += (c % 128) * mul
if c < 128 then
return v % TWO32
end
mul *= 128
end
fail(s, "varint too long")
return 0
end
local function i16(s: State): number
if not need(s, 2) then
return 0
end
local p = s.p
s.p = p + 2
if s.le then
return readi16(s.b, p)
end
local v = readu8(s.b, p) * 256 + readu8(s.b, p + 1)
return if v >= 32768 then v - 65536 else v
end
local function u32raw(s: State): number
if not need(s, 4) then
return 0
end
local p = s.p
s.p = p + 4
local v = readu32(s.b, p)
return if s.le then v else byteswap(v)
end
local function i32(s: State): number
if s.net then
local n = varuint(s)
return if n % 2 == 0 then n // 2 else -(n + 1) // 2
end
local v = u32raw(s)
return if v >= 0x80000000 then v - TWO32 else v
end
-- a length: i32 (zigzag varint in network NBT)
local function len(s: State): number
return i32(s)
end
local function i64(s: State): (number, number) -- hi, lo
if s.net then
local lo, hi, sh = 0, 0, 0
while true do
if sh >= 70 or not need(s, 1) then
fail(s, "varint too long")
return 0, 0
end
local c = readu8(s.b, s.p)
s.p += 1
local d = c % 128
if sh < 32 then
local x = d * 2 ^ sh
lo += x % TWO32
hi = (hi + x // TWO32) % TWO32
else
hi = (hi + d * 2 ^ (sh - 32)) % TWO32
end
sh += 7
if c < 128 then
break
end
end
local odd = lo % 2 == 1
lo = lo // 2 + (hi % 2) * 0x80000000
hi = hi // 2
if odd then
hi, lo = TWO32 - 1 - hi, TWO32 - 1 - lo
end
return hi, lo
end
if s.le then
local lo = u32raw(s)
return u32raw(s), lo
end
local hi = u32raw(s)
return hi, u32raw(s)
end
local function f32(s: State): number
local v = u32raw(s)
writeu32(s.scratch, 0, v)
return readf32(s.scratch, 0)
end
local function f64(s: State): number
local hi, lo
if s.le then
lo = u32raw(s)
hi = u32raw(s)
else
hi = u32raw(s)
lo = u32raw(s)
end
writeu32(s.scratch, 0, lo)
writeu32(s.scratch, 4, hi)
return readf64(s.scratch, 0)
end
local function str(s: State): string
local n
if s.net then
n = varuint(s)
else
n = i16(s) % 65536
end
if not need(s, n) then
return ""
end
local v = readstring(s.b, s.p, n)
s.p += n
return if s.java then fromModified(v) else v
end
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 }
local payload: (State, number) -> any
local function count(s: State, n: number, size: number): boolean
if n < 0 then
fail(s, "negative length " .. n)
return false
end
if n * size > s.e - s.p then
fail(s, "truncated: " .. n .. " elements past the end")
return false
end
return true
end
payload = function(s: State, id: number): any
if id == 3 then
return i32(s)
elseif id == 8 then
return str(s)
elseif id == 10 then
s.depth += 1
if s.depth > s.maxDepth then
return fail(s, "limit: nested deeper than " .. s.maxDepth)
end
local o, keys = {}, {}
while true do
local t = u8(s)
if s.err then
return nil
end
if t == 0 then
break
end
if t > 12 then
return fail(s, "bad tag type " .. t)
end
local k = str(s)
local v = payload(s, t)
if s.err then
return nil
end
if o[k] == nil then
table.insert(keys, k)
end
o[k] = v
end
s.depth -= 1
return Types.object(o, keys)
elseif id == 1 then
if not need(s, 1) then
return nil
end
s.p += 1
return tag("byte", readi8(s.b, s.p - 1))
elseif id == 2 then
return tag("short", i16(s))
elseif id == 4 then
local hi, lo = i64(s)
return tag("long", Value.fromHiLo(hi, lo))
elseif id == 5 then
return tag("float", f32(s))
elseif id == 6 then
return tag("double", f64(s))
elseif id == 7 then
local n = len(s)
if not count(s, n, 1) then
return nil
end
local out = buffer.create(n)
buffer.copy(out, 0, s.b, s.p, n)
s.p += n
return out
elseif id == 9 then
local et = u8(s)
local n = len(s)
if s.err then
return nil
end
if et > 12 then
return fail(s, "bad list element type " .. et)
end
if et == 0 and n > 0 then
return fail(s, "list of end tags with " .. n .. " elements")
end
if not count(s, n, (if s.net then MIN_NET else MIN)[et]) then
return nil
end
s.depth += 1
if s.depth > s.maxDepth then
return fail(s, "limit: nested deeper than " .. s.maxDepth)
end
local out = table.create(n)
for i = 1, n do
local v = payload(s, et)
if s.err then
return nil
end
out[i] = v
end
s.depth -= 1
Value.setListType(out, NAMES[et])
return out
elseif id == 11 then
local n = len(s)
if not count(s, n, if s.net then 1 else 4) then
return nil
end
local out = table.create(n)
for i = 1, n do
out[i] = i32(s)
end
return tag("intArray", out)
elseif id == 12 then
local n = len(s)
if not count(s, n, if s.net then 1 else 8) then
return nil
end
local out = buffer.create(n * 8)
if s.net then
for i = 0, n - 1 do
local hi, lo = i64(s)
writeu32(out, i * 8, lo)
writeu32(out, i * 8 + 4, hi)
end
elseif s.le then
buffer.copy(out, 0, s.b, s.p, n * 8)
s.p += n * 8
else
local b, p = s.b, s.p
for i = 0, n - 1 do
local q = p + i * 8
writeu32(out, i * 8 + 4, byteswap(readu32(b, q)))
writeu32(out, i * 8, byteswap(readu32(b, q + 4)))
end
s.p = p + n * 8
end
return tag("longArray", out)
end
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
local le = net or o.endian == "little"
local s: State = {
b = b,
p = pos,
e = limit,
le = le,
net = net,
java = not le,
depth = 0,
maxDepth = o.maxDepth or 512,
err = nil,
scratch = buffer.create(8),
}
local id = u8(s)
if s.err then
return nil, s.err, pos
end
if id == 0 or id > 12 then
return nil, "bad root tag type " .. id, pos
end
local name = if o.nameless then "" else str(s)
local v = payload(s, id)
if s.err then
return nil, s.err, s.p
end
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)
v %= TWO32
while v >= 128 do
w:u8(v % 128 + 128)
v //= 128
end
w:u8(v)
end
local function wi32(ws: WState, v: number)
v %= TWO32 -- two's complement
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)
elseif ws.le then
ws.w:u32le(v)
else
ws.w:u32be(v)
end
end
local function wi16(ws: WState, v: number)
v %= 65536
if ws.le then
ws.w:u16le(v)
else
ws.w:u16be(v)
end
end
local function wi64(ws: WState, hi: number, lo: number)
if ws.net then
-- zigzag: (n << 1) ^ (n >> 63)
local neg = hi >= 0x80000000
local zh = (hi * 2) % TWO32 + (if lo >= 0x80000000 then 1 else 0)
local zl = (lo * 2) % TWO32
if neg then
zh, zl = TWO32 - 1 - zh, TWO32 - 1 - zl
end
while zh > 0 or zl >= 128 do
ws.w:u8(zl % 128 + 128)
zl = zl // 128 + (zh % 128) * 0x2000000
zh //= 128
end
ws.w:u8(zl)
elseif ws.le then
ws.w:u32le(lo)
ws.w:u32le(hi)
else
ws.w:u32be(hi)
ws.w:u32be(lo)
end
end
local function wstr(ws: WState, s: string): string?
local v = if ws.java then toModified(s) else s
if ws.net then
wvaruint(ws.w, #v)
else
if #v > 65535 then
return "string longer than 65535 bytes"
end
wi16(ws, #v)
end
ws.w:string(v)
return nil
end
local function integer(v: any, lo: number, hi: number, what: string): (number?, string?)
local n = if type(v) == "boolean" then (if v then 1 else 0) else v
if type(n) ~= "number" or n % 1 ~= 0 or n < lo or n > hi then
return nil, "bad " .. what .. " value " .. tostring(n)
end
return n, nil
end
local wpayload: (WState, string, any) -> string?
local function wlist(ws: WState, v: { any }): string?
local lt = Value.listType(v)
local n = #v
local wrap = false
if not lt then
if n == 0 then
lt = "end"
else
local t1, e1 = Value.typeOf(v[1])
if not t1 then
return e1
end
lt = t1
end
end
for i = 1, n do
local t, e = Value.typeOf(v[i])
if not t then
return e
end
if t ~= lt then
wrap = true -- mixed element types: every element becomes a compound { [""] = value }, as Minecraft does
end
end
if wrap then
lt = "compound"
end
if lt == "end" and n > 0 then
return "a list of end tags cannot hold elements"
end
ws.w:u8(IDS[lt :: string])
wi32(ws, n)
for i = 1, n do
local x = v[i]
if wrap and Value.typeOf(x) ~= "compound" then
x = Types.object({ [""] = x }, { "" })
end
local e = wpayload(ws, lt :: string, x)
if e then
return e
end
end
return nil
end
wpayload = function(ws: WState, t: string, v: any): string?
local w = ws.w
local x = if Value.isTag(v) then v.value else v
if t == "int" then
local n, e = integer(x, -2147483648, 4294967295, "int")
if not n then
return e
end
wi32(ws, n)
elseif t == "string" then
if type(x) ~= "string" then
return "bad string value"
end
return wstr(ws, x)
elseif t == "compound" then
ws.depth += 1
if ws.depth > ws.maxDepth then
return "nested deeper than " .. ws.maxDepth .. " (a cycle?)"
end
for _, k in Types.keys(v) do
if type(k) ~= "string" then
return "compound key " .. tostring(k) .. " is not a string"
end
local c = v[k]
local ct, e = Value.typeOf(c)
if not ct then
return e .. " (key " .. k .. ")"
end
w:u8(IDS[ct :: string])
e = wstr(ws, k)
if e then
return e
end
e = wpayload(ws, ct :: string, c)
if e then
return e
end
end
w:u8(0)
ws.depth -= 1
elseif t == "list" then
ws.depth += 1
if ws.depth > ws.maxDepth then
return "nested deeper than " .. ws.maxDepth .. " (a cycle?)"
end
local e = wlist(ws, v)
if e then
return e
end
ws.depth -= 1
elseif t == "byte" then
local n, e = integer(x, -128, 255, "byte")
if not n then
return e
end
w:u8(n % 256)
elseif t == "short" then
local n, e = integer(x, -32768, 65535, "short")
if not n then
return e
end
wi16(ws, n)
elseif t == "long" then
local hi, lo = Value.toHiLo(x)
if not hi then
return "bad long value " .. tostring(x)
end
wi64(ws, hi, lo :: number)
elseif t == "float" or t == "double" then
if type(x) ~= "number" then
return "bad " .. t .. " value " .. tostring(x)
end
if t == "float" then
if ws.le then
w:f32le(x)
else
w:f32be(x)
end
elseif ws.le then
w:f64le(x)
else
w:f64be(x)
end
elseif t == "byteArray" then
if type(x) ~= "buffer" then
return "bad byteArray value"
end
wi32(ws, buffer.len(x))
w:bytes(x)
elseif t == "intArray" then
if type(x) ~= "table" then
return "bad intArray value"
end
wi32(ws, #x)
for i = 1, #x do
local n, e = integer(x[i], -2147483648, 4294967295, "intArray element")
if not n then
return e
end
wi32(ws, n)
end
elseif t == "longArray" then
if type(x) ~= "buffer" or buffer.len(x) % 8 ~= 0 then
return "bad longArray value (a buffer of 8-byte little-endian longs)"
end
local n = buffer.len(x) // 8
wi32(ws, n)
if ws.le and not ws.net then
w:bytes(x)
else
for i = 0, n - 1 do
wi64(ws, buffer.readu32(x, i * 8 + 4), buffer.readu32(x, i * 8))
end
end
else
return "cannot write tag type " .. t
end
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
local le = net or o.endian == "little"
local t, e = Value.typeOf(v)
if not t then
return nil, e
end
local ws: WState = { w = Bytes.writer(1024), le = le, net = net, java = not le, depth = 0, maxDepth = o.maxDepth or 512 }
ws.w:u8(IDS[t :: string])
if not o.nameless then
e = wstr(ws, o.name or "")
if e then
return nil, e
end
end
e = wpayload(ws, t :: string, v)
if e then
return nil, e
end
return ws.w:finish(), nil
end
return Binary
+649
View File
@@ -0,0 +1,649 @@
--!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.
local Types = require("@rosetta/Types")
local Value = require("@rosetta/codecs/text/Nbt/Value")
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
}
local byte, sub, find = string.byte, string.sub, string.find
local TWO32 = 4294967296
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
if not p.err then
p.err, p.at = msg, p.i
end
p.i = p.n + 1
return nil
end
local function ws(p: P)
local _, e = find(p.s, "^%s*", p.i)
p.i = (e :: number) + 1
end
local function isUnquoted(c: number): boolean
return (c >= 48 and c <= 57) or (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or c == 45 or c == 46 or c == 43
end
local ESC: { [string]: string } = { ["\\"] = "\\", ["'"] = "'", ['"'] = '"', n = "\n", t = "\t", r = "\r", b = "\b", f = "\f", s = " " }
local function quoted(p: P): string?
local q = sub(p.s, p.i, p.i)
p.i += 1
local out = {}
while true do
local j = find(p.s, if q == '"' then '["\\]' else "['\\]", p.i)
if not j then
return fail(p, "unterminated string")
end
table.insert(out, sub(p.s, p.i, j - 1))
if sub(p.s, j, j) == q then
p.i = j + 1
return table.concat(out)
end
local c = sub(p.s, j + 1, j + 1)
if ESC[c] then
table.insert(out, ESC[c])
p.i = j + 2
elseif c == "x" or c == "u" or c == "U" then
local nd = if c == "x" then 2 elseif c == "u" then 4 else 8
local hex = sub(p.s, j + 2, j + 1 + nd)
if #hex ~= nd or find(hex, "[^%x]") then
p.i = j
return fail(p, "bad \\" .. c .. " escape")
end
local cp = tonumber(hex, 16) :: number
if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then
p.i = j
return fail(p, "bad code point in \\" .. c .. " escape")
end
table.insert(out, utf8.char(cp))
p.i = j + 2 + nd
else
p.i = j
return fail(p, "bad escape \\" .. c)
end
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 },
i = { -2147483648, 2147483647, 4294967295 },
}
local INT_NAME = { b = "byte", s = "short", i = "int", l = "long" }
local function integer(t: string): any
local sign, body = string.match(t, "^([+-]?)(.+)$")
body = string.gsub(body :: string, "_", "") :: string
local radix, digits, suffix = 10, body, ""
local low = string.lower(body)
local m, sfx
if sub(low, 1, 2) == "0x" then
-- b and s are hex digits: a byte / short suffix needs its signedness (0x7Fsb, 0xFFub)
m, sfx = string.match(sub(body, 3), "^(%x+)([sSuU][bBsSiIlL])$")
if not m then
m, sfx = string.match(sub(body, 3), "^(%x+)([iIlL]?)$")
end
if not m then
return nil
end
radix = 16
elseif sub(low, 1, 2) == "0b" then
m, sfx = string.match(sub(body, 3), "^([01]+)([sSuU]?[bBsSiIlL]?)$")
if m then
radix = 2
end
end
if not m then
m, sfx = string.match(body, "^(%d+)([sSuU]?[bBsSiIlL]?)$")
if not m then
return nil
end
end
digits, suffix = m :: string, string.lower(sfx :: string)
local unsigned = false
if #suffix == 2 then
unsigned = sub(suffix, 1, 1) == "u"
suffix = sub(suffix, 2)
elseif suffix == "u" then
return nil
end
if suffix == "" then
suffix = "i"
end
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)
local d = if c <= 57 then c - 48 elseif c >= 97 then c - 87 else c - 55
local x = lo * radix + d
local carry = x // TWO32
lo = x - carry * TWO32
hi = hi * radix + carry
if hi >= TWO32 then
return nil
end
end
if suffix == "l" then
local neg = sign == "-"
if radix == 10 then
if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or not neg)) then
return nil
end
end
if neg and (hi > 0 or lo > 0) then
lo = (TWO32 - lo) % TWO32
hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32
end
return tag("long", Value.fromHiLo(hi, lo))
end
if hi > 0 then
return nil
end
local r = INT_RANGE[suffix]
local v = lo
if sign == "-" then
v = -v
end
if radix ~= 10 and not unsigned and sign ~= "-" and v > r[2] and v <= r[3] then
v -= r[3] + 1 -- hex / binary literals wrap into the signed range (0xFFb = -1b)
elseif unsigned then
if v > r[3] then
return nil
end
if v > r[2] then
v -= r[3] + 1
end
end
if v < r[1] or v > r[2] then
return nil
end
if suffix == "i" then
return v
end
return tag(INT_NAME[suffix], v)
end
local function number(t: string): any
local low = string.lower(t)
if low == "true" then
return tag("byte", 1)
elseif low == "false" then
return tag("byte", 0)
end
local sfx = sub(low, -1)
local special = string.match(low, "^([+-]?)infinity[fd]$")
if special then
return tag(if sfx == "f" then "float" else "double", if special == "-" then -math.huge else math.huge)
elseif low == "nanf" or low == "nand" then
return tag(if sfx == "f" then "float" else "double", 0 / 0)
end
local iv = integer(t)
if iv ~= nil then
return iv
end
local body = string.gsub(t, "_", "")
local m, fs = string.match(body, "^([+-]?[%d%.]+[eE]?[+-]?%d*)([fFdD]?)$")
if not m then
return nil
end
-- mantissa digits[.digits] or .digits, an optional exponent; without a fraction or an exponent a suffix is needed
local mant, ex = string.match(m :: string, "^(.-)([eE][+-]?%d+)$")
if not mant then
mant = m
end
if not (string.match(mant :: string, "^[+-]?%d+%.?%d*$") or string.match(mant :: string, "^[+-]?%.%d+$")) then
return nil
end
if fs == "" and not ex and not find(mant :: string, ".", 1, true) then
return nil
end
local v = tonumber(m)
if not v then
return nil
end
if string.lower(fs :: string) == "f" then
local b = buffer.create(4)
buffer.writef32(b, 0, v)
return tag("float", buffer.readf32(b, 0))
end
return tag("double", v)
end
local parseValue: (P) -> any
local function token(p: P): string
local j = p.i
while j <= p.n and isUnquoted(byte(p.s, j)) do
j += 1
end
local t = sub(p.s, p.i, j - 1)
p.i = j
return t
end
local function key(p: P): string?
ws(p)
local c = sub(p.s, p.i, p.i)
if c == '"' or c == "'" then
return quoted(p)
end
local t = token(p)
if t == "" then
return fail(p, "expected a key")
end
return t
end
local ARRAY = { B = "byte", I = "int", L = "long" }
local function array(p: P, kind: string): any
local items = {}
ws(p)
if sub(p.s, p.i, p.i) ~= "]" then
while true do
ws(p)
local at = p.i
local t = token(p)
local v = if t ~= "" then number(t) else nil
local vt = Value.typeOf(v)
if v == nil or (vt ~= "byte" and vt ~= "short" and vt ~= "int" and vt ~= "long") then
p.i = at
return fail(p, "expected an integer in a " .. kind .. " array")
end
local x: any = if Value.isTag(v) then (v :: any).value else v
if kind == "byte" and (x < -128 or x > 127) or kind == "int" and vt == "long" then
p.i = at
return fail(p, "value out of range in a " .. kind .. " array")
end
table.insert(items, x)
ws(p)
local c = sub(p.s, p.i, p.i)
p.i += 1
if c == "]" then
break
elseif c ~= "," then
p.i -= 1
return fail(p, "expected , or ]")
end
ws(p)
if sub(p.s, p.i, p.i) == "]" then
p.i += 1
break
end
end
else
p.i += 1
end
if kind == "byte" then
local b = buffer.create(#items)
for i, x in items do
buffer.writei8(b, i - 1, x)
end
return b
elseif kind == "int" then
return tag("intArray", items)
end
return Value.longArray(items)
end
parseValue = function(p: P): any
ws(p)
if p.i > p.n then
return fail(p, "expected a value")
end
local c = sub(p.s, p.i, p.i)
if c == "{" then
p.depth += 1
if p.depth > p.maxDepth then
return fail(p, "limit: nested deeper than " .. p.maxDepth)
end
p.i += 1
local o, keys = {}, {}
ws(p)
if sub(p.s, p.i, p.i) == "}" then
p.i += 1
else
while true do
local k = key(p)
if p.err then
return nil
end
ws(p)
if sub(p.s, p.i, p.i) ~= ":" then
return fail(p, "expected :")
end
p.i += 1
local v = parseValue(p)
if p.err then
return nil
end
if o[k :: string] == nil then
table.insert(keys, k)
end
o[k :: string] = v
ws(p)
local d = sub(p.s, p.i, p.i)
p.i += 1
if d == "}" then
break
elseif d ~= "," then
p.i -= 1
return fail(p, "expected , or }")
end
ws(p)
if sub(p.s, p.i, p.i) == "}" then
p.i += 1
break
end
end
end
p.depth -= 1
return Types.object(o, keys)
elseif c == "[" then
p.depth += 1
if p.depth > p.maxDepth then
return fail(p, "limit: nested deeper than " .. p.maxDepth)
end
p.i += 1
local kind = string.match(p.s, "^%s*([BIL])%s*;", p.i)
if kind then
local _, e = find(p.s, "^%s*[BIL]%s*;", p.i)
p.i = (e :: number) + 1
local v = array(p, ARRAY[kind])
p.depth -= 1
return v
end
local items = {}
local lt: string? = nil
local mixed = false
ws(p)
if sub(p.s, p.i, p.i) == "]" then
p.i += 1
else
while true do
local v = parseValue(p)
if p.err then
return nil
end
local t = Value.typeOf(v)
if lt == nil then
lt = t
elseif t ~= lt then
mixed = true
end
table.insert(items, v)
ws(p)
local d = sub(p.s, p.i, p.i)
p.i += 1
if d == "]" then
break
elseif d ~= "," then
p.i -= 1
return fail(p, "expected , or ]")
end
ws(p)
if sub(p.s, p.i, p.i) == "]" then
p.i += 1
break
end
end
end
p.depth -= 1
if not mixed then
Value.setListType(items, lt or "end")
end
return items
elseif c == '"' or c == "'" then
return quoted(p)
end
local at = p.i
local t = token(p)
if t == "" then
return fail(p, "unexpected character " .. string.format("%q", c))
end
local v = number(t)
if v == nil then
if string.match(t, "^[+-]?%d[%d_]*[sSuU]?[bBsSiIlL]$") then
p.i = at
return fail(p, "number out of range: " .. t)
end
return t
end
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)
if p.err then
return nil, p.err, p.at
end
ws(p)
if p.i <= p.n then
return nil, "trailing characters after the value", p.i
end
return v, nil, nil
end
-- ------------------------------------------------------------------------------------------------ print
local function shortest(v: number, single: boolean): string
if v ~= v then
return "NaN"
elseif v == math.huge then
return "Infinity"
elseif v == -math.huge then
return "-Infinity"
end
local b = buffer.create(4)
if single then
buffer.writef32(b, 0, v)
v = buffer.readf32(b, 0)
end
local s = ""
for digits = if single then 6 else 15, 17 do
s = string.format("%." .. digits .. "g", v)
local back = tonumber(s) :: number
if single then
buffer.writef32(b, 0, back)
back = buffer.readf32(b, 0)
end
if back == v then
break
end
end
if not find(s, "[%.eEn]") then
s ..= ".0"
end
return s
end
Snbt.shortest = shortest
local function quote(s: string, q: string): string
local other = if q == '"' then "'" else '"'
local _, nq = string.gsub(s, q, "")
local _, no = string.gsub(s, other, "")
if nq > no then
q = other
end
local e = string.gsub(s, "[\\" .. q .. "%c]", function(c: string): string
if c == "\\" or c == q then
return "\\" .. c
elseif c == "\n" then
return "\\n"
elseif c == "\t" then
return "\\t"
elseif c == "\r" then
return "\\r"
end
return string.format("\\x%02x", byte(c))
end)
return q .. e .. q
end
local function keyText(k: string, q: string): string
if k ~= "" and not find(k, "[^%w_%-%.%+]") then
return k
end
return quote(k, q)
end
type Pr = { out: { string }, indent: string?, q: string, depth: number }
local printValue: (Pr, any, number) -> string?
local function scalar(v: any, q: string): string?
local tv = type(v)
if tv == "number" then
if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then
return string.format("%d", v)
end
return shortest(v, false) .. "d"
elseif tv == "string" then
return quote(v, q)
elseif tv == "boolean" then
return if v then "1b" else "0b"
elseif Value.isTag(v) then
local t, x = v.type, v.value
if t == "byte" then
return string.format("%db", x)
elseif t == "short" then
return string.format("%ds", x)
elseif t == "int" then
return string.format("%d", x)
elseif t == "long" then
return (if type(x) == "string" then x else string.format("%d", x)) .. "L"
elseif t == "float" then
return shortest(x, true) .. "f"
elseif t == "double" then
return shortest(x, false) .. "d"
elseif t == "string" then
return quote(x, q)
end
end
return nil
end
local function seq(pr: Pr, head: string, items: { string }, close: string)
if pr.indent and #items > 0 then
local pad = string.rep(pr.indent, pr.depth)
table.insert(pr.out, head .. "\n" .. pad .. pr.indent .. table.concat(items, ",\n" .. pad .. pr.indent) .. "\n" .. pad .. close)
else
table.insert(pr.out, head .. table.concat(items, if pr.indent then ", " else ",") .. close)
end
end
local function sub1(pr: Pr, v: any): (string?, string?)
local inner: Pr = { out = {}, indent = pr.indent, q = pr.q, depth = pr.depth + 1 }
local e = printValue(inner, v, inner.depth)
if e then
return nil, e
end
return table.concat(inner.out), nil
end
printValue = function(pr: Pr, v: any, depth: number): string?
if depth > 512 then
return "nested deeper than 512 (a cycle?)"
end
local s = scalar(v, pr.q)
if s then
table.insert(pr.out, s)
return nil
end
local t, terr = Value.typeOf(v)
if not t then
return terr
end
if t == "byteArray" then
local items = table.create(buffer.len(v)) :: { string }
for i = 0, buffer.len(v) - 1 do
items[i + 1] = buffer.readi8(v, i) .. "b"
end
seq(pr, "[B;", items, "]")
elseif t == "intArray" then
local items = {}
for i, x in v.value do
items[i] = string.format("%d", x)
end
seq(pr, "[I;", items, "]")
elseif t == "longArray" then
local items = {}
for i, x in Value.longs(v) do
items[i] = (if type(x) == "string" then x else string.format("%d", x)) .. "L"
end
seq(pr, "[L;", items, "]")
elseif t == "list" then
local items: { string } = {}
for i = 1, #v do
local x, e = sub1(pr, v[i])
if e then
return e
end
items[i] = x :: string
end
seq(pr, "[", items, "]")
else
local items = {}
for _, k in Types.keys(v) do
if type(k) ~= "string" then
return "compound key " .. tostring(k) .. " is not a string"
end
local x, e = sub1(pr, v[k])
if e then
return e
end
table.insert(items, keyText(k, pr.q) .. (if pr.indent then ": " else ":") .. (x :: string))
end
seq(pr, "{", items, "}")
end
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
local pr: Pr = {
out = {},
indent = if type(ind) == "number" then string.rep(" ", ind) elseif type(ind) == "string" then ind else nil,
q = if o.quote == "'" then "'" else '"',
depth = 0,
}
local e = printValue(pr, v, 0)
if e then
return nil, e
end
return table.concat(pr.out), nil
end
Value.print = function(v: any): string
return Snbt.print(v) or "?"
end
return Snbt
+256
View File
@@ -0,0 +1,256 @@
--!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 = "<name>", 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.
local Types = require("@rosetta/Types")
local Value = {}
-- tag ids (the binary format) <-> names
Value.NAMES = {
[0] = "end",
"byte",
"short",
"int",
"long",
"float",
"double",
"byteArray",
"string",
"list",
"compound",
"intArray",
"longArray",
} :: { [number]: string }
Value.IDS = {} :: { [string]: number }
for id = 0, 12 do
Value.IDS[Value.NAMES[id]] = id
end
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
TagMeta.__tostring = function(v: any): string
return Value.print(v)
end
TagMeta.__eq = function(a: any, b: any): boolean
if a.type ~= b.type then
return false
end
local x, y = a.value, b.value
if type(x) == "buffer" and type(y) == "buffer" then
return buffer.tostring(x) == buffer.tostring(y)
elseif type(x) == "table" and type(y) == "table" then
if #x ~= #y then
return false
end
for i = 1, #x do
if x[i] ~= y[i] then
return false
end
end
return true
end
return x == y
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
return s * TWO32 + lo
end
local neg = s < 0
if neg then -- magnitude = 2^64 - v
lo = (TWO32 - lo) % TWO32
hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32
end
local parts = {}
while hi > 0 or lo > 0 do -- divide (hi, lo) by 10^4: r * 2^32 + lo < 10^4 * 2^32 stays exact, ql < 2^32
local qh = hi // 10000
local x = (hi - qh * 10000) * TWO32 + lo
local ql = x // 10000
local d = x - ql * 10000
hi, lo = qh, ql
table.insert(parts, 1, string.format(if hi > 0 or lo > 0 then "%04d" else "%d", d))
end
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
return nil, nil
end
local hi = v // TWO32
local lo = v - hi * TWO32
return hi % TWO32, lo
elseif type(v) == "string" then
local neg, digits = string.match(v, "^(%-?)(%d+)$")
if not digits or #digits > 19 then
return nil, nil
end
local hi, lo = 0, 0
for i = 1, #digits do
local x = lo * 10 + (string.byte(digits, i) - 48)
local carry = x // TWO32
lo = x - carry * TWO32
hi = hi * 10 + carry
end
if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or neg == "")) then
return nil, nil
end
if neg == "-" and (hi > 0 or lo > 0) then
lo = (TWO32 - lo) % TWO32
hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32
end
return hi, lo
end
return nil, nil
end
-- ------------------------------------------------------------------------------------------------ constructors
local function tag(name: string, v: any): Tag
return setmetatable({ type = name, value = v }, TagMeta) :: any
end
function Value.byte(n: number): Tag
return tag("byte", n)
end
function Value.short(n: number): Tag
return tag("short", n)
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)
if hi then
v = Value.fromHiLo(hi, lo :: number)
end
end
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))
end
function Value.double(n: number): Tag
return tag("double", n)
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)
end
local list: { any } = (t or {}) :: any
local b = buffer.create(#list * 8)
for i, x in list do
local hi, lo = Value.toHiLo(x)
buffer.writeu32(b, (i - 1) * 8, lo or 0)
buffer.writeu32(b, (i - 1) * 8 + 4, hi or 0)
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 }
for i = 0, buffer.len(b) // 8 - 1 do
out[i + 1] = Value.fromHiLo(buffer.readu32(b, i * 8 + 4), buffer.readu32(b, i * 8))
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
return t
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
function Value.setListType(t: any, name: string)
listTypes[t] = name
end
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
return if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then "int" else "double", nil
elseif tv == "string" then
return "string", nil
elseif tv == "boolean" then
return "byte", nil
elseif tv == "buffer" then
return "byteArray", nil
elseif tv == "table" then
if getmetatable(v) == TagMeta then
local n = v.type
if Value.IDS[n] == nil or n == "end" or n == "list" or n == "compound" or n == "string" or n == "int" or n == "byteArray" then
if n == "int" or n == "string" or n == "byteArray" then
return n, nil
end
return nil, "bad tag type " .. tostring(n)
end
return n, nil
elseif Types.isObject(v) then
return "compound", nil
elseif listTypes[v] or v[1] ~= nil or next(v) == nil then
return "list", nil
end
return "compound", nil
end
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
elseif type(v) == "boolean" then
return if v then 1 else 0
elseif Value.isTag(v) then
local x = v.value
if type(x) == "number" then
return x
elseif type(x) == "string" then
return tonumber(x)
end
end
return nil
end
return Value
+380
View File
@@ -0,0 +1,380 @@
--!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.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Value = require("@rosetta/codecs/text/Nbt/Value")
local Binary = require("@rosetta/codecs/text/Nbt/Binary")
local Snbt = require("@rosetta/codecs/text/Nbt/Snbt")
local Nbt = {}
export type Tag = Value.Tag
export type Info = {
name: string, -- the root tag's name
endian: "big" | "little",
varint: boolean?, -- Bedrock network NBT
compression: "gzip" | "zlib" | "none",
header: number?, -- Bedrock level.dat: the storage version from the 8-byte header
}
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"
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)
}
Nbt.TAG = Value.IDS -- name -> id
Nbt.TAG_NAMES = Value.NAMES -- id -> name
Nbt.byte = Value.byte
Nbt.short = Value.short
Nbt.int = Value.int
Nbt.long = Value.long
Nbt.float = Value.float
Nbt.double = Value.double
Nbt.intArray = Value.intArray
Nbt.longArray = Value.longArray
Nbt.longs = Value.longs
Nbt.list = Value.list
Nbt.listType = Value.listType
Nbt.compound = Value.compound
Nbt.typeOf = Value.typeOf
Nbt.isTag = Value.isTag
Nbt.number = Value.number
Nbt.fromHiLo = Value.fromHiLo
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
return nil, aerr
end
local v, name, at = Binary.read(b, o, o + l, opts :: any)
if v == nil then
return nil, Err.from(name, (at or o) - o)
end
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
return nil, Err.new(Err.ARG, tostring(e))
end
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
return nil, aerr
end
local c0 = if l >= 2 then buffer.readu8(b, o) else 0
local c1 = if l >= 2 then buffer.readu8(b, o + 1) else 0
local out, err, comp
if c0 == 0x1f and c1 == 0x8b then
out, err = Deflate.gunzip(b, o, l)
comp = "gzip"
elseif c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0 then
out, err = Deflate.zlib(b, o, l)
comp = "zlib"
else
return b, o, o + l, "none"
end
if not out then
return nil, err
end
if buffer.len(out) > (maxBytes or 2 ^ 28) then
return nil, Err.new(Err.LIMIT, "inflates to " .. buffer.len(out) .. " bytes, over maxBytes")
end
return out, 0, buffer.len(out), comp
end
export type Peek = {
compression: string, -- "gzip" | "zlib" | "none"
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
firstName: string?,
head: buffer, -- the first (up to 1024) uncompressed bytes
}
local function plausibleName(b: buffer, p: number, n: number): string?
if p + n > buffer.len(b) or n > 256 then
return nil
end
local s = buffer.readstring(b, p, n)
if string.find(s, "[%z\1-\31\127]") then
return nil
end
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)
if l < 3 then
return nil
end
local c0, c1 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1)
local head: buffer
local comp = "none"
if c0 == 0x1f and c1 == 0x8b or (c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0) then
local h = Deflate.peek(buf, o, l, 1024)
if not h then
return nil
end
head, comp = h, if c0 == 0x1f then "gzip" else "zlib"
else
local n = math.min(l, 1024)
head = buffer.create(n)
buffer.copy(head, 0, buf, o, n)
end
local hn = buffer.len(head)
local function at(p: number, endian: string, header: boolean): Peek?
if p + 3 > hn then
return nil
end
local t = buffer.readu8(head, p)
if t ~= 10 and t ~= 9 then
return nil
end
local function u16(q: number): number
local a, b = buffer.readu8(head, q), buffer.readu8(head, q + 1)
return if endian == "big" then a * 256 + b else b * 256 + a
end
local nl = u16(p + 1)
local name = plausibleName(head, p + 3, nl)
if not name then
return nil
end
local res: Peek = { compression = comp, endian = endian :: any, header = header, rootType = Value.NAMES[t], name = name, head = head }
local q = p + 3 + nl
if t == 10 and q < hn then
local ft = buffer.readu8(head, q)
if ft > 12 then
return nil
end
if ft == 0 then
res.firstType = "end" -- an empty root compound
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
return nil
end
res.firstType, res.firstName = Value.NAMES[ft], fname
end
end
return res
end
if hn >= 12 and buffer.readu32(head, 4) == (if comp == "none" then l else -1) - 8 then
local r = at(8, "little", true)
if r then
return r
end
end
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)
if not b then
return nil, s
end
local data: buffer, start: number, stop: number = b, s, e :: number
local function try(endian: string, from: number, varint: boolean?): (any, any, number?)
return Binary.read(data, from, stop, { endian = endian :: any, varint = varint, nameless = o.nameless, maxDepth = o.maxDepth })
end
local header: number? = nil
local v, name, at
if o.varint then
v, name, at = try("little", start, true)
elseif o.endian then
local from = start
if o.endian == "little" and stop - start >= 8 and buffer.readu32(data, start + 4) == stop - start - 8 then
header, from = buffer.readu32(data, start), start + 8
end
v, name, at = try(o.endian, from)
else
-- Bedrock level.dat: version, length (u32le), then little-endian NBT
if stop - start >= 9 and buffer.readu32(data, start + 4) == stop - start - 8 and buffer.readu8(data, start + 8) == 10 then
v, name, at = try("little", start + 8)
if v ~= nil then
header = buffer.readu32(data, start)
o = table.clone(o)
o.endian = "little"
end
end
if v == nil then
local bv, bn, ba = try("big", start)
if bv ~= nil and ba == stop then
v, name, at, o = bv, bn, ba, table.clone(o)
o.endian = "big"
else
local lv, ln, la = try("little", start)
if lv ~= nil and (la == stop or bv == nil) then
v, name, at, o = lv, ln, la, table.clone(o)
o.endian = "little"
elseif bv ~= nil then
v, name, at, o = bv, bn, ba, table.clone(o)
o.endian = "big"
else
v, name, at = nil, bn, ba
end
end
end
end
if v == nil then
return nil, Err.from(name, (at or start) - start)
end
local info: Info = {
name = name,
endian = if o.varint or o.endian == "little" then "little" else "big",
varint = if o.varint then true else nil,
compression = comp :: any,
header = header,
}
if type(v) == "table" then
infos[v] = info
end
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)
local endian = o.endian or (info and info.endian) or "big"
local varint = if o.varint ~= nil then o.varint else (info and info.varint)
local raw, e = Binary.write(v, {
endian = endian,
varint = varint,
nameless = o.nameless,
name = o.name or (info and info.name) or "",
})
if not raw then
return nil, Err.new(Err.ARG, tostring(e))
end
local header = if o.header ~= nil then o.header else (info and info.header)
if header then
local h = buffer.create(buffer.len(raw) + 8)
buffer.writeu32(h, 0, header)
buffer.writeu32(h, 4, buffer.len(raw))
buffer.copy(h, 8, raw)
raw = h
end
local comp = o.compression or (info and info.compression) or (if endian == "big" then "gzip" else "none")
if comp == "gzip" then
return Deflate.gzip(raw, { level = o.level })
elseif comp == "zlib" then
return Deflate.zlibCompress(raw, { level = o.level })
elseif comp ~= "none" then
return nil, Err.new(Err.ARG, "unknown compression " .. tostring(comp))
end
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
return nil, Err.new(Err.ARG, "Nbt.parse: text must be a string")
end
local v, e, at = Snbt.parse(s, opts)
if v == nil then
return nil, Err.from(e, (at or 1) - 1)
end
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
return nil, Err.new(Err.ARG, tostring(e))
end
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
local k, rest = string.match(part, "^([^%[]*)(.*)$")
if k ~= "" then
if type(cur) ~= "table" or Value.isTag(cur) then
return nil
end
cur = cur[k]
end
for idx in string.gmatch(rest :: string, "%[(%-?%d+)%]") do
local i = tonumber(idx) :: number
if type(cur) == "table" and not Value.isTag(cur) then
cur = cur[i + 1]
elseif Value.isTag(cur) and type(cur.value) == "table" then
cur = cur.value[i + 1]
elseif type(cur) == "buffer" and i >= 0 and i < buffer.len(cur) then
cur = buffer.readi8(cur, i)
else
return nil
end
end
end
return cur
end
Nbt.object = Types.object
Nbt.shortest = Snbt.shortest
return Nbt
+94
View File
@@ -0,0 +1,94 @@
--!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.
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
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
-- CP1252 bytes 0x80..0x9F (undefined ones map to U+FFFD)
Text.CP1252 = {
[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,
}
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
local readu16 = buffer.readu16
local function unit(at: number): number
local v = readu16(b, at)
return if bigEndian then (v % 256) * 256 + v // 256 else v
end
while k + 1 < n do
local c = unit(o + k)
k += 2
if c >= 0xD800 and c < 0xDC00 and k + 1 < n then
local lo = unit(o + k)
if lo >= 0xDC00 and lo < 0xE000 then
c = 0x10000 + (c - 0xD800) * 1024 + (lo - 0xDC00)
k += 2
end
end
if c >= 0xD800 and c < 0xE000 then
c = 0xFFFD
end
table.insert(out, Text.utf8char(c))
end
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)
end
if utf8.len(text) then
return text
end
if warnings then
table.insert(warnings, "text is not UTF-8: read as Windows-1252")
end
local out = table.create(#text)
for i = 1, #text do
local b = string.byte(text, i)
if b < 0x80 then
out[i] = string.char(b)
else
out[i] = utf8.char(if b < 0xA0 then Text.CP1252[b] or 0xFFFD else b)
end
end
return table.concat(out)
end
function Text.lines(text: string): { string }
text = string.gsub(text, "\r\n?", "\n")
local out = {}
for line in string.gmatch(text .. "\n", "([^\n]*)\n") do
table.insert(out, line)
end
return out
end
return Text
+216
View File
@@ -0,0 +1,216 @@
--!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.
local Url = {}
export type Location = { url: string, playable: boolean, reason: string?, [string]: any }
export type Parts = {
scheme: string?,
authority: string?,
path: string,
query: string?,
fragment: string?,
}
-- Splits a URI reference into its five components (RFC 3986 appendix B).
function Url.split(ref: string): Parts
local scheme, rest = string.match(ref, "^([%a][%w+%.%-]*):(.*)$")
if not scheme then
rest = ref
end
local s = rest :: string
local fragment, query, authority
local i = string.find(s, "#", 1, true)
if i then
fragment = string.sub(s, i + 1)
s = string.sub(s, 1, i - 1)
end
i = string.find(s, "?", 1, true)
if i then
query = string.sub(s, i + 1)
s = string.sub(s, 1, i - 1)
end
if string.sub(s, 1, 2) == "//" then
local j = string.find(s, "/", 3, true)
if j then
authority = string.sub(s, 3, j - 1)
s = string.sub(s, j)
else
authority = string.sub(s, 3)
s = ""
end
end
return { scheme = scheme, authority = authority, path = s, query = query, fragment = fragment }
end
-- Recomposes components (RFC 3986 section 5.3).
function Url.join(p: Parts): string
local out = {}
if p.scheme then
table.insert(out, p.scheme .. ":")
end
if p.authority then
table.insert(out, "//" .. p.authority)
end
table.insert(out, p.path)
if p.query then
table.insert(out, "?" .. p.query)
end
if p.fragment then
table.insert(out, "#" .. p.fragment)
end
return table.concat(out)
end
-- RFC 3986 section 5.2.4
function Url.removeDotSegments(path: string): string
local input = path
local output = {}
while input ~= "" do
if string.sub(input, 1, 3) == "../" then
input = string.sub(input, 4)
elseif string.sub(input, 1, 2) == "./" then
input = string.sub(input, 3)
elseif string.sub(input, 1, 3) == "/./" then
input = string.sub(input, 3)
elseif input == "/." then
input = "/"
elseif string.sub(input, 1, 4) == "/../" then
input = string.sub(input, 4)
table.remove(output)
elseif input == "/.." then
input = "/"
table.remove(output)
elseif input == "." or input == ".." then
input = ""
else
-- move the first segment (with its leading "/", up to the next "/") to the output
local j = string.find(input, "/", 2, true)
local seg = if j then string.sub(input, 1, j - 1) else input
table.insert(output, seg)
input = string.sub(input, #seg + 1)
end
end
return table.concat(output)
end
-- Resolves a reference against an absolute base URI (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 = "" }
if r.scheme then
t.scheme, t.authority, t.path, t.query = r.scheme, r.authority, Url.removeDotSegments(r.path), r.query
else
if r.authority then
t.authority, t.path, t.query = r.authority, Url.removeDotSegments(r.path), r.query
else
if r.path == "" then
t.path = b.path
t.query = if r.query then r.query else b.query
else
if string.sub(r.path, 1, 1) == "/" then
t.path = Url.removeDotSegments(r.path)
else
-- merge (5.2.3)
local merged
if b.authority and b.path == "" then
merged = "/" .. r.path
else
local k = string.match(b.path, "^.*()/")
merged = (if k then string.sub(b.path, 1, k) else "") .. r.path
end
t.path = Url.removeDotSegments(merged)
end
t.query = r.query
end
t.authority = b.authority
end
t.scheme = b.scheme
end
t.fragment = r.fragment
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.
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
or string.sub(s, 1, 2) == "\\\\"
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
end
local scheme = string.match(s, "^([%a][%w+%.%-]*):")
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
return { url = loc, playable = false, reason = "local path" }
end
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
if scheme then
if scheme == "http" or scheme == "https" then
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
return { url = loc, playable = false, reason = "relative path without a base URL" }
end
if scheme == "http" or scheme == "https" then
return { url = url, playable = true }
elseif scheme == "file" then
return { url = url, playable = false, reason = "local path" }
end
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
end
local s = Url.scheme(baseUrl)
if s and Url.split(baseUrl).authority ~= nil or s == "file" then
return Url.encodeUnsafe(baseUrl), s
elseif Url.isWindowsPath(baseUrl) then
return baseUrl, "windows"
end
if warnings then
table.insert(warnings, "base URL is not absolute: " .. baseUrl)
end
return nil, nil
end
return Url
+763
View File
@@ -0,0 +1,763 @@
--!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.
local Text = require("@rosetta/codecs/text/Text")
local Types = require("@rosetta/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 utf8char = Text.utf8char
Parse.utf8char = utf8char
local CP1252: { [number]: number } = {
[0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020,
[0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152,
[0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022,
[0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A,
[0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178,
}
local function utf16(s: string, start: number, le: boolean): (string?, string?)
local out = table.create(#s // 2)
local n = 0
local i = start
local len = #s
while i + 1 <= len do
local a, b = byte(s, i, i + 1)
local u = if le then a + b * 256 else a * 256 + b
i += 2
if u >= 0xD800 and u <= 0xDBFF then
if i + 1 > len then
return nil, "truncated UTF-16 surrogate pair"
end
local c, d = byte(s, i, i + 1)
local lo = if le then c + d * 256 else c * 256 + d
if lo < 0xDC00 or lo > 0xDFFF then
return nil, "bad UTF-16 surrogate pair"
end
i += 2
u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00)
elseif u >= 0xDC00 and u <= 0xDFFF then
return nil, "bad UTF-16 surrogate pair"
end
n += 1
out[n] = utf8char(u)
end
if i <= len then
return nil, "odd number of bytes in UTF-16 text"
end
return table.concat(out), nil
end
-- toUtf8(s) -> UTF-8 text (BOM removed), the encoding name | nil, message
function Parse.toUtf8(s: string): (string?, string)
local b1, b2, b3 = byte(s, 1, 3)
if b1 == 0xEF and b2 == 0xBB and b3 == 0xBF then
return sub(s, 4), "utf-8"
elseif b1 == 0xFF and b2 == 0xFE then
local t, e = utf16(s, 3, true)
return t, e or "utf-16le"
elseif b1 == 0xFE and b2 == 0xFF then
local t, e = utf16(s, 3, false)
return t, e or "utf-16be"
elseif b1 == 0x3C and b2 == 0 then
local t, e = utf16(s, 1, true)
return t, e or "utf-16le"
elseif b1 == 0 and b2 == 0x3C then
local t, e = utf16(s, 1, false)
return t, e or "utf-16be"
end
local decl = match(s, "^<%?xml[^>]-%?>")
local enc = if decl then match(decl, "encoding%s*=%s*[\"']([%w%._%-]+)[\"']") else nil
if enc then
local e = lower(enc)
if e == "utf-8" or e == "utf8" or e == "us-ascii" or e == "ascii" then
if find(s, "[\128-\255]") and not utf8.len(s) then
return nil, "invalid UTF-8"
end
return s, e
elseif e == "iso-8859-1" or e == "latin1" or e == "latin-1" or e == "iso8859-1" or e == "windows-1252" or e == "cp1252" then
local w = e == "windows-1252" or e == "cp1252"
return (gsub(s, "[\128-\255]", function(c: string): string
local v = byte(c)
return utf8char(if w then CP1252[v] or v else v)
end)), e
elseif e == "utf-16" or e == "utf-16le" or e == "utf-16be" then
return s, "utf-8" -- declared UTF-16 but read as 8-bit text: trust the bytes
end
return nil, "unsupported encoding " .. enc
end
if find(s, "[\128-\255]") and not utf8.len(s) then
return nil, "invalid UTF-8"
end
return s, "utf-8"
end
-- the <?xml ...?> pseudo-attributes, strictly: version, then encoding?, then standalone?, each after whitespace
local function xmlDecl(data: string): { [string]: string }?
local p = 1
local out: { [string]: string } = {}
for k, key in { "version", "encoding", "standalone" } do
local ws = match(data, "^[ \t\n]*()", p) :: any
local q, v, e = match(data, "^" .. key .. "[ \t\n]*=[ \t\n]*([\"'])(.-)%1()", ws)
if q then
if k > 1 and ws == p then
return nil -- no whitespace before
end
if (key == "version" and not match(v, "^1%.%d+$"))
or (key == "encoding" and not match(v, "^%a[%w%._%-]*$"))
or (key == "standalone" and v ~= "yes" and v ~= "no")
then
return nil
end
out[key] = v
p = e
elseif key == "version" then
return nil
end
end
if match(data, "^[ \t\n]*()", p) ~= #data + 1 then
return nil
end
return out
end
-- the events iterator: next() -> event, a, b, c
-- "decl", { version, encoding, standalone } the <?xml ...?> declaration
-- "doctype", raw, info raw = the text between "<!DOCTYPE" and ">"; info = { name,
-- publicId, systemId, entities }
-- "start", name, attrs (Types.object), ns ns: the element's namespace URI (opts.namespaces) or nil
-- "end", name
-- "text", s character data, entities decoded (whitespace-only dropped
-- unless opts.whitespace)
-- "cdata", s "comment", s "pi", target, data
-- "error", message, offset then the iterator ends
-- nil at the end of the document.
function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any)
local o: Options = opts or {}
local keepWs = o.whitespace == true
local nsOn = o.namespaces == true
local maxExp = o.maxExpansion or 1e7
local maxDepth = o.maxDepth or 10000
local entities: { [string]: string } = {}
if o.entities then
for k, v in o.entities do
entities[k] = v
end
end
local external: { [string]: boolean } = {}
local expanded = 0
if find(s, "\r", 1, true) then
s = gsub(gsub(s, "\r\n", "\n"), "\r", "\n")
end
local n = #s
local i = 1
local stack: { string } = {}
local nsStack: { { [string]: string } } = {}
local preserve: { boolean } = {}
local depth = 0
local rootSeen = false
local rootDone = false
local dead = false
local pending: { any }? = nil -- an "end" queued after a self-closing start
local errMsg: string? = nil
local errAt = 0
local function fail(msg: string, at: number): (string, string, number)
dead = true
return "error", msg, at - 1
end
-- decode entity / character references in raw text; nil on error (errMsg set)
local decode: (raw: string, at: number, level: number) -> string?
function decode(raw: string, at: number, level: number): string?
if not find(raw, "&", 1, true) then
return raw
end
local parts = {}
local np = 0
local p = 1
while true do
local a = find(raw, "&", p, true)
if not a then
break
end
np += 1
parts[np] = sub(raw, p, a - 1)
local ref, e = match(raw, "^&([^;&%s<]*);()", a)
if not ref then
errMsg, errAt = "bad reference (no ';')", at + a - 1
return nil
end
local rep: string
if byte(ref) == 35 then -- #
local cp = if byte(ref, 2) == 120 then tonumber(match(ref, "^#x(%x+)$") or "", 16) else tonumber(match(ref, "^#(%d+)$") or "")
if not cp or cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) or cp == 0xFFFE or cp == 0xFFFF then
errMsg, errAt = "bad character reference &" .. ref .. ";", at + a - 1
return nil
end
rep = utf8char(cp)
else
local pre = PREDEF[ref]
if pre then
rep = pre
else
local ent = entities[ref]
if not ent then
errMsg = if external[ref] then "external entity &" .. ref .. "; not supported" else "undefined entity &" .. ref .. ";"
errAt = at + a - 1
return nil
end
if level > 40 then
errMsg, errAt = "entity references nested too deeply (recursive?)", at + a - 1
return nil
end
local r = decode(ent, at + a - 1, level + 1)
if not r then
return nil
end
rep = r
end
end
expanded += #rep
if expanded > maxExp then
errMsg, errAt = "entity expansion over the limit", at + a - 1
return nil
end
np += 1
parts[np] = rep
p = e :: any
end
np += 1
parts[np] = sub(raw, p)
return table.concat(parts)
end
local function lookupNs(prefix: string): string?
for d = depth, 1, -1 do
local m = nsStack[d]
if m and m[prefix] ~= nil then
return m[prefix]
end
end
if prefix == "xml" then
return "http://www.w3.org/XML/1998/namespace"
end
return nil
end
-- a quoted literal at p -> its content, the position after it | nil
local function literal(p: number): (string?, number)
local q = byte(s, p)
if q ~= 34 and q ~= 39 then
return nil, p
end
local e = find(s, if q == 34 then '"' else "'", p + 1, true)
if not e then
return nil, p
end
return sub(s, p + 1, e - 1), e + 1
end
-- an ExternalID (SYSTEM "sys" | PUBLIC "pub" "sys") at p -> publicId, systemId, next | nil
local function externalId(p: number): (string?, string?, number?)
local kw = sub(s, p, p + 5)
if kw == "SYSTEM" then
local q = match(s, "^[ \t\n]+()", p + 6) :: any
if not q then
return nil, nil, nil
end
local sys, e = literal(q)
if not sys then
return nil, nil, nil
end
return "", sys, e
elseif kw == "PUBLIC" then
local q = match(s, "^[ \t\n]+()", p + 6) :: any
if not q then
return nil, nil, nil
end
local pub, e = literal(q)
if not pub or find(pub, "[^ \r\n%w%-'()+,./:=?;!*#@$_%%]") then
return nil, nil, nil
end
local r = match(s, "^[ \t\n]+()", e) :: any
if not r then
return nil, nil, nil
end
local sys, e2 = literal(r)
if not sys then
return nil, nil, nil
end
return pub, sys, e2
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
end
local p = 1
local parts = {}
while true do
local a = find(v, "&", p, true)
if not a then
table.insert(parts, sub(v, p))
break
end
table.insert(parts, sub(v, p, a - 1))
local hex = match(v, "^&#x(%x+);", a)
local dec = match(v, "^&#(%d+);", a)
if hex or dec then
local cp = tonumber(hex or dec, if hex then 16 else 10) :: number
if cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) then
return nil
end
table.insert(parts, utf8char(cp))
p = (find(v, ";", a, true) :: number) + 1
else
local name = match(v, "^&([%a_:\128-\255][%w_:%.%-\128-\255]*);", a)
if not name then
return nil
end
table.insert(parts, "&" .. name .. ";")
p = a + #name + 2
end
end
return table.concat(parts)
end
-- the DOCTYPE at i (just past "<!DOCTYPE"): its raw text and info { name, publicId, systemId, entities }; records
-- the internal subset's general entities. nil, message on bad syntax.
local function doctype(): (string?, any)
local start = i
local p = match(s, "^[ \t\n]+()", i) :: any
if not p then
return nil, "bad DOCTYPE"
end
local name = match(s, NAME, p)
if not name then
return nil, "bad DOCTYPE name"
end
local info: any = { name = name, entities = {} }
p += #name
local q = match(s, "^[ \t\n]*()", p) :: any
if q > p and (sub(s, q, q + 5) == "SYSTEM" or sub(s, q, q + 5) == "PUBLIC") then
local pub, sys, e = externalId(q)
if not pub then
return nil, "bad DOCTYPE external id"
end
info.publicId = if pub ~= "" then pub else nil
info.systemId = sys
q = match(s, "^[ \t\n]*()", e) :: any
end
if byte(s, q) == 91 then -- the internal subset
q += 1
while true do
q = match(s, "^[ \t\n]*()", q) :: any
local c = byte(s, q)
if c == 93 then
q += 1
break
elseif c == 37 then -- %name;
local pe = match(s, "^%%[%a_:\128-\255][%w_:%.%-\128-\255]*;()", q)
if not pe then
return nil, "bad parameter-entity reference"
end
q = pe :: any
elseif sub(s, q, q + 3) == "<!--" then
local e = find(s, "--", q + 4, true)
if not e or byte(s, e + 2) ~= 62 then
return nil, if e then "'--' inside a comment" else "unterminated comment in DOCTYPE"
end
q = e + 3
elseif sub(s, q, q + 1) == "<?" then
local target = match(s, NAME, q + 2)
local e = find(s, "?>", q + 2, true)
if not target or not e or lower(target) == "xml" then
return nil, "bad processing instruction in DOCTYPE"
end
q = e + 2
elseif sub(s, q, q + 7) == "<!ENTITY" then
local r = match(s, "^[ \t\n]+()", q + 8) :: any
if not r then
return nil, "bad ENTITY declaration"
end
local isPe = false
if byte(s, r) == 37 then
isPe = true
r = match(s, "^[ \t\n]+()", r + 1) :: any
if not r then
return nil, "bad ENTITY declaration"
end
end
local ename = match(s, NAME, r)
if not ename then
return nil, "bad ENTITY name"
end
r = match(s, "^[ \t\n]+()", r + #ename) :: any
if not r then
return nil, "bad ENTITY declaration"
end
local val, e = literal(r)
if val then
local v = entityValue(val)
if not v then
return nil, "bad ENTITY value"
end
if not isPe and entities[ename] == nil then
entities[ename] = v
info.entities[ename] = v
end
r = e
else
local pub, _, e2 = externalId(r)
if not pub then
return nil, "bad ENTITY declaration"
end
r = e2 :: number
local nd = match(s, "^[ \t\n]+NDATA[ \t\n]+()", r)
if nd then
local nn = match(s, NAME, nd)
if not nn or isPe then
return nil, "bad NDATA"
end
r = nd + #nn
end
if not isPe then
external[ename] = true
end
end
r = match(s, "^[ \t\n]*()", r) :: any
if byte(s, r) ~= 62 then
return nil, "bad ENTITY declaration"
end
q = r + 1
elseif sub(s, q, q + 8) == "<!ELEMENT" or sub(s, q, q + 8) == "<!ATTLIST" or sub(s, q, q + 9) == "<!NOTATION" then
local kw = match(s, "^<!(%u+)", q) :: string
local r = match(s, "^[ \t\n]+()", q + 2 + #kw) :: any
if not r or not match(s, NAME, r) then
return nil, "bad " .. kw .. " declaration"
end
-- skip to the closing '>' outside quotes
while true do
local c2 = byte(s, r)
if c2 == nil then
return nil, "unterminated DOCTYPE"
elseif c2 == 34 or c2 == 39 then
local e = find(s, if c2 == 34 then '"' else "'", r + 1, true)
if not e then
return nil, "unterminated DOCTYPE"
end
r = e + 1
elseif c2 == 62 then
break
elseif c2 == 60 then
return nil, "bad " .. kw .. " declaration"
else
r += 1
end
end
q = r + 1
elseif c == nil then
return nil, "unterminated DOCTYPE"
else
return nil, "bad markup in the DOCTYPE"
end
end
q = match(s, "^[ \t\n]*()", q) :: any
end
if byte(s, q) ~= 62 then
return nil, if q > n then "unterminated DOCTYPE" else "bad DOCTYPE"
end
i = q + 1
return sub(s, start, q - 1), info
end
return function(): (string?, any, any, any)
if dead then
return nil
end
if pending then
local ev = pending
pending = nil
depth -= 1
if depth == 0 then
rootDone = true
end
return "end", ev[1]
end
while true do
if i > n then
dead = true
if depth > 0 then
return "error", "unclosed element <" .. stack[depth] .. ">", n
end
if not rootSeen then
return "error", "no root element", n
end
return nil
end
local c = byte(s, i)
if c ~= 60 then -- text
local e = find(s, "<", i, true) or (n + 1)
local raw = sub(s, i, e - 1)
local start = i
i = e
local wsOnly = not find(raw, "[^ \t\n]")
if depth == 0 then
if not wsOnly then
return fail(if rootDone then "text after the root element" else "text before the root element", start)
end
else
if find(raw, "]]>", 1, true) then
return fail("']]>' in text", start + (find(raw, "]]>", 1, true) :: number) - 1)
end
local bad = find(raw, "[%z\1-\8\11\12\14-\31]")
if bad then
return fail("control character in text", start + bad - 1)
end
if not wsOnly or keepWs or preserve[depth] then
local t = decode(raw, start, 0)
if not t then
return fail(errMsg :: string, errAt)
end
return "text", t
end
end
continue
end
local c2 = byte(s, i + 1)
if c2 == 47 then -- </
local name = match(s, NAME, i + 2)
if not name then
return fail("bad end tag", i)
end
local p = match(s, "^[ \t\n]*()", i + 2 + #name) :: any
if byte(s, p) ~= 62 then
return fail(if p > n then "unterminated end tag" else "bad end tag", p)
end
if depth == 0 or stack[depth] ~= name then
return fail("mismatched end tag </" .. name .. ">" .. (if depth > 0 then " (open: <" .. stack[depth] .. ">)" else ""), i)
end
i = p + 1
stack[depth] = nil
nsStack[depth] = nil
preserve[depth] = nil
depth -= 1
if depth == 0 then
rootDone = true
end
return "end", name
elseif c2 == 33 then -- <!
if sub(s, i + 2, i + 3) == "--" then
local e = find(s, "--", i + 4, true)
if not e then
return fail("unterminated comment", i)
end
if byte(s, e + 2) ~= 62 then
return fail(if e + 2 > n then "unterminated comment" else "'--' inside a comment", e)
end
local text = sub(s, i + 4, e - 1)
i = e + 3
return "comment", text
elseif sub(s, i + 2, i + 8) == "[CDATA[" then
if depth == 0 then
return fail("CDATA outside the root element", i)
end
local e = find(s, "]]>", i + 9, true)
if not e then
return fail("unterminated CDATA section", i)
end
local text = sub(s, i + 9, e - 1)
i = e + 3
return "cdata", text
elseif sub(s, i + 2, i + 8) == "DOCTYPE" then
if rootSeen then
return fail("DOCTYPE after the root element", i)
end
local at = i
i += 9
local raw, info = doctype()
if not raw then
return fail(info, at)
end
return "doctype", raw, info
end
return fail("bad markup declaration", i)
elseif c2 == 63 then -- <?
local target = match(s, NAME, i + 2)
if not target then
return fail("bad processing instruction", i)
end
local e = find(s, "?>", i + 2 + #target, true)
if not e then
return fail("unterminated processing instruction", i)
end
local data = sub(s, i + 2 + #target, e - 1)
if data ~= "" and not find(data, "^[ \t\n]") then
return fail("bad processing instruction", i)
end
data = match(data, "^[ \t\n]*(.-)$") :: string
local at = i
i = e + 2
if lower(target) == "xml" then
if target ~= "xml" or at ~= 1 then
return fail("misplaced XML declaration", at)
end
local decl = xmlDecl(data)
if not decl then
return fail("bad XML declaration", at)
end
return "decl", decl
end
return "pi", target, data
end
-- a start tag
local name = match(s, NAME, i + 1)
if not name then
return fail(if i + 1 > n then "truncated tag" else "bad tag name", i + 1)
end
if rootDone then
return fail("a second root element <" .. name .. ">", i)
end
local at = i
local p = i + 1 + #name
local attrs = Types.object()
local order = {}
local closed = false
local nsMap: { [string]: string }? = nil
while true do
local q = match(s, "^[ \t\n]*()", p) :: any
local cc = byte(s, q)
if cc == 62 then
p = q + 1
break
elseif cc == 47 then
if byte(s, q + 1) ~= 62 then
return fail("bad tag end", q)
end
p = q + 2
closed = true
break
elseif cc == nil then
return fail("truncated tag", q)
end
if q == p then
return fail("missing whitespace between attributes", q)
end
local an = match(s, NAME, q)
if not an then
return fail("bad attribute name", q)
end
local r = match(s, "^[ \t\n]*=[ \t\n]*()", q + #an) :: any
if not r then
return fail("attribute " .. an .. " without a value", q)
end
local qc = byte(s, r)
if qc ~= 34 and qc ~= 39 then
return fail("unquoted attribute value", r)
end
local e = find(s, if qc == 34 then '"' else "'", r + 1, true)
if not e then
return fail("unterminated attribute value", r)
end
local raw = sub(s, r + 1, e - 1)
if find(raw, "<", 1, true) then
return fail("'<' in an attribute value", r)
end
if find(raw, "[%z\1-\8\11\12\14-\31]") then
return fail("control character in an attribute value", r)
end
local v = decode(raw, r + 1, 0)
if not v then
return fail(errMsg :: string, errAt)
end
if find(raw, "[\t\n]") then
-- attribute-value normalization: literal tab / newline become spaces (references stay)
v = decode((gsub(raw, "[\t\n]", " ")), r + 1, 0) :: string
end
if attrs[an] ~= nil then
return fail("duplicate attribute " .. an, q)
end
attrs[an] = v
table.insert(order, an)
if nsOn then
if an == "xmlns" or sub(an, 1, 6) == "xmlns:" then
local m: { [string]: string } = nsMap or {}
nsMap = m
m[if an == "xmlns" then "" else sub(an, 7)] = v
end
end
p = e + 1
end
Types.object(attrs, order)
i = p
depth += 1
if depth > maxDepth then
return fail("nested deeper than " .. maxDepth, at)
end
stack[depth] = name
nsStack[depth] = nsMap :: any
local sp = attrs["xml:space"]
preserve[depth] = if sp == "preserve" then true elseif sp == "default" then false else (preserve[depth - 1] or false)
rootSeen = true
local uri: string? = nil
if nsOn then
local prefix = match(name, "^([^:]*):") or ""
uri = lookupNs(prefix)
if uri == "" then
uri = nil
end
if prefix ~= "" and uri == nil then
return fail("undeclared namespace prefix " .. prefix, at)
end
end
if closed then
stack[depth] = nil
nsStack[depth] = nil
preserve[depth] = nil
pending = { name } -- depth goes down when the queued "end" is returned
end
return "start", name, attrs, uri
end
end
end
-- lookup(nsMaps...) helper for the DOM: the namespace URI of prefix, walking an element's ancestors
function Parse.resolve(node: any, prefix: string): string?
local p = node
local key = if prefix == "" then "xmlns" else "xmlns:" .. prefix
while p do
local a = p.attrs
if a and a[key] ~= nil then
local v = a[key]
return if v == "" then nil else v
end
p = p.parent
end
if prefix == "xml" then
return "http://www.w3.org/XML/1998/namespace"
end
return nil
end
return Parse
+440
View File
@@ -0,0 +1,440 @@
--!strict
-- codecs/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.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Parse = require("@rosetta/codecs/text/Xml/Parse")
local Xml = {}
export type Node = Types.XmlNode
export type DecodeOptions = Parse.Options & {
comments: boolean?, -- keep comments as "#comment" nodes (default false)
cdata: boolean?, -- keep CDATA sections as "#cdata" nodes (default false: merged into the text)
pi: boolean?, -- keep processing instructions as "#pi" nodes (default false)
parents: boolean?, -- set node.parent (default true)
}
export type EncodeOptions = {
indent: (number | string)?, -- pretty print elements that hold only elements (default none)
declaration: boolean?, -- write <?xml version="1.0" encoding="UTF-8"?> (default: true for a "#document")
selfClose: boolean?, -- <a/> for empty elements (default true)
}
local find, gsub, sub, match = string.find, string.gsub, string.sub, string.match
local function text(src: any): (string?, Err.Err?)
if type(src) == "string" then
return src, nil
elseif type(src) == "buffer" then
return buffer.tostring(src), nil
end
return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src))
end
local function errCode(msg: string, at: number, n: number): string
if find(msg, "unterminated", 1, true) or find(msg, "truncated", 1, true) or find(msg, "unclosed", 1, true) or at >= n then
return Err.TRUNCATED
elseif find(msg, "over the limit", 1, true) or find(msg, "nested deeper", 1, true) then
return Err.LIMIT
elseif find(msg, "not supported", 1, true) or find(msg, "unsupported", 1, true) then
return Err.UNSUPPORTED
end
return Err.CORRUPT
end
-- events(src, opts?) -> iterator: event, a, b, c (see codecs/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, ""
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 :: string, ":", 1, true) and match(ch.name, ":(.*)$") == name) then
table.insert(out, ch)
end
walk(ch)
end
end
end
walk(node)
return out
end
-- text(node) -> all the character data below node, concatenated (CDATA included, comments / PIs not)
function Xml.text(node: any): string
if type(node) == "string" then
return node
end
if node.name == "#cdata" then
return node.text or ""
end
local parts = {}
local function walk(n: any)
for _, ch in n.children do
if type(ch) == "string" then
table.insert(parts, ch)
elseif ch.name == "#cdata" then
table.insert(parts, ch.text or "")
elseif string.byte(ch.name) ~= 35 then
walk(ch)
end
end
end
walk(node)
return table.concat(parts)
end
-- prefix(name) / localName(name): the parts of a qualified name ("svg:rect" -> "svg", "rect"; "rect" -> "", "rect")
function Xml.prefix(name: string): string
return match(name, "^([^:]*):") or ""
end
function Xml.localName(name: string): string
return match(name, ":(.*)$") or name
end
-- namespace(node, prefix?) -> the URI bound to prefix (default: the node's own prefix) at node, through its
-- ancestors' xmlns attributes (needs parent links)
function Xml.namespace(node: Node, prefix: string?): string?
return Parse.resolve(node, prefix or Xml.prefix(node.name))
end
-- clark(node, attrName?) -> "{uri}local" (ElementTree's notation) for the element, or for one of its attributes
-- (unprefixed attributes have no namespace)
function Xml.clark(node: Node, attrName: string?): string
local name = attrName or node.name
local prefix = Xml.prefix(name)
if attrName and prefix == "" then
return name
end
local uri = Parse.resolve(node, prefix)
if uri then
return "{" .. uri .. "}" .. Xml.localName(name)
end
return name
end
-- ------------------------------------------------------------------------------------------------ encode
local TEXT_ESC = { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ["\r"] = "&#13;" }
local ATTR_ESC = { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;", ["\t"] = "&#9;", ["\n"] = "&#10;", ["\r"] = "&#13;" }
-- escape(s) / escapeAttr(s): text / attribute-value escaping
function Xml.escape(s: string): string
return (gsub(s, "[&<>\r]", TEXT_ESC))
end
function Xml.escapeAttr(s: string): string
return (gsub(s, '[&<>"\t\n\r]', ATTR_ESC))
end
local function badName(name: any): boolean
return type(name) ~= "string" or not match(name, "^[%a_:\128-\255][%w_:%.%-\128-\255]*$")
end
-- encode(node, opts?) -> string | nil, Err. node: a "#document" or any node (an element, a comment, ...)
function Xml.encode(node: Node, opts: EncodeOptions?): (string?, Err.Err?)
local o: EncodeOptions = opts or {}
local ind: string? = nil
if type(o.indent) == "number" then
ind = if o.indent > 0 then string.rep(" ", o.indent) else nil
elseif type(o.indent) == "string" then
ind = o.indent
end
local selfClose = o.selfClose ~= false
local out: { string } = {}
local err: string? = nil
local seen: { [any]: boolean } = {}
local write: (n: any, depth: number) -> ()
function write(n: any, depth: number)
if err then
return
end
if type(n) == "string" then
table.insert(out, Xml.escape(n))
return
end
if type(n) ~= "table" or type(n.name) ~= "string" then
err = "a child is not a node or a string"
return
end
if seen[n] then
err = "a node appears twice (a cycle?)"
return
end
seen[n] = true
local name = n.name
if name == "#comment" then
local t = n.text or ""
if find(t, "--", 1, true) or sub(t, -1) == "-" then
err = "comment text contains '--'"
return
end
table.insert(out, "<!--" .. t .. "-->")
elseif name == "#cdata" then
table.insert(out, "<![CDATA[" .. gsub(n.text or "", "]]>", "]]]]><![CDATA[>") .. "]]>")
elseif name == "#pi" then
if badName(n.target) or find(n.text or "", "?>", 1, true) then
err = "bad processing instruction"
return
end
table.insert(out, "<?" .. n.target .. (if n.text and n.text ~= "" then " " .. n.text else "") .. "?>")
elseif name == "#doctype" then
table.insert(out, "<!DOCTYPE" .. (n.text or "") .. ">")
elseif name == "#document" then
for i, ch in n.children do
if i > 1 and ind then
table.insert(out, "\n")
end
write(ch, 0)
end
else
if badName(name) then
err = "bad element name " .. tostring(name)
return
end
table.insert(out, "<" .. name)
local attrs = n.attrs or {}
for _, k in Types.keys(attrs) do
local v = attrs[k]
if badName(k) then
err = "bad attribute name " .. tostring(k)
return
end
if type(v) == "number" or type(v) == "boolean" then
v = tostring(v)
elseif type(v) ~= "string" then
err = "attribute " .. k .. " is not a string"
return
end
table.insert(out, " " .. k .. '="' .. Xml.escapeAttr(v) .. '"')
end
local ch = n.children or {}
if #ch == 0 then
table.insert(out, if selfClose then "/>" else "></" .. name .. ">")
return
end
table.insert(out, ">")
local pretty = ind ~= nil
if pretty then
for _, c in ch do
if type(c) == "string" or c.name == "#cdata" then
pretty = false
break
end
end
end
for _, c in ch do
if pretty then
table.insert(out, "\n" .. string.rep(ind :: string, depth + 1))
end
write(c, depth + 1)
end
if pretty then
table.insert(out, "\n" .. string.rep(ind :: string, depth))
end
table.insert(out, "</" .. name .. ">")
end
end
local decl = o.declaration
if decl == nil then
decl = node.name == "#document"
end
if decl then
local d: any = node.declaration or {}
table.insert(out, '<?xml version="' .. (d.version or "1.0") .. '" encoding="UTF-8"' .. (if d.standalone then ' standalone="' .. d.standalone .. '"' else "") .. "?>")
table.insert(out, "\n")
end
if node.name == "#document" and node.doctype then
local dt: any = node.doctype
local raw = dt.raw
if raw == nil then
raw = " " .. (dt.name or (if node.root then node.root.name else "root"))
if dt.publicId then
raw ..= ' PUBLIC "' .. dt.publicId .. '" "' .. (dt.systemId or "") .. '"'
elseif dt.systemId then
raw ..= ' SYSTEM "' .. dt.systemId .. '"'
end
end
table.insert(out, "<!DOCTYPE" .. raw .. ">\n")
end
write(node, 0)
if err then
return nil, Err.new(Err.ARG, err)
end
if ind and node.name == "#document" then
table.insert(out, "\n")
end
return table.concat(out), nil
end
return Xml