diff --git a/docs/FORMATS.md b/docs/FORMATS.md index fa63e2f..e0ef163 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -17,6 +17,15 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` | | archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` | | archive | zst | .zst .tzst | yes | - | stream: true | `tests/archive/zst.luau` | +| data | cbor | .cbor | yes | yes | binary: true, ordered: true, tags: true | `tests/data/cbor.luau` | +| data | csv | .csv .tsv | yes | yes | header: true | `tests/data/csv.luau` | +| data | ini | .ini .cfg .conf .inf .desktop | yes | yes | ordered: true | `tests/data/ini.luau` | +| data | json | .json .jsonl .ndjson .geojson | yes | yes | ordered: true, streaming: true | `tests/data/json.luau` | +| data | msgpack | .msgpack .mpk | yes | yes | binary: true, ordered: true | `tests/data/msgpack.luau` | +| data | plist | .plist | yes | yes | binary: "read", ordered: true | `tests/data/plist.luau` | +| data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` | +| data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` | +| data | yaml | .yaml .yml | yes | yes | ordered: true, multiDocument: true, anchors: true | `tests/data/yaml.luau` | Codecs (layer 1, shared by formats; not loadable on their own): @@ -24,7 +33,9 @@ Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec - codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. +- codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): - codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine - codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed +- codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... - codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index c0070ac..94aece3 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -158,6 +158,114 @@ local list: { Entry } = { return require("@formats/archive/zst") end, }, + { + name = "cbor", + category = "data", + path = "data/cbor", + extensions = { "cbor" }, + mime = { "application/cbor", "application/cbor-seq" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true, tags = true }, + load = function() + return require("@formats/data/cbor") + end, + }, + { + name = "csv", + category = "data", + path = "data/csv", + extensions = { "csv", "tsv" }, + mime = { "text/csv", "text/tab-separated-values" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + caps = { decode = true, encode = true, header = true }, + load = function() + return require("@formats/data/csv") + end, + }, + { + name = "ini", + category = "data", + path = "data/ini", + extensions = { "ini", "cfg", "conf", "inf", "desktop" }, + mime = { "text/plain" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + caps = { decode = true, encode = true, ordered = true }, + load = function() + return require("@formats/data/ini") + end, + }, + { + name = "json", + category = "data", + path = "data/json", + extensions = { "json", "jsonl", "ndjson", "geojson" }, + mime = { "application/json", "application/x-ndjson" }, + deps = { "core/Err", "core/Bytes", "codecs/Json" }, + caps = { decode = true, encode = true, ordered = true, streaming = true }, + load = function() + return require("@formats/data/json") + end, + }, + { + name = "msgpack", + category = "data", + path = "data/msgpack", + extensions = { "msgpack", "mpk" }, + mime = { "application/msgpack", "application/x-msgpack" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true }, + load = function() + return require("@formats/data/msgpack") + end, + }, + { + name = "plist", + category = "data", + path = "data/plist", + extensions = { "plist" }, + mime = { "application/x-plist", "application/x-bplist" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Json" }, + caps = { decode = true, encode = true, binary = "read", ordered = true }, + load = function() + return require("@formats/data/plist") + end, + }, + { + name = "toml", + category = "data", + path = "data/toml", + extensions = { "toml" }, + mime = { "application/toml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + caps = { decode = true, encode = true, ordered = true, dates = true }, + load = function() + return require("@formats/data/toml") + end, + }, + { + name = "xml", + category = "data", + path = "data/xml", + extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, + mime = { "application/xml", "text/xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml" }, + caps = { decode = true, encode = true, namespaces = true, streaming = true }, + load = function() + return require("@formats/data/xml") + end, + }, + { + name = "yaml", + category = "data", + path = "data/yaml", + extensions = { "yaml", "yml" }, + mime = { "application/yaml", "application/x-yaml", "text/yaml" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true }, + load = function() + return require("@formats/data/yaml") + end, + }, } return list diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 9f37bd1..1d8db5c 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -343,12 +343,289 @@ export type Archive = { -- ------------------------------------------------------------------------------------------------ Data -- data formats decode to plain Luau values; JSON null / YAML ~ / CBOR null is this sentinel (nil cannot sit in a --- table). XML decodes to XmlNode trees. +-- table). XML decodes to XmlNode trees. Byte strings (msgpack bin, CBOR bytes, plist data) are buffers. local nullMeta = { __tostring = function() return "null" end } Types.null = table.freeze(setmetatable({}, nullMeta)) -export type XmlNode = { name: string, attrs: { [string]: string }, children: { XmlNode | string }, parent: XmlNode? } + +-- Objects (maps) whose key order matters, and empty objects (which would otherwise read back as empty arrays), carry +-- an "object" metatable with their key order. Decoders mark empty objects always and every object when asked +-- (opts.ordered); encoders write an object's keys in that order (keys added later, or plain tables: sorted). +-- local o = Types.object() o.b = 1; o.a = 2 -- or Types.object({ a = 2, b = 1 }, { "b", "a" }) +-- Types.set(o, "c", 3) -- assigns and appends "c" to the order +-- for _, k in Types.keys(o) do ... end +local OBJECT = { __object = true } +local objectMeta: { [any]: { any } } = setmetatable({}, { __mode = "k" }) :: any -- object -> its key order +-- object(t?, keys?) -> t marked as an object, keys = its key order (default: none recorded; Types.set appends) +function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any } + local o = t or {} + if getmetatable(o) == nil then + setmetatable(o, OBJECT) + end + objectMeta[o] = keys or {} + return o +end +-- isObject(v) -> true for tables made by Types.object +function Types.isObject(v: any): boolean + return type(v) == "table" and objectMeta[v] ~= nil +end +-- set(o, k, v): o[k] = v, appending k to o's key order when new (o must be an object; a plain table just assigns) +function Types.set(o: { [any]: any }, k: any, v: any) + local order = objectMeta[o] + if order and o[k] == nil and v ~= nil then + table.insert(order, k) + end + o[k] = v +end +local function keyLess(a: any, b: any): boolean + local ta, tb = type(a), type(b) + if ta ~= tb then + return ta < tb + end + if ta == "number" or ta == "string" then + return a < b + end + return tostring(a) < tostring(b) +end +-- keys(t) -> the keys in order: an object's recorded order (keys since removed are skipped), then any other keys +-- sorted (numbers before strings) +function Types.keys(t: { [any]: any }): { any } + local order = objectMeta[t] + local out, seen = {}, {} + if order then + for _, k in order do + if t[k] ~= nil and not seen[k] then + seen[k] = true + table.insert(out, k) + end + end + end + local rest = {} + for k in next, t do + if not seen[k] then + table.insert(rest, k) + end + end + if #rest > 0 then + table.sort(rest, keyLess) + table.move(rest, 1, #rest, #out + 1, out) + end + return out +end + +-- Dates and times (TOML datetimes, plist , CBOR tags 0 / 1, msgpack timestamps). Fields present depend on the +-- kind: "datetime" (with offset: an instant), "datetime-local", "date-local", "time-local". offset is in minutes +-- east of UTC (nil = local time). tostring gives RFC 3339 ("1979-05-27T07:32:00.5-07:00", "07:32:00", ...). +export type Date = { + kind: "datetime" | "datetime-local" | "date-local" | "time-local", + year: number?, + month: number?, + day: number?, + hour: number?, + minute: number?, + second: number?, + nanosecond: number?, -- 0 .. 999999999 + offset: number?, -- minutes east of UTC +} +local DateMeta = {} +local function p2(n: number): string + return string.format("%02d", n) +end +local function fmtDate(d: any): string + local s = "" + if d.year then + s = string.format("%04d-%02d-%02d", d.year, d.month or 1, d.day or 1) + end + if d.hour then + if s ~= "" then + s ..= "T" + end + s ..= p2(d.hour) .. ":" .. p2(d.minute or 0) .. ":" .. p2(d.second or 0) + local ns = d.nanosecond or 0 + if ns > 0 then + local f = string.format("%09d", ns) + s ..= "." .. (string.gsub(f, "0+$", "")) + end + if d.offset then + if d.offset == 0 then + s ..= "Z" + else + local o = math.abs(d.offset) + s ..= (if d.offset < 0 then "-" else "+") .. p2(o // 60) .. ":" .. p2(o % 60) + end + end + end + return s +end +DateMeta.__tostring = fmtDate +DateMeta.__eq = function(a: any, b: any): boolean + return fmtDate(a) == fmtDate(b) and a.kind == b.kind +end +local DateLib = {} +-- days since 1970-01-01 of a civil date (proleptic Gregorian; Howard Hinnant's algorithm) +local function daysFromCivil(y: number, m: number, d: number): number + y = if m <= 2 then y - 1 else y + local era = (if y >= 0 then y else y - 399) // 400 + local yoe = y - era * 400 + local mp = (m + 9) % 12 + local doy = (153 * mp + 2) // 5 + d - 1 + local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy + return era * 146097 + doe - 719468 +end +local function civilFromDays(z: number): (number, number, number) + z += 719468 + local era = (if z >= 0 then z else z - 146096) // 146097 + local doe = z - era * 146097 + local yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365 + local y = yoe + era * 400 + local doy = doe - (365 * yoe + yoe // 4 - yoe // 100) + local mp = (5 * doy + 2) // 153 + local d = doy - (153 * mp + 2) // 5 + 1 + local m = if mp < 10 then mp + 3 else mp - 9 + return (if m <= 2 then y + 1 else y), m, d +end +local MDAYS = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } +-- new(fields) -> Date (kind inferred from the fields present when not given) +function DateLib.new(f: { [string]: any }): Date + local d: any = {} + for k, v in f do + d[k] = v + end + if d.kind == nil then + d.kind = if d.year and d.hour then (if d.offset then "datetime" else "datetime-local") + elseif d.year then "date-local" + else "time-local" + end + return setmetatable(d, DateMeta) :: any +end +-- is(v) -> true for Dates +function DateLib.is(v: any): boolean + return type(v) == "table" and getmetatable(v) == DateMeta +end +-- valid(d) -> true when the fields are in range (month 1..12, the day exists in that month, hour < 24, ...) +function DateLib.valid(d: Date): boolean + if d.year then + local y, m, dd = d.year, d.month or 0, d.day or 0 + if y < 0 or y > 9999 or m < 1 or m > 12 or dd < 1 or dd > MDAYS[m] then + return false + end + if m == 2 and dd == 29 and not (y % 4 == 0 and (y % 100 ~= 0 or y % 400 == 0)) then + return false + end + end + if d.hour then + if d.hour > 23 or (d.minute or 0) > 59 or (d.second or 0) > 60 then + return false + end + end + if d.offset and math.abs(d.offset) >= 24 * 60 then + return false + end + return true +end +-- parse(s) -> Date | nil: RFC 3339 / ISO 8601 date-times and their TOML partial forms ("1979-05-27", +-- "07:32:00.999", "1979-05-27 07:32:00Z", lower-case t / z accepted); out-of-range fields return nil +function DateLib.parse(s: string): Date? + local d: any = {} + local rest = s + local y, mo, dd, r1 = string.match(rest, "^(%d%d%d%d)%-(%d%d)%-(%d%d)(.*)$") + if y then + d.year, d.month, d.day = tonumber(y), tonumber(mo), tonumber(dd) + rest = r1 + if rest == "" then + return if DateLib.valid(d) then DateLib.new(d) else nil + end + local sep = string.sub(rest, 1, 1) + if sep ~= "T" and sep ~= "t" and sep ~= " " then + return nil + end + rest = string.sub(rest, 2) + end + local h, mi, r2 = string.match(rest, "^(%d%d):(%d%d)(.*)$") + if not h then + return nil + end + d.hour, d.minute = tonumber(h), tonumber(mi) + rest = r2 + local sec, r3 = string.match(rest, "^:(%d%d)(.*)$") + if not sec then + return nil + end + d.second = tonumber(sec) + rest = r3 + local frac, r4 = string.match(rest, "^%.(%d+)(.*)$") + if frac then + d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9)) + rest = r4 + else + d.nanosecond = 0 + end + if rest ~= "" then + if not d.year then + return nil + end + if rest == "Z" or rest == "z" then + d.offset = 0 + else + local sign, oh, om = string.match(rest, "^([%+%-])(%d%d):(%d%d)$") + if not sign then + return nil + end + local oh_n, om_n = tonumber(oh) :: number, tonumber(om) :: number + if oh_n > 23 or om_n > 59 then + return nil + end + d.offset = (oh_n * 60 + om_n) * (if sign == "-" then -1 else 1) + end + end + return if DateLib.valid(d) then DateLib.new(d) else nil +end +-- toUnix(d) -> seconds since 1970-01-01T00:00:00Z (fractional; local times are taken as UTC) +function DateLib.toUnix(d: Date): number + local days = if d.year then daysFromCivil(d.year, d.month or 1, d.day or 1) else 0 + local s = days * 86400 + (d.hour or 0) * 3600 + (d.minute or 0) * 60 + (d.second or 0) - (d.offset or 0) * 60 + return s + (d.nanosecond or 0) / 1e9 +end +-- fromUnix(seconds, offset?) -> a "datetime" Date (offset in minutes, default 0 = UTC) +function DateLib.fromUnix(t: number, offset: number?): Date + local off = offset or 0 + local whole = math.floor(t) + local ns = math.floor((t - whole) * 1e9 + 0.5) + if ns >= 1e9 then + whole += 1 + ns -= 1e9 + end + local lt = whole + off * 60 + local days = lt // 86400 + local secs = lt - days * 86400 + local y, m, dd = civilFromDays(days) + return DateLib.new({ + kind = "datetime", + year = y, + month = m, + day = dd, + hour = secs // 3600, + minute = (secs // 60) % 60, + second = secs % 60, + nanosecond = ns, + offset = off, + }) +end +Types.Date = table.freeze(DateLib) + +-- XML: an element, or (name starting with "#") a "#document" / "#comment" / "#cdata" / "#pi" / "#doctype" node with +-- its content in text. attrs is a Types.object (attribute order kept). Text children are plain strings. +export type XmlNode = { + name: string, + attrs: { [string]: string }, + children: { XmlNode | string }, + parent: XmlNode?, + text: string?, -- "#comment" / "#cdata" / "#pi" (the data after the target) / "#doctype" content + target: string?, -- "#pi": the target + ns: string?, -- the namespace URI (opts.namespaces) + [string]: any, +} -- ------------------------------------------------------------------------------------------------ Vector export type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any } diff --git a/src/Formats/codecs/Json/Decode.luau b/src/Formats/codecs/Json/Decode.luau new file mode 100644 index 0000000..46b9fd2 --- /dev/null +++ b/src/Formats/codecs/Json/Decode.luau @@ -0,0 +1,433 @@ +--!strict +--!native +-- codecs/Json/Decode: the RFC 8259 parser behind codecs/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 Types = require("@formats/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 function utf8char(c: number): string + if c < 0x80 then + return char(c) + elseif c < 0x800 then + return char(0xC0 + c // 64, 0x80 + c % 64) + elseif c < 0x10000 then + return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) + end + return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) +end +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 diff --git a/src/Formats/codecs/Json/Encode.luau b/src/Formats/codecs/Json/Encode.luau new file mode 100644 index 0000000..78d0ac5 --- /dev/null +++ b/src/Formats/codecs/Json/Encode.luau @@ -0,0 +1,307 @@ +--!strict +--!native +-- codecs/Json/Encode: the serializer behind codecs/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("@formats/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 diff --git a/src/Formats/codecs/Json/init.luau b/src/Formats/codecs/Json/init.luau new file mode 100644 index 0000000..f9b6204 --- /dev/null +++ b/src/Formats/codecs/Json/init.luau @@ -0,0 +1,294 @@ +--!strict +-- codecs/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("@formats/codecs/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("@formats/core/Err") +local Types = require("@formats/Types") +local Decode = require("@formats/codecs/Json/Decode") +local Encode = require("@formats/codecs/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 diff --git a/src/Formats/codecs/Xml/Parse.luau b/src/Formats/codecs/Xml/Parse.luau new file mode 100644 index 0000000..4a04ff3 --- /dev/null +++ b/src/Formats/codecs/Xml/Parse.luau @@ -0,0 +1,771 @@ +--!strict +--!native +-- codecs/Xml/Parse: the XML 1.0 pull parser behind codecs/Xml. Input decoding (UTF-8, UTF-16 LE / BE by BOM or +-- by the first bytes, ISO-8859-1 / US-ASCII / Windows-1252 by the declaration), line-ending normalization, the +-- well-formedness rules that matter (one root, matched tags, unique attributes, quoted values, no '<' in values, +-- legal names, character references in range, no "--" in comments, no "]]>" in text), the five predefined entities, +-- character references and internal general entities from the DOCTYPE (with an expansion limit). Not supported: +-- external entities / DTDs (references to them are errors), entity values containing markup (taken as text), +-- validation. Never throws: errors are events. +local Types = require("@formats/Types") + +local Parse = {} + +local byte, sub, find, match, char, gsub, lower = string.byte, string.sub, string.find, string.match, string.char, string.gsub, string.lower + +export type Options = { + whitespace: boolean?, -- keep whitespace-only text (default false: dropped, except inside xml:space="preserve") + namespaces: boolean?, -- resolve namespace prefixes: "start" events carry the element's URI (default false) + entities: { [string]: string }?, -- extra general entities (name -> replacement text) + maxExpansion: number?, -- total characters produced by entity expansion (default 1e7; the billion laughs guard) + maxDepth: number?, -- element nesting limit (default 10000) +} + +local NAME = "^[%a_:\128-\255][%w_:%.%-\128-\255]*" +local PREDEF: { [string]: string } = { lt = "<", gt = ">", amp = "&", quot = '"', apos = "'" } + +local function utf8char(c: number): string + if c < 0x80 then + return char(c) + elseif c < 0x800 then + return char(0xC0 + c // 64, 0x80 + c % 64) + elseif c < 0x10000 then + return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) + end + return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) +end +Parse.utf8char = utf8char + +local CP1252: { [number]: number } = { + [0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020, + [0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152, + [0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022, + [0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A, + [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178, +} + +local function utf16(s: string, start: number, le: boolean): (string?, string?) + local out = table.create(#s // 2) + local n = 0 + local i = start + local len = #s + while i + 1 <= len do + local a, b = byte(s, i, i + 1) + local u = if le then a + b * 256 else a * 256 + b + i += 2 + if u >= 0xD800 and u <= 0xDBFF then + if i + 1 > len then + return nil, "truncated UTF-16 surrogate pair" + end + local c, d = byte(s, i, i + 1) + local lo = if le then c + d * 256 else c * 256 + d + if lo < 0xDC00 or lo > 0xDFFF then + return nil, "bad UTF-16 surrogate pair" + end + i += 2 + u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00) + elseif u >= 0xDC00 and u <= 0xDFFF then + return nil, "bad UTF-16 surrogate pair" + end + n += 1 + out[n] = utf8char(u) + end + if i <= len then + return nil, "odd number of bytes in UTF-16 text" + end + return table.concat(out), nil +end + +-- toUtf8(s) -> UTF-8 text (BOM removed), the encoding name | nil, message +function Parse.toUtf8(s: string): (string?, string) + local b1, b2, b3 = byte(s, 1, 3) + if b1 == 0xEF and b2 == 0xBB and b3 == 0xBF then + return sub(s, 4), "utf-8" + elseif b1 == 0xFF and b2 == 0xFE then + local t, e = utf16(s, 3, true) + return t, e or "utf-16le" + elseif b1 == 0xFE and b2 == 0xFF then + local t, e = utf16(s, 3, false) + return t, e or "utf-16be" + elseif b1 == 0x3C and b2 == 0 then + local t, e = utf16(s, 1, true) + return t, e or "utf-16le" + elseif b1 == 0 and b2 == 0x3C then + local t, e = utf16(s, 1, false) + return t, e or "utf-16be" + end + local decl = match(s, "^<%?xml[^>]-%?>") + local enc = if decl then match(decl, "encoding%s*=%s*[\"']([%w%._%-]+)[\"']") else nil + if enc then + local e = lower(enc) + if e == "utf-8" or e == "utf8" or e == "us-ascii" or e == "ascii" then + if find(s, "[\128-\255]") and not utf8.len(s) then + return nil, "invalid UTF-8" + end + return s, e + elseif e == "iso-8859-1" or e == "latin1" or e == "latin-1" or e == "iso8859-1" or e == "windows-1252" or e == "cp1252" then + local w = e == "windows-1252" or e == "cp1252" + return (gsub(s, "[\128-\255]", function(c: string): string + local v = byte(c) + return utf8char(if w then CP1252[v] or v else v) + end)), e + elseif e == "utf-16" or e == "utf-16le" or e == "utf-16be" then + return s, "utf-8" -- declared UTF-16 but read as 8-bit text: trust the bytes + end + return nil, "unsupported encoding " .. enc + end + if find(s, "[\128-\255]") and not utf8.len(s) then + return nil, "invalid UTF-8" + end + return s, "utf-8" +end + +-- the pseudo-attributes, strictly: version, then encoding?, then standalone?, each after whitespace +local function xmlDecl(data: string): { [string]: string }? + local p = 1 + local out: { [string]: string } = {} + for k, key in { "version", "encoding", "standalone" } do + local ws = match(data, "^[ \t\n]*()", p) :: any + local q, v, e = match(data, "^" .. key .. "[ \t\n]*=[ \t\n]*([\"'])(.-)%1()", ws) + if q then + if k > 1 and ws == p then + return nil -- no whitespace before + end + if (key == "version" and not match(v, "^1%.%d+$")) + or (key == "encoding" and not match(v, "^%a[%w%._%-]*$")) + or (key == "standalone" and v ~= "yes" and v ~= "no") + then + return nil + end + out[key] = v + p = e + elseif key == "version" then + return nil + end + end + if match(data, "^[ \t\n]*()", p) ~= #data + 1 then + return nil + end + return out +end + +-- the events iterator: next() -> event, a, b, c +-- "decl", { version, encoding, standalone } the declaration +-- "doctype", raw, info raw = the text between ""; info = { name, +-- publicId, systemId, entities } +-- "start", name, attrs (Types.object), ns ns: the element's namespace URI (opts.namespaces) or nil +-- "end", name +-- "text", s character data, entities decoded (whitespace-only dropped +-- unless opts.whitespace) +-- "cdata", s "comment", s "pi", target, data +-- "error", message, offset then the iterator ends +-- nil at the end of the document. +function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) + local o: Options = opts or {} + local keepWs = o.whitespace == true + local nsOn = o.namespaces == true + local maxExp = o.maxExpansion or 1e7 + local maxDepth = o.maxDepth or 10000 + local entities: { [string]: string } = {} + if o.entities then + for k, v in o.entities do + entities[k] = v + end + end + local external: { [string]: boolean } = {} + local expanded = 0 + if find(s, "\r", 1, true) then + s = gsub(gsub(s, "\r\n", "\n"), "\r", "\n") + end + local n = #s + local i = 1 + local stack: { string } = {} + local nsStack: { { [string]: string } } = {} + local preserve: { boolean } = {} + local depth = 0 + local rootSeen = false + local rootDone = false + local dead = false + local pending: { any }? = nil -- an "end" queued after a self-closing start + local errMsg: string? = nil + local errAt = 0 + + local function fail(msg: string, at: number): (string, string, number) + dead = true + return "error", msg, at - 1 + end + + -- decode entity / character references in raw text; nil on error (errMsg set) + local decode: (raw: string, at: number, level: number) -> string? + function decode(raw: string, at: number, level: number): string? + if not find(raw, "&", 1, true) then + return raw + end + local parts = {} + local np = 0 + local p = 1 + while true do + local a = find(raw, "&", p, true) + if not a then + break + end + np += 1 + parts[np] = sub(raw, p, a - 1) + local ref, e = match(raw, "^&([^;&%s<]*);()", a) + if not ref then + errMsg, errAt = "bad reference (no ';')", at + a - 1 + return nil + end + local rep: string + if byte(ref) == 35 then -- # + local cp = if byte(ref, 2) == 120 then tonumber(match(ref, "^#x(%x+)$") or "", 16) else tonumber(match(ref, "^#(%d+)$") or "") + if not cp or cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) or cp == 0xFFFE or cp == 0xFFFF then + errMsg, errAt = "bad character reference &" .. ref .. ";", at + a - 1 + return nil + end + rep = utf8char(cp) + else + local pre = PREDEF[ref] + if pre then + rep = pre + else + local ent = entities[ref] + if not ent then + errMsg = if external[ref] then "external entity &" .. ref .. "; not supported" else "undefined entity &" .. ref .. ";" + errAt = at + a - 1 + return nil + end + if level > 40 then + errMsg, errAt = "entity references nested too deeply (recursive?)", at + a - 1 + return nil + end + local r = decode(ent, at + a - 1, level + 1) + if not r then + return nil + end + rep = r + end + end + expanded += #rep + if expanded > maxExp then + errMsg, errAt = "entity expansion over the limit", at + a - 1 + return nil + end + np += 1 + parts[np] = rep + p = e :: any + end + np += 1 + parts[np] = sub(raw, p) + return table.concat(parts) + end + + local function lookupNs(prefix: string): string? + for d = depth, 1, -1 do + local m = nsStack[d] + if m and m[prefix] ~= nil then + return m[prefix] + end + end + if prefix == "xml" then + return "http://www.w3.org/XML/1998/namespace" + end + return nil + end + + -- a quoted literal at p -> its content, the position after it | nil + local function literal(p: number): (string?, number) + local q = byte(s, p) + if q ~= 34 and q ~= 39 then + return nil, p + end + local e = find(s, if q == 34 then '"' else "'", p + 1, true) + if not e then + return nil, p + end + return sub(s, p + 1, e - 1), e + 1 + end + -- an ExternalID (SYSTEM "sys" | PUBLIC "pub" "sys") at p -> publicId, systemId, next | nil + local function externalId(p: number): (string?, string?, number?) + local kw = sub(s, p, p + 5) + if kw == "SYSTEM" then + local q = match(s, "^[ \t\n]+()", p + 6) :: any + if not q then + return nil + end + local sys, e = literal(q) + if not sys then + return nil + end + return "", sys, e + elseif kw == "PUBLIC" then + local q = match(s, "^[ \t\n]+()", p + 6) :: any + if not q then + return nil + end + local pub, e = literal(q) + if not pub or find(pub, "[^ \r\n%w%-'()+,./:=?;!*#@$_%%]") then + return nil + end + local r = match(s, "^[ \t\n]+()", e) :: any + if not r then + return nil + end + local sys, e2 = literal(r) + if not sys then + return nil + end + return pub, sys, e2 + end + return nil + end + -- check an entity value's references and expand its character references (the rest expand when used) + local function entityValue(v: string): string? + if find(v, "%", 1, true) then + return nil -- parameter-entity references are not allowed in the internal subset's markup + end + local p = 1 + local parts = {} + while true do + local a = find(v, "&", p, true) + if not a then + table.insert(parts, sub(v, p)) + break + end + table.insert(parts, sub(v, p, a - 1)) + local hex = match(v, "^&#x(%x+);", a) + local dec = match(v, "^&#(%d+);", a) + if hex or dec then + local cp = tonumber(hex or dec, if hex then 16 else 10) :: number + if cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) then + return nil + end + table.insert(parts, utf8char(cp)) + p = (find(v, ";", a, true) :: number) + 1 + else + local name = match(v, "^&([%a_:\128-\255][%w_:%.%-\128-\255]*);", a) + if not name then + return nil + end + table.insert(parts, "&" .. name .. ";") + p = a + #name + 2 + end + end + return table.concat(parts) + end + -- the DOCTYPE at i (just past " p and (sub(s, q, q + 5) == "SYSTEM" or sub(s, q, q + 5) == "PUBLIC") then + local pub, sys, e = externalId(q) + if not pub then + return nil, "bad DOCTYPE external id" + end + info.publicId = if pub ~= "" then pub else nil + info.systemId = sys + q = match(s, "^[ \t\n]*()", e) :: any + end + if byte(s, q) == 91 then -- the internal subset + q += 1 + while true do + q = match(s, "^[ \t\n]*()", q) :: any + local c = byte(s, q) + if c == 93 then + q += 1 + break + elseif c == 37 then -- %name; + local pe = match(s, "^%%[%a_:\128-\255][%w_:%.%-\128-\255]*;()", q) + if not pe then + return nil, "bad parameter-entity reference" + end + q = pe :: any + elseif sub(s, q, q + 3) == "") + elseif name == "#cdata" then + table.insert(out, "", "]]]]>") .. "]]>") + elseif name == "#pi" then + if badName(n.target) or find(n.text or "", "?>", 1, true) then + err = "bad processing instruction" + return + end + table.insert(out, "") + elseif name == "#doctype" then + table.insert(out, "") + elseif name == "#document" then + for i, ch in n.children do + if i > 1 and ind then + table.insert(out, "\n") + end + write(ch, 0) + end + else + if badName(name) then + err = "bad element name " .. tostring(name) + return + end + table.insert(out, "<" .. name) + local attrs = n.attrs or {} + for _, k in Types.keys(attrs) do + local v = attrs[k] + if badName(k) then + err = "bad attribute name " .. tostring(k) + return + end + if type(v) == "number" or type(v) == "boolean" then + v = tostring(v) + elseif type(v) ~= "string" then + err = "attribute " .. k .. " is not a string" + return + end + table.insert(out, " " .. k .. '="' .. Xml.escapeAttr(v) .. '"') + end + local ch = n.children or {} + if #ch == 0 then + table.insert(out, if selfClose then "/>" else ">") + return + end + table.insert(out, ">") + local pretty = ind ~= nil + if pretty then + for _, c in ch do + if type(c) == "string" or c.name == "#cdata" then + pretty = false + break + end + end + end + for _, c in ch do + if pretty then + table.insert(out, "\n" .. string.rep(ind :: string, depth + 1)) + end + write(c, depth + 1) + end + if pretty then + table.insert(out, "\n" .. string.rep(ind :: string, depth)) + end + table.insert(out, "") + end + end + + local decl = o.declaration + if decl == nil then + decl = node.name == "#document" + end + if decl then + local d: any = node.declaration or {} + table.insert(out, '") + table.insert(out, "\n") + end + if node.name == "#document" and node.doctype then + local dt: any = node.doctype + local raw = dt.raw + if raw == nil then + raw = " " .. (dt.name or (if node.root then node.root.name else "root")) + if dt.publicId then + raw ..= ' PUBLIC "' .. dt.publicId .. '" "' .. (dt.systemId or "") .. '"' + elseif dt.systemId then + raw ..= ' SYSTEM "' .. dt.systemId .. '"' + end + end + table.insert(out, "\n") + end + write(node, 0) + if err then + return nil, Err.new(Err.ARG, err) + end + if ind and node.name == "#document" then + table.insert(out, "\n") + end + return table.concat(out), nil +end + +return Xml diff --git a/src/Formats/data/cbor/Codec.luau b/src/Formats/data/cbor/Codec.luau new file mode 100644 index 0000000..f588c59 --- /dev/null +++ b/src/Formats/data/cbor/Codec.luau @@ -0,0 +1,607 @@ +--!strict +--!native +-- data/cbor/Codec: the CBOR (RFC 8949) decoder and encoder behind data/cbor. Never throws: errors return nil, +-- message, offset. +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") + +local Codec = {} + +local TWO32 = 4294967296 + +-- ------------------------------------------------------------------------------------------------ value types +local TaggedMeta = { __tostring = function(t: any): string + return "cbor.tag(" .. t.tag .. ")" +end } +local SimpleMeta = { __tostring = function(s: any): string + return "cbor.simple(" .. s.value .. ")" +end } +-- tagged(tag, value) -> { tag, value }: a tag this library does not interpret +function Codec.tagged(tag: number, value: any): { tag: number, value: any } + return setmetatable({ tag = tag, value = value }, TaggedMeta) :: any +end +function Codec.isTagged(v: any): boolean + return type(v) == "table" and getmetatable(v) == TaggedMeta +end +-- simple(n) -> an unassigned simple value (0..19, 32..255) +function Codec.simple(n: number): { value: number } + return setmetatable({ value = n }, SimpleMeta) :: any +end +function Codec.isSimple(v: any): boolean + return type(v) == "table" and getmetatable(v) == SimpleMeta +end +Codec.undefined = table.freeze(setmetatable({}, { __tostring = function() + return "undefined" +end })) + +-- decimal text of a big-endian unsigned byte string (any length) +local function bigText(s: string): string + local limbs = {} -- base 1e7, little-endian + for i = 1, #s do + local carry = string.byte(s, i) + for k = 1, #limbs do + local v = limbs[k] * 256 + carry + limbs[k] = v % 10000000 + carry = v // 10000000 + end + while carry > 0 do + table.insert(limbs, carry % 10000000) + carry //= 10000000 + end + end + if #limbs == 0 then + return "0" + end + local out = { string.format("%d", limbs[#limbs]) } + for k = #limbs - 1, 1, -1 do + table.insert(out, string.format("%07d", limbs[k])) + end + return table.concat(out) +end +-- text + 1 for a decimal string +local function incText(s: string): string + local digits = table.create(#s) + for i = 1, #s do + digits[i] = string.byte(s, i) - 48 + end + local i = #digits + while i >= 1 do + if digits[i] < 9 then + digits[i] += 1 + break + end + digits[i] = 0 + i -= 1 + end + local out = table.create(#digits) + for k, d in digits do + out[k] = string.char(48 + d) + end + return (if i == 0 then "1" else "") .. table.concat(out) +end + +export type DecodeOptions = { + bigInts: ("number" | "string")?, -- integers / bignums past 2^53: "string" keeps exact decimal text + null: any?, -- the value for null (default Types.null) + undefined: any?, -- the value for undefined (default Codec.undefined) + maxDepth: number?, -- default 512 + dates: boolean?, -- tags 0 / 1 as Types.Date (default true) +} + +type St = { r: Bytes.Reader, big: boolean, null: any, undef: any, maxDepth: number, dates: boolean } + +local BREAK = {} -- the 0xFF stop code, inside indefinite items + +-- the argument of a head: number (or nil, "text" for u64 past 2^53 when big), nil means indefinite (ai 31) +local function arg(st: St, ai: number): (number?, string?, string?) + local r = st.r + if ai < 24 then + return ai, nil, nil + elseif ai == 24 then + return r:u8(), nil, nil + elseif ai == 25 then + return r:u16be(), nil, nil + elseif ai == 26 then + return r:u32be(), nil, nil + elseif ai == 27 then + local hi, lo = r:u32be(), r:u32be() + if st.big and hi >= 0x200000 then + return hi * TWO32 + lo, bigText(string.char(hi // 16777216, (hi // 65536) % 256, (hi // 256) % 256, hi % 256, lo // 16777216, (lo // 65536) % 256, (lo // 256) % 256, lo % 256)), nil + end + return hi * TWO32 + lo, nil, nil + elseif ai == 31 then + return nil, nil, nil + end + return nil, nil, "reserved additional information " .. ai +end + +local item: (st: St, depth: number) -> (any, string?) + +local function chunks(st: St, major: number, depth: number): (string?, string?) + local parts = {} + while true do + local r = st.r + local ib = r:u8() + if r.err then + return nil, "truncated" + end + if ib == 0xFF then + return table.concat(parts), nil + end + if ib // 32 ~= major then + return nil, "bad chunk in an indefinite string" + end + local n, _, e = arg(st, ib % 32) + if e or n == nil then + return nil, e or "nested indefinite string" + end + if r.err or not r:need(n) then + return nil, "truncated string" + end + table.insert(parts, r:string(n)) + end +end + +local function half(h: number): number + local s = if h >= 32768 then -1 else 1 + local e = (h // 1024) % 32 + local m = h % 1024 + if e == 0 then + return s * m * 2 ^ -24 + elseif e == 31 then + return if m == 0 then s * math.huge else 0 / 0 + end + return s * (1 + m / 1024) * 2 ^ (e - 15) +end + +local function tag(st: St, t: number, v: any): (any, string?) + if t == 0 and st.dates then + if type(v) ~= "string" then + return nil, "tag 0 needs a text string" + end + local d = Types.Date.parse(v) + if not d or not d.offset then + return nil, "tag 0: bad date-time " .. v + end + return d, nil + elseif t == 1 and st.dates then + if type(v) ~= "number" or v ~= v or v == math.huge or v == -math.huge then + return nil, "tag 1 needs a number" + end + return Types.Date.fromUnix(v), nil + elseif t == 2 or t == 3 then + if type(v) ~= "string" then + return nil, "bignum tag needs a byte string" + end + local s = v :: string + local n = 0 + for i = 1, #s do + n = n * 256 + string.byte(s, i) + end + if n >= 9007199254740992 then + -- exact text; as a number, read back from that text (correctly rounded, unlike the running sum) + local text = bigText(s) + if t == 3 then + text = incText(text) + end + if st.big then + return if t == 2 then text else "-" .. text, nil + end + local x = tonumber(text) :: number + return if t == 2 then x else -x, nil + end + return if t == 2 then n else -1 - n, nil + elseif t == 55799 then + return v, nil + end + return Codec.tagged(t, v), nil +end + +function item(st: St, depth: number): (any, string?) + if depth > st.maxDepth then + return nil, "nested deeper than " .. st.maxDepth + end + local r = st.r + local ib = r:u8() + if r.err then + return nil, "truncated" + end + local major, ai = ib // 32, ib % 32 + if major == 7 then + if ai < 20 then + return Codec.simple(ai), nil + elseif ai == 20 then + return false, nil + elseif ai == 21 then + return true, nil + elseif ai == 22 then + return st.null, nil + elseif ai == 23 then + return st.undef, nil + elseif ai == 24 then + local n = r:u8() + if r.err then + return nil, "truncated" + end + if n < 32 then + return nil, "bad two-byte simple value" + end + return Codec.simple(n), nil + elseif ai == 25 then + local h = r:u16be() + return if r.err then nil else half(h), if r.err then "truncated" else nil + elseif ai == 26 then + local f = r:f32be() + return if r.err then nil else f, if r.err then "truncated" else nil + elseif ai == 27 then + local f = r:f64be() + return if r.err then nil else f, if r.err then "truncated" else nil + elseif ai == 31 then + return BREAK, nil + end + return nil, "reserved simple value" + end + local n, text, e = arg(st, ai) + if e then + return nil, e + end + if r.err then + return nil, "truncated" + end + if major == 0 then + if n == nil then + return nil, "indefinite integer" + end + return text or n, nil + elseif major == 1 then + if n == nil then + return nil, "indefinite integer" + end + if text then + return "-" .. incText(text), nil + end + return -1 - n, nil + elseif major == 2 or major == 3 then + local s: string + if n == nil then + local c, ce = chunks(st, major, depth) + if not c then + return nil, ce + end + s = c + else + if not r:need(n) then + return nil, "truncated string" + end + s = r:string(n) + end + if major == 2 then + return buffer.fromstring(s), nil + end + if string.find(s, "[\128-\255]") and not utf8.len(s) then + return nil, "invalid UTF-8 in a text string" + end + return s, nil + elseif major == 4 then + if n == nil then + local t = {} + while true do + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return t, nil + end + table.insert(t, v) + end + end + if n > r:remaining() then + return nil, "array count past the end" + end + local t = table.create(n) + for k = 1, n do + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return nil, "unexpected break" + end + t[k] = v + end + return t, nil + elseif major == 5 then + if n ~= nil and n * 2 > r:remaining() then + return nil, "map count past the end" + end + local t = {} + local order = {} + local k = 0 + while n == nil or k < n do + k += 1 + local key, ke = item(st, depth + 1) + if ke then + return nil, ke + end + if key == BREAK then + if n == nil then + break + end + return nil, "unexpected break" + end + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return nil, "unexpected break" + end + if key ~= key then + return nil, "NaN map key" + end + if t[key] == nil then + table.insert(order, key) + end + t[key] = v + end + return Types.object(t, order), nil + else -- 6: tag + if n == nil then + return nil, "indefinite tag" + end + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return nil, "unexpected break" + end + -- bignum content arrives as a buffer: hand the tag its bytes + if (n == 2 or n == 3) and type(v) == "buffer" then + return tag(st, n, buffer.tostring(v)) + end + return tag(st, n, v) + end +end + +-- decode(r, opts) -> value | nil, message, offset (one item; r is left after it) +function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) + local o: DecodeOptions = opts or {} + local st: St = { + r = r, + big = o.bigInts == "string", + null = if o.null ~= nil then o.null else Types.null, + undef = if o.undefined ~= nil then o.undefined else Codec.undefined, + maxDepth = o.maxDepth or 512, + dates = o.dates ~= false, + } + local v, e = item(st, 0) + if e then + return nil, e, r.pos - r.base + end + if v == BREAK then + return nil, "unexpected break", r.pos - r.base - 1 + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +export type EncodeOptions = { + compactFloats: boolean?, -- floats in the shortest of half / single / double that keeps the value (default false) + sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) + emptyTable: ("array" | "map")?, -- a plain empty table (default "array") + dates: ("string" | "epoch")?, -- Types.Date as tag 0 text (default) or tag 1 seconds + maxDepth: number?, -- default 512 (also catches cycles) +} + +type ESt = { w: Bytes.Writer, compact: boolean, sort: boolean, emptyMap: boolean, epoch: boolean, maxDepth: number, err: string? } + +local function head(w: Bytes.Writer, major: number, n: number) + local m = major * 32 + if n < 24 then + w:u8(m + n) + elseif n < 256 then + w:u8(m + 24) + w:u8(n) + elseif n < 65536 then + w:u8(m + 25) + w:u16be(n) + elseif n < TWO32 then + w:u8(m + 26) + w:u32be(n) + elseif n >= 18446744073709551616 then -- -1 - (-2^64) rounds up to 2^64: the exact argument is 2^64 - 1 + w:u8(m + 27) + w:u32be(0xFFFFFFFF) + w:u32be(0xFFFFFFFF) + else + w:u8(m + 27) + w:u64be(n) + end +end + +-- the half-float bits of x when x is exactly representable, else nil +local function toHalf(x: number): number? + if x ~= x then + return 0x7E00 + end + local sign = if x < 0 or (x == 0 and 1 / x < 0) then 0x8000 else 0 + local a = math.abs(x) + if a == math.huge then + return sign + 0x7C00 + end + if a == 0 then + return sign + end + local m, e = math.frexp(a) -- a = m * 2^e, 0.5 <= m < 1 + local exp = e - 1 + 15 + if exp >= 31 then + return nil + end + if exp <= 0 then -- subnormal: a = mant * 2^-24 + local mant = a / 2 ^ -24 + if mant ~= math.floor(mant) or mant >= 1024 then + return nil + end + return sign + mant + end + local frac = (m * 2 - 1) * 1024 + if frac ~= math.floor(frac) then + return nil + end + return sign + exp * 1024 + frac +end +Codec.toHalf = toHalf + +local function keyLess(a: any, b: any): boolean + local ta, tb = type(a), type(b) + if ta ~= tb then + return ta < tb + end + if ta == "number" or ta == "string" then + return a < b + end + return tostring(a) < tostring(b) +end + +local function isArray(t: any, emptyMap: boolean): boolean + if Types.isObject(t) then + return false + end + local n = #t + if n == 0 then + return next(t) == nil and not emptyMap + end + local c = 0 + for _ in next, t do + c += 1 + end + return c == n +end + +local scratch = buffer.create(8) + +local function enc(st: ESt, v: any, depth: number): boolean + local w = st.w + local tv = type(v) + if v == nil or v == Types.null then + w:u8(0xF6) + elseif v == Codec.undefined then + w:u8(0xF7) + elseif tv == "boolean" then + w:u8(if v then 0xF5 else 0xF4) + elseif tv == "number" then + if v == math.floor(v) and v >= -18446744073709551616 and v < 18446744073709551616 and not (v == 0 and 1 / v < 0) then + if v >= 0 then + head(w, 0, v) + else + head(w, 1, -1 - v) + end + else + local h = if st.compact then toHalf(v) else nil + if h then + w:u8(0xF9) + w:u16be(h) + else + buffer.writef32(scratch, 0, v) + if st.compact and (buffer.readf32(scratch, 0) == v or v ~= v) then + w:u8(0xFA) + w:f32be(v) + else + w:u8(0xFB) + w:f64be(v) + end + end + end + elseif tv == "string" then + head(w, 3, #v) + w:string(v) + elseif tv == "buffer" then + head(w, 2, buffer.len(v)) + w:bytes(v) + elseif tv == "table" then + if depth >= st.maxDepth then + st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)" + return false + end + if Codec.isTagged(v) then + if type(v.tag) ~= "number" or v.tag < 0 or v.tag ~= math.floor(v.tag) then + st.err = "bad tag number" + return false + end + head(w, 6, v.tag) + return enc(st, v.value, depth + 1) + elseif Codec.isSimple(v) then + local n = v.value + if n < 20 then + w:u8(0xE0 + n) + elseif n >= 32 and n < 256 then + w:u8(0xF8) + w:u8(n) + else + st.err = "bad simple value " .. tostring(n) + return false + end + elseif Types.Date.is(v) then + if st.epoch then + w:u8(0xC1) + return enc(st, Types.Date.toUnix(v), depth + 1) + end + w:u8(0xC0) + local s = tostring(v) + head(w, 3, #s) + w:string(s) + elseif isArray(v, st.emptyMap) then + local n = #v + head(w, 4, n) + for k = 1, n do + if not enc(st, v[k], depth + 1) then + return false + end + end + else + local keys: { any } + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + head(w, 5, #keys) + for _, k in keys do + if not enc(st, k, depth + 1) or not enc(st, v[k], depth + 1) then + return false + end + end + end + else + st.err = "cannot encode a " .. tv + return false + end + return true +end + +-- encode(v, opts) -> buffer | nil, message +function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) + local o: EncodeOptions = opts or {} + local st: ESt = { + w = Bytes.writer(256), + compact = o.compactFloats == true, + sort = o.sortKeys ~= false, + emptyMap = o.emptyTable == "map", + epoch = o.dates == "epoch", + maxDepth = o.maxDepth or 512, + err = nil, + } + if not enc(st, v, 0) then + return nil, st.err + end + return st.w:finish(), nil +end + +return Codec diff --git a/src/Formats/data/cbor/init.luau b/src/Formats/data/cbor/init.luau new file mode 100644 index 0000000..c605750 --- /dev/null +++ b/src/Formats/data/cbor/init.luau @@ -0,0 +1,100 @@ +--!strict +-- data/cbor: CBOR (RFC 8949). New code. Supports: every major type, indefinite-length strings / arrays / maps, half / +-- single / double floats, tags (0 / 1 date-times as Types.Date, 2 / 3 bignums as numbers or exact decimal text, +-- 55799 self-describe stripped, others kept as Cbor.tagged(tag, value)), simple values (Cbor.simple(n), +-- Cbor.undefined), byte strings as buffers, maps as Types.object (key order kept; keys of any type), sequences +-- (RFC 8742, opts.all). Encode: preferred (shortest) integer and length heads, float64 unless opts.compactFloats, +-- definite lengths. Not supported: other semantic tags (decimal fractions, bigfloats, ...) stay tagged values. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Codec = require("@formats/data/cbor/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Cbor = { + name = "cbor", + category = "data", + extensions = { "cbor" }, + mime = { "application/cbor", "application/cbor-seq" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true, tags = true }, +} + +export type DecodeOptions = Codec.DecodeOptions & { + all: boolean?, -- a CBOR sequence: every item into an array (default false: exactly one item) +} +export type EncodeOptions = Codec.EncodeOptions & { + all: boolean?, -- the value is an array of items, written as a sequence + selfDescribe: boolean?, -- prefix the 55799 self-describe tag (d9 d9 f7) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Cbor.sniff(r: Bytes.Reader): number + return if r:peek(3) == "\217\217\247" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function codeOf(e: string): string + if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then + return Err.TRUNCATED + elseif string.find(e, "nested deeper", 1, true) then + return Err.LIMIT + end + return Err.CORRUPT +end + +function Cbor.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + if o.all then + local out = {} + while not r:eof() do + local v, e, at = Codec.decode(r, o) + if e then + return nil, Err.new(codeOf(e), e, at) + end + table.insert(out, v) + end + return out, nil + end + local v, e, at = Codec.decode(r, o) + if e then + return nil, Err.new(codeOf(e), e, at) + end + if not r:eof() then + return nil, Err.new(Err.CORRUPT, "trailing data after the item (opts.all reads a sequence)", r.pos - r.base) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Cbor.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local w = Bytes.writer() + if opts and opts.selfDescribe then + w:string("\217\217\247") + end + local items = { value } + if opts and opts.all then + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "all: expected an array of items") + end + items = value + end + for _, v in items do + local b, e = Codec.encode(v, opts) + if not b then + return nil, Err.new(Err.ARG, e or "cannot encode") + end + w:bytes(b) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Cbor.tagged = Codec.tagged -- tagged(tag, value) -> a value written as that tag +Cbor.isTagged = Codec.isTagged +Cbor.simple = Codec.simple -- simple(n) -> a simple value +Cbor.isSimple = Codec.isSimple +Cbor.undefined = Codec.undefined + +return Cbor diff --git a/src/Formats/data/csv/init.luau b/src/Formats/data/csv/init.luau new file mode 100644 index 0000000..e5c7d6d --- /dev/null +++ b/src/Formats/data/csv/init.luau @@ -0,0 +1,316 @@ +--!strict +-- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv module). New code. Supports: any +-- one-byte delimiter (opts.delimiter, or "auto" to pick , ; tab |), quoted fields with doubled quotes and embedded +-- line breaks, CRLF / LF / CR line ends, a header row (opts.header: rows become Types.object keyed by the column +-- names, in column order), number conversion by option; encode from arrays of arrays or of keyed rows, quoting only +-- where needed (like Python's QUOTE_MINIMAL) or always. Blank lines are skipped. Not supported: escape characters +-- other than the doubled quote, multi-byte delimiters. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Json = require("@formats/codecs/Json") + +-- ------------------------------------------------------------------------------------------------ contract +local Csv = { + name = "csv", + category = "data", + extensions = { "csv", "tsv" }, + mime = { "text/csv", "text/tab-separated-values" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + caps = { decode = true, encode = true, header = true }, +} + +export type DecodeOptions = { + delimiter: string?, -- one byte (default ","; "auto" guesses from the first line among , ; tab |) + quote: string?, -- the quote byte (default '"') + header: boolean?, -- the first row names the columns: rows become Types.object (default false: arrays) + numbers: boolean?, -- fields that are numbers become numbers (default false: every field is a string) + maxRows: number?, -- refuse more rows (default unlimited) +} +export type EncodeOptions = { + delimiter: string?, -- default "," + quote: string?, -- default '"' + newline: string?, -- the row terminator (default "\r\n", as RFC 4180 and Python's csv) + quoteAll: boolean?, -- quote every field (default false: only those that need it) + columns: { string }?, -- keyed rows: the column order (default: the keys of the rows in first-seen order) + header: boolean?, -- keyed rows: write the header row (default true) +} + +-- ------------------------------------------------------------------------------------------------ constants +local find, sub, byte, gsub = string.find, string.sub, string.byte, string.gsub + +local function patEscape(c: string): string + return (gsub(c, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0")) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Csv.sniff(r: Bytes.Reader): number + local head = r:peek(1024) + if find(head, "%z") then + return 0 + end + local l1, l2 = string.match(head, "^([^\r\n]*)\r?\n([^\r\n]*)") + if not l1 or l1 == "" then + return 0 + end + for _, d in { ",", "\t", ";" } do + local _, c1 = gsub(l1, d, "") + local _, c2 = gsub(l2, d, "") + if c1 > 0 and c1 == c2 then + return 0.15 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function guess(s: string, q: string): string + local line = string.match(s, "^[^\r\n]*") or "" + line = gsub(line, patEscape(q) .. "[^" .. patEscape(q) .. "]*" .. patEscape(q), "") + local best, bestN = ",", 0 + for _, d in { ",", ";", "\t", "|" } do + local _, n = gsub(line, patEscape(d), "") + if n > bestN then + best, bestN = d, n + end + end + return best +end + +-- rows(s, opts) -> { { string } } | nil, Err +function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?) + local o: DecodeOptions = opts or {} + local q = o.quote or '"' + local d = o.delimiter or "," + if d == "auto" then + d = guess(s, q) + end + if #d ~= 1 or #q ~= 1 or d == q or d == "\n" or d == "\r" then + return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes (not line ends)") + end + local qb, db = byte(q), byte(d) + local stop = "[" .. patEscape(d) .. "\r\n]" + local maxRows = o.maxRows or math.huge + local rows: { { string } } = {} + local row: { string } = {} + local n = #s + local i = 1 + local rowEmpty = true -- the current line has no field text yet (blank lines are skipped) + while true do + local c = byte(s, i) + local field: string + if c == qb then + local k = i + 1 + local parts = {} + while true do + local j = find(s, q, k, true) + if not j then + return nil, Err.new(Err.TRUNCATED, "unterminated quoted field", i - 1) + end + if byte(s, j + 1) == qb then + table.insert(parts, sub(s, k, j)) + k = j + 2 + else + table.insert(parts, sub(s, k, j - 1)) + i = j + 1 + break + end + end + -- text after the closing quote up to the delimiter is kept (Python's lenient reading) + local e = find(s, stop, i) or (n + 1) + if e > i then + table.insert(parts, sub(s, i, e - 1)) + end + i = e + field = table.concat(parts) + rowEmpty = false + else + local e = find(s, stop, i) or (n + 1) + field = sub(s, i, e - 1) + if e > i then + rowEmpty = false + end + i = e + end + table.insert(row, field) + c = byte(s, i) + if c == db then + rowEmpty = false + i += 1 + else + -- end of the row: CRLF / LF / CR / end of data + if c == 13 and byte(s, i + 1) == 10 then + i += 2 + elseif c ~= nil then + i += 1 + end + if not rowEmpty then + table.insert(rows, row) + if #rows > maxRows then + return nil, Err.new(Err.LIMIT, "more than " .. maxRows .. " rows") + end + end + row = {} + rowEmpty = true + if i > n then + break + end + end + end + return rows, nil +end + +local NUMBER = "^%s*[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*%s*$" +local function convert(v: string): any + if string.match(v, NUMBER) or string.match(v, "^%s*[%-%+]?%.%d+[eE]?[%-%+]?%d*%s*$") then + local x = tonumber(v) + if x then + return x + end + end + return v +end + +function Csv.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if sub(s, 1, 3) == "\239\187\191" then + s = sub(s, 4) + end + local rows, err = Csv.parse(s, opts) + if not rows then + return nil, err + end + local o: DecodeOptions = opts or {} + if o.numbers then + for _, row in rows do + for k, v in row do + row[k] = convert(v) + end + end + end + if not o.header then + return rows, nil + end + local names = rows[1] or {} + local out = table.create(math.max(#rows - 1, 0)) + for k = 2, #rows do + local row = rows[k] + local obj = Types.object() + for c, name in names do + if row[c] ~= nil then + Types.set(obj, tostring(name), row[c]) + end + end + out[k - 1] = obj + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function text(v: any): (string?, string?) + local tv = type(v) + if tv == "string" then + return v, nil + elseif tv == "number" then + local s = Json.number(v) + if not s then + return if v ~= v then "nan" elseif v > 0 then "inf" else "-inf", nil + end + return s, nil + elseif tv == "boolean" then + return if v then "true" else "false", nil + elseif v == nil or v == Types.null then + return "", nil + elseif tv == "table" and Types.Date.is(v) then + return tostring(v), nil + end + return nil, "cannot write a " .. tv .. " as a field" +end + +local function isArray(t: any): boolean + if type(t) ~= "table" or Types.isObject(t) then + return false + end + local n = #t + return n > 0 or next(t) == nil +end + +function Csv.encode(rows: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local d, q, nl = o.delimiter or ",", o.quote or '"', o.newline or "\r\n" + if #d ~= 1 or #q ~= 1 or d == q then + return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes") + end + if type(rows) ~= "table" then + return nil, Err.new(Err.ARG, "expected an array of rows") + end + local special = "[" .. patEscape(d) .. patEscape(q) .. "\r\n]" + local qq = q .. q + local out: { string } = {} + local function writeRow(fields: { any }, count: number): Err.Err? + local parts = table.create(count) + for k = 1, count do + local s, e = text(fields[k]) + if not s then + return Err.new(Err.ARG, "row " .. (#out + 1) .. ", field " .. k .. ": " .. tostring(e)) + end + if o.quoteAll or find(s, special) or (count == 1 and s == "") then + s = q .. gsub(s, patEscape(q), qq) .. q + end + parts[k] = s + end + table.insert(out, table.concat(parts, d) .. nl) + return nil + end + local keyed = rows[1] ~= nil and not isArray(rows[1]) + if keyed then + local cols = o.columns + if not cols then + local seen, list = {}, {} + for _, row in rows do + if type(row) ~= "table" then + return nil, Err.new(Err.ARG, "rows must be tables") + end + for _, k in Types.keys(row) do + if not seen[k] then + seen[k] = true + table.insert(list, k) + end + end + end + cols = list + end + local cl = cols :: { any } + if o.header ~= false then + local e = writeRow(cl, #cl) + if e then + return nil, e + end + end + for _, row in rows do + local fields = table.create(#cl) + for k, name in cl do + fields[k] = row[name] + end + local e = writeRow(fields, #cl) + if e then + return nil, e + end + end + else + for _, row in rows do + if type(row) ~= "table" then + return nil, Err.new(Err.ARG, "rows must be arrays of fields") + end + local e = writeRow(row, #row) + if e then + return nil, e + end + end + end + return buffer.fromstring(table.concat(out)), nil +end + +return Csv diff --git a/src/Formats/data/ini/init.luau b/src/Formats/data/ini/init.luau new file mode 100644 index 0000000..fe48955 --- /dev/null +++ b/src/Formats/data/ini/init.luau @@ -0,0 +1,250 @@ +--!strict +-- data/ini: INI / config files, read the way Python's configparser does (interpolation off, key case kept). New code. +-- Supports: [sections] (name = everything between the first '[' and the last ']'), key = value and key: value, +-- ; and # comment lines (indented too), indented continuation lines (joined with "\n"), keys before any section (at +-- the top level), duplicate keys / sections (the last value wins, sections merge), inline comments, keys without a +-- value and typed values by option. Decodes to a Types.object of sections (each a Types.object of strings), top-level +-- keys beside them. Encode writes configparser's layout ("key = value", a blank line after each section, nested +-- tables as dotted section names). Not supported: interpolation, the DEFAULT section's inheritance, escapes. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Json = require("@formats/codecs/Json") + +-- ------------------------------------------------------------------------------------------------ contract +local Ini = { + name = "ini", + category = "data", + extensions = { "ini", "cfg", "conf", "inf", "desktop" }, + mime = { "text/plain" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + caps = { decode = true, encode = true, ordered = true }, +} + +export type DecodeOptions = { + inlineComments: boolean?, -- strip " ;..." / " #..." after values (default false, like configparser) + allowNoValue: boolean?, -- a line with a key and no delimiter is the key with value true (default false: an error) + types: boolean?, -- values that are numbers / true / false / yes / no / on / off become numbers / booleans + strict: boolean?, -- a duplicate section or key is an error (default false: last wins / merge) +} +export type EncodeOptions = { + delimiter: string?, -- default " = " +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ini.sniff(r: Bytes.Reader): number + local head = r:peek(512) + if string.find(head, "%z") then + return 0 + end + local first = string.match(head, "^[%s]*([^\r\n]*)") + while first and string.match(first, "^[;#]") do + head = string.match(head, "^[^\n]*\n(.*)$") or "" + first = string.match(head, "^[%s]*([^\r\n]*)") + end + if first and string.match(first, "^%[[^%]]+%]%s*$") then + return 0.2 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local BOOLS: { [string]: boolean } = { ["true"] = true, ["false"] = false, yes = true, no = false, on = true, off = false } + +local function typed(v: any): any + if type(v) ~= "string" then + return v + end + local b = BOOLS[string.lower(v)] + if b ~= nil then + return b + end + if string.match(v, "^[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*$") or string.match(v, "^[%-%+]?%.%d+$") or string.match(v, "^0x%x+$") then + local n = tonumber(v) + if n then + return n + end + end + return v +end + +function Ini.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + local root = Types.object() + local cur = root + local lastKey: string? = nil + local lastIndent = 0 + local lastTable: any = nil + local seenKeys: { [any]: { [string]: boolean } } = {} + local pos = 1 + local lineStart = 0 + for line in string.gmatch(s .. "\n", "([^\n]*)\n") do + lineStart = pos - 1 + pos += #line + 1 + line = string.gsub(line, "\r$", "") + local indent = #(string.match(line, "^[ \t]*") :: string) + local trimmed = string.match(line, "^%s*(.-)%s*$") :: string + if trimmed == "" then + lastKey = nil + elseif string.match(trimmed, "^[;#]") then + -- a comment line (configparser: also when indented); it does not end a continuation + elseif lastKey and indent > lastIndent then + -- continuation of the previous value + local v = trimmed + if o.inlineComments then + v = string.match(v, "^(.-)%s+[;#]") or v + end + local prev = lastTable[lastKey] + lastTable[lastKey] = (if type(prev) == "string" then prev else "") .. "\n" .. v + elseif string.sub(trimmed, 1, 1) == "[" and string.find(trimmed, "]", 2, true) then + local name = string.match(trimmed, "^%[(.*)%]") :: string + local existing = root[name] + if existing ~= nil and type(existing) ~= "table" then + return nil, Err.new(Err.CORRUPT, "section [" .. name .. "] has the name of a top-level key", lineStart) + end + if existing and o.strict then + return nil, Err.new(Err.CORRUPT, "duplicate section [" .. name .. "]", lineStart) + end + if not existing then + existing = Types.object() + Types.set(root, name, existing) + end + cur = existing + lastKey = nil + else + local key, value = string.match(trimmed, "^(.-)%s*[=:]%s*(.*)$") + if not key then + if not o.allowNoValue then + return nil, Err.new(Err.CORRUPT, "line without '=' or ':': " .. string.sub(trimmed, 1, 40), lineStart) + end + key, value = trimmed, true :: any + end + if key == "" then + return nil, Err.new(Err.CORRUPT, "empty key", lineStart) + end + if o.inlineComments and type(value) == "string" then + value = string.match(value, "^(.-)%s+[;#]") or (if string.match(value, "^[;#]") then "" else value) + end + local seen = seenKeys[cur] + if not seen then + seen = {} + seenKeys[cur] = seen + end + if seen[key :: string] and o.strict then + return nil, Err.new(Err.CORRUPT, "duplicate key " .. key, lineStart) + end + seen[key :: string] = true + if cur == root and type(root[key]) == "table" then + return nil, Err.new(Err.CORRUPT, "top-level key " .. key .. " has the name of a section", lineStart) + end + Types.set(cur, key, value) + lastKey, lastIndent, lastTable = key, indent, cur + end + end + if o.types then + for _, k in Types.keys(root) do + local v = root[k] + if type(v) == "table" then + for _, k2 in Types.keys(v) do + v[k2] = typed(v[k2]) + end + else + root[k] = typed(v) + end + end + end + return root, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function text(v: any): string? + local tv = type(v) + if tv == "string" then + return (string.gsub(v, "\n", "\n\t")) + elseif tv == "number" then + return Json.number(v) or tostring(v) + elseif tv == "boolean" then + return if v then "true" else "false" + elseif v == Types.null then + return "" + elseif tv == "table" and Types.Date.is(v) then + return tostring(v) + end + return nil +end + +function Ini.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "expected a table of sections") + end + local delim = (opts and opts.delimiter) or " = " + local out: { string } = {} + local err: string? = nil + local function keyOk(k: any): boolean + if type(k) ~= "string" and type(k) ~= "number" then + err = "keys must be strings" + return false + end + local ks = tostring(k) + if ks == "" or string.find(ks, "[=:\r\n]") or string.match(ks, "^[%s;#%[]") or string.match(ks, "%s$") then + err = "key " .. string.format("%q", ks) .. " cannot be written" + return false + end + return true + end + local function pairsOf(t: any, prefix: string, depth: number): boolean + if depth > 32 then + err = "sections nested too deeply (a cycle?)" + return false + end + local subs = {} + local lines = {} + for _, k in Types.keys(t) do + local v = t[k] + if type(v) == "table" and not Types.Date.is(v) and v ~= Types.null then + table.insert(subs, k) + else + if not keyOk(k) then + return false + end + local s = text(v) + if not s then + err = "cannot write a " .. type(v) .. " value" + return false + end + table.insert(lines, tostring(k) .. delim .. s .. "\n") + end + end + if prefix ~= "" then + table.insert(out, "[" .. prefix .. "]\n") + table.move(lines, 1, #lines, #out + 1, out) + table.insert(out, "\n") + elseif #lines > 0 then + table.move(lines, 1, #lines, #out + 1, out) + table.insert(out, "\n") + end + for _, k in subs do + local name = tostring(k) + if string.find(name, "[\r\n%]]") then + err = "section name " .. string.format("%q", name) .. " cannot be written" + return false + end + if not pairsOf(t[k], if prefix == "" then name else prefix .. "." .. name, depth + 1) then + return false + end + end + return true + end + if not pairsOf(value, "", 0) then + return nil, Err.new(Err.ARG, err or "cannot encode") + end + return buffer.fromstring(table.concat(out)), nil +end + +return Ini diff --git a/src/Formats/data/json/init.luau b/src/Formats/data/json/init.luau new file mode 100644 index 0000000..bf75d5f --- /dev/null +++ b/src/Formats/data/json/init.luau @@ -0,0 +1,93 @@ +--!strict +-- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/Json (which see for the value mapping and options). +-- Supports: decode to plain Luau values (Types.null, ordered keys and bigInts as strings by option), encode compact or +-- pretty. JSON Lines through codecs/Json.lines. Not supported: JSON5 / comments / trailing commas. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Json = require("@formats/codecs/Json") + +-- ------------------------------------------------------------------------------------------------ contract +local JsonFormat = { + name = "json", + category = "data", + extensions = { "json", "jsonl", "ndjson", "geojson" }, + mime = { "application/json", "application/x-ndjson" }, + deps = { "core/Err", "core/Bytes", "codecs/Json" }, + caps = { decode = true, encode = true, ordered = true, streaming = true }, +} + +export type DecodeOptions = Json.DecodeOptions & { + lines: boolean?, -- JSON Lines: decode every value into an array (default false: one value) +} +export type EncodeOptions = Json.EncodeOptions & { + lines: boolean?, -- JSON Lines: the value must be an array, written one compact value per line +} + +-- ------------------------------------------------------------------------------------------------ sniff +function JsonFormat.sniff(r: Bytes.Reader): number + local head = r:peek(64) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + local first = string.match(head, "^[ \t\r\n]*(.)") + if first == "{" then + local nxt = string.match(head, "^[^{]*{[ \t\r\n]*(.)") + return if nxt == nil or nxt == '"' or nxt == "}" then 0.6 else 0.1 + elseif first == "[" then + -- past any nested '[': a JSON value must start (TOML / INI "[section]" and "[[table]]" do not) + local nxt = string.match(head, "^[ \t\r\n]*[%[ \t\r\n]*(.)") + if nxt == nil or string.find('{"-0123456789tfn]', nxt, 1, true) then + return 0.3 + end + return 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function JsonFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if opts and opts.lines then + local out = {} + for _, v, err in Json.lines(s, opts) do + if err then + return nil, err + end + table.insert(out, v) + end + return out, nil + end + return Json.decode(s, opts) +end + +-- ------------------------------------------------------------------------------------------------ encode +function JsonFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if opts and opts.lines then + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "lines: expected an array of values") + end + local o = table.clone(opts) :: any + o.indent = nil + local parts = {} + for i, v in value do + local s, err = Json.encode(v, o) + if not s then + return nil, err + end + parts[i] = s .. "\n" + end + return buffer.fromstring(table.concat(parts)), nil + end + local s, err = Json.encode(value, opts) + if not s then + return nil, err + end + if opts and opts.indent then + s ..= "\n" + end + return buffer.fromstring(s), nil +end + +return JsonFormat diff --git a/src/Formats/data/msgpack/Codec.luau b/src/Formats/data/msgpack/Codec.luau new file mode 100644 index 0000000..fd42577 --- /dev/null +++ b/src/Formats/data/msgpack/Codec.luau @@ -0,0 +1,468 @@ +--!strict +--!native +-- data/msgpack/Codec: the MessagePack decoder and encoder behind data/msgpack (msgpack spec, 2017 revision with +-- str8 / bin / ext and the timestamp extension). Never throws: errors return nil, message, offset. +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") + +local Codec = {} + +local TWO32 = 4294967296 + +-- an extension value: { type = -128..127, data = buffer } +local ExtMeta = { __tostring = function(e: any): string + return "msgpack.ext(" .. e.type .. ", " .. buffer.len(e.data) .. " bytes)" +end } +function Codec.ext(t: number, data: buffer): { type: number, data: buffer } + return setmetatable({ type = t, data = data }, ExtMeta) :: any +end +function Codec.isExt(v: any): boolean + return type(v) == "table" and getmetatable(v) == ExtMeta +end + +-- decimal text of hi * 2^32 + lo (hi, lo unsigned 32-bit), exact +local function u64text(hi: number, lo: number): string + if hi == 0 then + return string.format("%d", lo) + end + local digits = {} + -- long division by 10 on four 16-bit limbs + local l = { hi // 65536, hi % 65536, lo // 65536, lo % 65536 } + while l[1] ~= 0 or l[2] ~= 0 or l[3] ~= 0 or l[4] ~= 0 do + local rem = 0 + for k = 1, 4 do + local cur = rem * 65536 + l[k] + l[k] = cur // 10 + rem = cur % 10 + end + table.insert(digits, 1, string.char(48 + rem)) + end + return table.concat(digits) +end +Codec.u64text = u64text + +export type DecodeOptions = { + bigInts: ("number" | "string")?, -- 64-bit integers past 2^53: "string" keeps the exact decimal text + null: any?, -- the value for nil (default Types.null) + maxDepth: number?, -- nesting limit (default 512) + timestamps: boolean?, -- ext -1 as a Types.Date (default true) + ordered: boolean?, -- maps as Types.object with key order (default true) +} + +type St = { r: Bytes.Reader, big: boolean, null: any, maxDepth: number, ts: boolean, ordered: boolean } + +local function int64(st: St, signed: boolean): any + local r = st.r + local hi, lo = r:u32be(), r:u32be() + if signed and hi >= 0x80000000 then + -- negative: two's complement + local nhi, nlo = 0xFFFFFFFF - hi, TWO32 - lo + if nlo == TWO32 then + nlo = 0 + nhi += 1 + end + if st.big and nhi >= 0x200000 then + return "-" .. u64text(nhi, nlo) + end + return -(nhi * TWO32 + nlo) + end + if st.big and hi >= 0x200000 then + return u64text(hi, lo) + end + return hi * TWO32 + lo +end + +local value: (st: St, depth: number) -> (any, string?) + +local function ext(st: St, n: number): (any, string?) + local r = st.r + local t = r:i8() + if r.err or not r:need(n) then + return nil, "truncated ext" + end + if t == -1 and st.ts then + local secs, ns = 0, 0 + if n == 4 then + secs = r:u32be() + elseif n == 8 then + local hi, lo = r:u32be(), r:u32be() + ns = hi // 4 + secs = (hi % 4) * TWO32 + lo + elseif n == 12 then + ns = r:u32be() + secs = r:i64be() + else + return nil, "bad timestamp length" + end + if ns > 999999999 then + return nil, "bad timestamp nanoseconds" + end + local d: any = Types.Date.fromUnix(secs) + d.nanosecond = ns + return d, nil + end + return Codec.ext(t, r:bytes(n)), nil +end + +local function array(st: St, n: number, depth: number): (any, string?) + if n > st.r:remaining() then + return nil, "array count past the end" + end + local t = table.create(n) + for k = 1, n do + local v, e = value(st, depth + 1) + if e then + return nil, e + end + t[k] = v + end + return t, nil +end + +local function map(st: St, n: number, depth: number): (any, string?) + if n * 2 > st.r:remaining() then + return nil, "map count past the end" + end + local t = {} + local order: { any }? = if st.ordered then table.create(n) else nil + for _ = 1, n do + local k, e = value(st, depth + 1) + if e then + return nil, e + end + local v, e2 = value(st, depth + 1) + if e2 then + return nil, e2 + end + if k ~= k then + return nil, "NaN map key" + end + if order and t[k] == nil then + table.insert(order, k) + end + t[k] = v + end + return Types.object(t, order or {}), nil +end + +function value(st: St, depth: number): (any, string?) + if depth > st.maxDepth then + return nil, "nested deeper than " .. st.maxDepth + end + local r = st.r + local b = r:u8() + if r.err then + return nil, "truncated" + end + if b < 0x80 then + return b, nil + elseif b >= 0xE0 then + return b - 256, nil + elseif b < 0x90 then + return map(st, b - 0x80, depth) + elseif b < 0xA0 then + return array(st, b - 0x90, depth) + elseif b < 0xC0 then + local n = b - 0xA0 + if not r:need(n) then + return nil, "truncated string" + end + return r:string(n), nil + elseif b == 0xC0 then + return st.null, nil + elseif b == 0xC2 then + return false, nil + elseif b == 0xC3 then + return true, nil + elseif b == 0xC4 or b == 0xC5 or b == 0xC6 then + local n = if b == 0xC4 then r:u8() elseif b == 0xC5 then r:u16be() else r:u32be() + if r.err or not r:need(n) then + return nil, "truncated bin" + end + return r:bytes(n), nil + elseif b == 0xC7 or b == 0xC8 or b == 0xC9 then + local n = if b == 0xC7 then r:u8() elseif b == 0xC8 then r:u16be() else r:u32be() + if r.err then + return nil, "truncated ext" + end + return ext(st, n) + elseif b == 0xCA then + local v = r:f32be() + return if r.err then nil else v, if r.err then "truncated" else nil + elseif b == 0xCB then + local v = r:f64be() + return if r.err then nil else v, if r.err then "truncated" else nil + elseif b >= 0xCC and b <= 0xD3 then + local v: any + if b == 0xCC then + v = r:u8() + elseif b == 0xCD then + v = r:u16be() + elseif b == 0xCE then + v = r:u32be() + elseif b == 0xCF then + v = int64(st, false) + elseif b == 0xD0 then + v = r:i8() + elseif b == 0xD1 then + v = r:i16be() + elseif b == 0xD2 then + v = r:i32be() + else + v = int64(st, true) + end + if r.err then + return nil, "truncated" + end + return v, nil + elseif b >= 0xD4 and b <= 0xD8 then + return ext(st, 2 ^ (b - 0xD4)) + elseif b >= 0xD9 and b <= 0xDB then + local n = if b == 0xD9 then r:u8() elseif b == 0xDA then r:u16be() else r:u32be() + if r.err or not r:need(n) then + return nil, "truncated string" + end + return r:string(n), nil + elseif b == 0xDC or b == 0xDD then + local n = if b == 0xDC then r:u16be() else r:u32be() + if r.err then + return nil, "truncated" + end + return array(st, n, depth) + elseif b == 0xDE or b == 0xDF then + local n = if b == 0xDE then r:u16be() else r:u32be() + if r.err then + return nil, "truncated" + end + return map(st, n, depth) + end + return nil, string.format("reserved type byte 0x%02x", b) +end + +-- decode(r, opts) -> value, nil | nil, message, offset (one value; r is left after it) +function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) + local o: DecodeOptions = opts or {} + local st: St = { + r = r, + big = o.bigInts == "string", + null = if o.null ~= nil then o.null else Types.null, + maxDepth = o.maxDepth or 512, + ts = o.timestamps ~= false, + ordered = o.ordered ~= false, + } + local v, e = value(st, 0) + if e then + return nil, e, r.pos - r.base + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +export type EncodeOptions = { + float32: boolean?, -- non-integer numbers as float32 (default false: float64) + sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) + emptyTable: ("array" | "map")?, -- a plain empty table (default "array") + maxDepth: number?, -- default 512 (also catches cycles) + stringsAsBin: boolean?, -- strings as bin (default false: str) +} + +type ESt = { w: Bytes.Writer, f32: boolean, sort: boolean, emptyMap: boolean, maxDepth: number, bin: boolean, err: string? } + +local function writeInt(w: Bytes.Writer, v: number) + if v >= 0 then + if v < 128 then + w:u8(v) + elseif v < 256 then + w:u8(0xCC) + w:u8(v) + elseif v < 65536 then + w:u8(0xCD) + w:u16be(v) + elseif v < TWO32 then + w:u8(0xCE) + w:u32be(v) + else + w:u8(0xCF) + w:u64be(v) + end + else + if v >= -32 then + w:u8(v + 256) + elseif v >= -128 then + w:u8(0xD0) + w:u8(v + 256) + elseif v >= -32768 then + w:u8(0xD1) + w:u16be(v + 65536) + elseif v >= -2147483648 then + w:u8(0xD2) + w:u32be(v + TWO32) + else + w:u8(0xD3) + local hi = math.floor(v / TWO32) + local lo = v - hi * TWO32 + w:u32be(hi + TWO32) + w:u32be(lo) + end + end +end + +local function lenHeader(w: Bytes.Writer, n: number, fix: number?, fixMax: number, b8: number?, b16: number, b32: number) + if fix and n <= fixMax then + w:u8(fix + n) + elseif b8 and n < 256 then + w:u8(b8) + w:u8(n) + elseif n < 65536 then + w:u8(b16) + w:u16be(n) + else + w:u8(b32) + w:u32be(n) + end +end + +local function keyLess(a: any, b: any): boolean + local ta, tb = type(a), type(b) + if ta ~= tb then + return ta < tb + end + if ta == "number" or ta == "string" then + return a < b + end + return tostring(a) < tostring(b) +end + +local function isArray(t: any, emptyMap: boolean): boolean + if Types.isObject(t) then + return false + end + local n = #t + if n == 0 then + return next(t) == nil and not emptyMap + end + local c = 0 + for _ in next, t do + c += 1 + end + return c == n +end +Codec.isArray = isArray + +local function enc(st: ESt, v: any, depth: number): boolean + local w = st.w + local tv = type(v) + if v == nil or v == Types.null then + w:u8(0xC0) + elseif tv == "boolean" then + w:u8(if v then 0xC3 else 0xC2) + elseif tv == "number" then + if v == math.floor(v) and v >= -9223372036854775808 and v < 18446744073709551616 then + writeInt(w, v) + elseif st.f32 then + w:u8(0xCA) + w:f32be(v) + else + w:u8(0xCB) + w:f64be(v) + end + elseif tv == "string" then + if st.bin then + lenHeader(w, #v, nil, 0, 0xC4, 0xC5, 0xC6) + else + lenHeader(w, #v, 0xA0, 31, 0xD9, 0xDA, 0xDB) + end + w:string(v) + elseif tv == "buffer" then + lenHeader(w, buffer.len(v), nil, 0, 0xC4, 0xC5, 0xC6) + w:bytes(v) + elseif tv == "table" then + if depth >= st.maxDepth then + st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)" + return false + end + if Codec.isExt(v) then + local n = buffer.len(v.data) + if n == 1 or n == 2 or n == 4 or n == 8 or n == 16 then + w:u8(({ [1] = 0xD4, [2] = 0xD5, [4] = 0xD6, [8] = 0xD7, [16] = 0xD8 })[n]) + else + lenHeader(w, n, nil, 0, 0xC7, 0xC8, 0xC9) + end + w:u8(v.type % 256) + w:bytes(v.data) + elseif Types.Date.is(v) then + local t = Types.Date.toUnix(v) + local secs = math.floor(t) + local ns = (v :: any).nanosecond or 0 + if ns == 0 and secs >= 0 and secs < TWO32 then + w:u8(0xD6) + w:u8(0xFF) + w:u32be(secs) + elseif secs >= 0 and secs < 2 ^ 34 then + w:u8(0xD7) + w:u8(0xFF) + w:u32be(ns * 4 + secs // TWO32) + w:u32be(secs % TWO32) + else + w:u8(0xC7) + w:u8(12) + w:u8(0xFF) + w:u32be(ns) + local hi = math.floor(secs / TWO32) + w:u32be(hi % TWO32) + w:u32be(secs - hi * TWO32) + end + elseif isArray(v, st.emptyMap) then + local n = #v + lenHeader(w, n, 0x90, 15, nil, 0xDC, 0xDD) + for k = 1, n do + if not enc(st, v[k], depth + 1) then + return false + end + end + else + local keys: { any } + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + lenHeader(w, #keys, 0x80, 15, nil, 0xDE, 0xDF) + for _, k in keys do + if not enc(st, k, depth + 1) or not enc(st, v[k], depth + 1) then + return false + end + end + end + else + st.err = "cannot encode a " .. tv + return false + end + return true +end + +-- encode(v, opts) -> buffer | nil, message +function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) + local o: EncodeOptions = opts or {} + local st: ESt = { + w = Bytes.writer(256), + f32 = o.float32 == true, + sort = o.sortKeys ~= false, + emptyMap = o.emptyTable == "map", + maxDepth = o.maxDepth or 512, + bin = o.stringsAsBin == true, + err = nil, + } + if not enc(st, v, 0) then + return nil, st.err + end + return st.w:finish(), nil +end + +return Codec diff --git a/src/Formats/data/msgpack/init.luau b/src/Formats/data/msgpack/init.luau new file mode 100644 index 0000000..ecd96f9 --- /dev/null +++ b/src/Formats/data/msgpack/init.luau @@ -0,0 +1,90 @@ +--!strict +-- data/msgpack: MessagePack (msgpack spec, str8 / bin / ext revision). New code. Supports: every type, the +-- timestamp extension (-1) as Types.Date, other extensions as Msgpack.ext(type, data), bin as buffers, maps as +-- Types.object (key order kept; keys of any type), 64-bit integers past 2^53 as exact decimal strings by option, a +-- stream of concatenated values (opts.all). Encode picks the smallest integer / length forms (float64 for +-- non-integers unless opts.float32). Not supported: nothing in the spec. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Codec = require("@formats/data/msgpack/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Msgpack = { + name = "msgpack", + category = "data", + extensions = { "msgpack", "mpk" }, + mime = { "application/msgpack", "application/x-msgpack" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true }, +} + +export type DecodeOptions = Codec.DecodeOptions & { + all: boolean?, -- decode every concatenated value into an array (default false: exactly one value) +} +export type EncodeOptions = Codec.EncodeOptions & { + all: boolean?, -- the value is an array of values, written one after another +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Msgpack.sniff(_r: Bytes.Reader): number + return 0 -- no magic: by extension or opts.format only +end + +-- ------------------------------------------------------------------------------------------------ decode +function Msgpack.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + if o.all then + local out = {} + while not r:eof() do + local v, e, at = Codec.decode(r, o) + if e then + return nil, Err.new(if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED else Err.CORRUPT, e, at) + end + table.insert(out, v) + end + return out, nil + end + local v, e, at = Codec.decode(r, o) + if e then + local code = if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED + elseif string.find(e, "nested deeper", 1, true) then Err.LIMIT + else Err.CORRUPT + return nil, Err.new(code, e, at) + end + if not r:eof() then + return nil, Err.new(Err.CORRUPT, "trailing data after the value (opts.all reads a stream)", r.pos - r.base) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Msgpack.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if opts and opts.all then + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "all: expected an array of values") + end + local w = Bytes.writer() + for _, v in value do + local b, e = Codec.encode(v, opts) + if not b then + return nil, Err.new(Err.ARG, e or "cannot encode") + end + w:bytes(b) + end + return w:finish(), nil + end + local b, e = Codec.encode(value, opts) + if not b then + return nil, Err.new(Err.ARG, e or "cannot encode") + end + return b, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- ext(type, data) -> an extension value { type, data } that encodes as ext; isExt(v) +Msgpack.ext = Codec.ext +Msgpack.isExt = Codec.isExt + +return Msgpack diff --git a/src/Formats/data/plist/Base64.luau b/src/Formats/data/plist/Base64.luau new file mode 100644 index 0000000..115cf94 --- /dev/null +++ b/src/Formats/data/plist/Base64.luau @@ -0,0 +1,71 @@ +--!strict +--!native +-- data/plist/Base64: RFC 4648 base64 for plist (decode skips whitespace; encode wraps lines). Never throws. +local Base64 = {} + +local ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" +local DEC: { [number]: number } = {} +for i = 1, 64 do + DEC[string.byte(ALPHA, i)] = i - 1 +end +local ENC: { string } = {} +for i = 1, 64 do + ENC[i - 1] = string.sub(ALPHA, i, i) +end + +-- decode(s) -> buffer | nil, message (whitespace ignored; padding optional) +function Base64.decode(s: string): (buffer?, string?) + local clean = string.gsub(s, "[ \t\r\n]", "") + clean = string.gsub(clean, "=+$", "") + local n = #clean + if n % 4 == 1 then + return nil, "bad base64 length" + end + local out = buffer.create(n * 3 // 4) + local o = 0 + local acc, bits = 0, 0 + for i = 1, n do + local v = DEC[string.byte(clean, i)] + if v == nil then + return nil, "bad base64 character" + end + acc = acc * 64 + v + bits += 6 + if bits >= 8 then + bits -= 8 + local b = acc // (2 ^ bits) + buffer.writeu8(out, o, b) + o += 1 + acc -= b * 2 ^ bits + end + end + return out, nil +end + +-- encode(b, lineBytes?) -> base64 text; lineBytes > 0 puts "\n" after every lineBytes input bytes (and at the end) +function Base64.encode(b: buffer, lineBytes: number?): string + local n = buffer.len(b) + local parts = table.create(n // 3 + 2) + local per = lineBytes or 0 + local k = 0 + local i = 0 + while i < n do + local a = buffer.readu8(b, i) + local c1 = if i + 1 < n then buffer.readu8(b, i + 1) else 0 + local c2 = if i + 2 < n then buffer.readu8(b, i + 2) else 0 + local v = a * 65536 + c1 * 256 + c2 + local q = ENC[v // 262144] .. ENC[(v // 4096) % 64] + q ..= if i + 1 < n then ENC[(v // 64) % 64] else "=" + q ..= if i + 2 < n then ENC[v % 64] else "=" + k += 1 + parts[k] = q + i += 3 + if per > 0 and (i % per == 0 or i >= n) then + k += 1 + parts[k] = "\n" + end + end + return table.concat(parts) +end + +return Base64 diff --git a/src/Formats/data/plist/Binary.luau b/src/Formats/data/plist/Binary.luau new file mode 100644 index 0000000..544fe33 --- /dev/null +++ b/src/Formats/data/plist/Binary.luau @@ -0,0 +1,271 @@ +--!strict +--!native +-- data/plist/Binary: the binary property list reader ("bplist00", CoreFoundation's format as documented in +-- CFBinaryPList.c and implemented by Python's plistlib). Objects: null / bool / fill, ints (1, 2, 4, 8 bytes; 16-byte +-- ints are read from their low 8 bytes), reals (4 / 8 bytes), dates, data, ASCII / UTF-16BE / UTF-8 strings, UIDs, +-- arrays, sets (as arrays), dicts (Types.object, key order kept). Shared references decode to the same table; cycles +-- are errors. Never throws: errors return nil, message. +local Types = require("@formats/Types") + +local Binary = {} + +local readu8 = buffer.readu8 +local TWO32 = 4294967296 +local EPOCH_2001 = 978307200 + +local UidMeta = { __tostring = function(u: any): string + return "UID(" .. u.uid .. ")" +end } +function Binary.uid(n: number): { uid: number } + return setmetatable({ uid = n }, UidMeta) :: any +end +function Binary.isUid(v: any): boolean + return type(v) == "table" and getmetatable(v) == UidMeta +end + +local function be(b: buffer, o: number, n: number): number + local v = 0 + for k = 0, n - 1 do + v = v * 256 + readu8(b, o + k) + end + return v +end + +local function utf8char(c: number): string + if c < 0x80 then + return string.char(c) + elseif c < 0x800 then + return string.char(0xC0 + c // 64, 0x80 + c % 64) + elseif c < 0x10000 then + return string.char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) + end + return string.char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) +end + +export type Options = { bigInts: ("number" | "string")?, maxDepth: number? } + +-- decode(buf, base, len, opts) -> value | nil, message +function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (any, string?) + if len < 40 then + return nil, "truncated: shorter than header + trailer" + end + local t = base + len - 32 + local offSize, refSize = readu8(b, t + 6), readu8(b, t + 7) + local numObjects = be(b, t + 8, 8) + local top = be(b, t + 16, 8) + local tableOff = be(b, t + 24, 8) + if offSize < 1 or offSize > 8 or refSize < 1 or refSize > 8 then + return nil, "bad trailer sizes" + end + if numObjects < 1 or top >= numObjects or tableOff < 8 or tableOff + numObjects * offSize > len - 32 then + return nil, "bad trailer" + end + local maxDepth = (opts and opts.maxDepth) or 512 + local cache: { [number]: any } = {} + local busy: { [number]: boolean } = {} + + local object: (idx: number, depth: number) -> (any, string?) + + -- a length nibble: 0..14, or 15 = an int object follows + local function count(o: number, nib: number): (number?, number) + if nib < 15 then + return nib, o + 1 + end + if o + 2 > len - 32 then + return nil, 0 + end + local m = readu8(b, base + o + 1) + if m // 16 ~= 1 then + return nil, 0 + end + local w = 2 ^ (m % 16) + if w > 8 or o + 2 + w > len - 32 then + return nil, 0 + end + return be(b, base + o + 2, w), o + 2 + w + end + + local function ref(at: number): number + return be(b, base + at, refSize) + end + + function object(idx: number, depth: number): (any, string?) + local cached = cache[idx] + if cached ~= nil then + return cached, nil + end + if busy[idx] then + return nil, "object references form a cycle" + end + if depth > maxDepth then + return nil, "nested deeper than " .. maxDepth + end + if idx >= numObjects then + return nil, "object reference out of range" + end + local o = be(b, base + tableOff + idx * offSize, offSize) + if o < 8 or o >= len - 32 then + return nil, "object offset out of range" + end + local marker = readu8(b, base + o) + local hi, nib = marker // 16, marker % 16 + local v: any + if marker == 0x00 then + v = Types.null + elseif marker == 0x08 then + v = false + elseif marker == 0x09 then + v = true + elseif hi == 1 then + local w = 2 ^ nib + if w > 16 or o + 1 + w > len - 32 then + return nil, "bad integer" + end + if w == 16 then + o += 8 + w = 8 + end + if w == 8 then + local h, l = be(b, base + o + 1, 4), be(b, base + o + 5, 4) + if h >= 0x80000000 and nib == 3 then + v = (h - TWO32) * TWO32 + l + elseif opts and opts.bigInts == "string" and h >= 0x200000 then + -- exact decimal text of h * 2^32 + l + local digits = {} + local limbs = { h // 65536, h % 65536, l // 65536, l % 65536 } + while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do + local rem = 0 + for k = 1, 4 do + local cur = rem * 65536 + limbs[k] + limbs[k] = cur // 10 + rem = cur % 10 + end + table.insert(digits, 1, string.char(48 + rem)) + end + v = table.concat(digits) + else + v = h * TWO32 + l + end + else + v = be(b, base + o + 1, w) + end + elseif hi == 2 then + if nib == 2 and o + 5 <= len - 32 then + local s = buffer.create(4) + for k = 0, 3 do + buffer.writeu8(s, k, readu8(b, base + o + 4 - k)) + end + v = buffer.readf32(s, 0) + elseif nib == 3 and o + 9 <= len - 32 then + local s = buffer.create(8) + for k = 0, 7 do + buffer.writeu8(s, k, readu8(b, base + o + 8 - k)) + end + v = buffer.readf64(s, 0) + else + return nil, "bad real" + end + elseif marker == 0x33 then + if o + 9 > len - 32 then + return nil, "truncated date" + end + local s = buffer.create(8) + for k = 0, 7 do + buffer.writeu8(s, k, readu8(b, base + o + 8 - k)) + end + local secs = buffer.readf64(s, 0) + if secs ~= secs or math.abs(secs) > 1e14 then + return nil, "bad date" + end + v = Types.Date.fromUnix(secs + EPOCH_2001) + elseif hi == 4 or hi == 5 or hi == 6 or hi == 7 then + local n, p = count(o, nib) + if not n then + return nil, "bad length" + end + local bytes = if hi == 6 then n * 2 else n + if p + bytes > len - 32 then + return nil, "string / data past the end" + end + if hi == 4 then + local d = buffer.create(bytes) + buffer.copy(d, 0, b, base + p, bytes) + v = d + elseif hi == 6 then + local parts = table.create(n) + local k = 0 + while k < n do + local u = be(b, base + p + k * 2, 2) + k += 1 + if u >= 0xD800 and u <= 0xDBFF and k < n then + local lo = be(b, base + p + k * 2, 2) + if lo >= 0xDC00 and lo <= 0xDFFF then + u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00) + k += 1 + end + end + table.insert(parts, utf8char(u)) + end + v = table.concat(parts) + else + v = buffer.readstring(b, base + p, bytes) + end + elseif hi == 8 then + if o + 2 + nib > len - 32 then + return nil, "bad UID" + end + v = Binary.uid(be(b, base + o + 1, nib + 1)) + elseif hi == 0xA or hi == 0xC or hi == 0xD then + local n, p = count(o, nib) + if not n then + return nil, "bad length" + end + local refs = if hi == 0xD then n * 2 else n + if p + refs * refSize > len - 32 then + return nil, "collection past the end" + end + busy[idx] = true + if hi == 0xD then + local t2 = {} + local order = table.create(n) + for k = 0, n - 1 do + local key, ke = object(ref(p + k * refSize), depth + 1) + if ke then + return nil, ke + end + if type(key) ~= "string" then + return nil, "dict key is not a string" + end + local val, ve = object(ref(p + (n + k) * refSize), depth + 1) + if ve then + return nil, ve + end + if t2[key] == nil then + table.insert(order, key) + end + t2[key] = val + end + v = Types.object(t2, order) + else + local arr = table.create(n) + for k = 0, n - 1 do + local item, ie = object(ref(p + k * refSize), depth + 1) + if ie then + return nil, ie + end + arr[k + 1] = item + end + v = arr + end + busy[idx] = nil + else + return nil, string.format("unknown object marker 0x%02x", marker) + end + cache[idx] = v + return v, nil + end + + return object(top, 0) +end + +return Binary diff --git a/src/Formats/data/plist/init.luau b/src/Formats/data/plist/init.luau new file mode 100644 index 0000000..e8bede1 --- /dev/null +++ b/src/Formats/data/plist/init.luau @@ -0,0 +1,306 @@ +--!strict +-- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/Xml; the write is +-- byte-identical to Python's plistlib for the same key order) and binary plists ("bplist00", read). Values: dict -> +-- Types.object (key order kept), array, string, integer / real -> number, true / false, date -> Types.Date, data -> +-- buffer, UID (binary) -> Plist.uid(n). Not supported: binary write, the old OpenStep text format, integers past +-- 2^63. Note: Luau has one number type, so a real with an integral value is written back as . + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Xml = require("@formats/codecs/Xml") +local Json = require("@formats/codecs/Json") +local Base64 = require("@formats/data/plist/Base64") +local Binary = require("@formats/data/plist/Binary") + +-- ------------------------------------------------------------------------------------------------ contract +local Plist = { + name = "plist", + category = "data", + extensions = { "plist" }, + mime = { "application/x-plist", "application/x-bplist" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Json" }, + caps = { decode = true, encode = true, binary = "read", ordered = true }, +} + +export type DecodeOptions = { + bigInts: ("number" | "string")?, -- integers past 2^53: "string" keeps exact decimal text + maxDepth: number?, -- default 512 +} +export type EncodeOptions = { + sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Plist.sniff(r: Bytes.Reader): number + local head = r:peek(256) + if string.sub(head, 1, 6) == "bplist" then + return 1 + end + if string.find(head, " ((opts and opts.maxDepth) or 512) then + return nil, "nested too deeply" + end + local name = node.name + if name == "dict" then + local out = Types.object() + local kids = Xml.children(node) + local i = 1 + while i <= #kids do + local k = kids[i] + if k.name ~= "key" then + return nil, "dict: expected , got <" .. k.name .. ">" + end + local v = kids[i + 1] + if not v then + return nil, "dict: without a value" + end + local val, e = xmlValue(v, opts, depth + 1) + if e then + return nil, e + end + Types.set(out, Xml.text(k), val) + i += 2 + end + return out, nil + elseif name == "array" then + local out = {} + for _, ch in Xml.children(node) do + local val, e = xmlValue(ch, opts, depth + 1) + if e then + return nil, e + end + table.insert(out, val) + end + return out, nil + elseif name == "string" then + return Xml.text(node), nil + elseif name == "integer" then + local t = string.match(Xml.text(node), "^%s*(.-)%s*$") :: string + local neg, hex = string.match(t, "^([%-%+]?)0[xX](%x+)$") + local n: number? + if hex then + n = tonumber(hex, 16) + if n and neg == "-" then + n = -n + end + elseif string.match(t, "^[%-%+]?%d+$") then + n = tonumber(t) + if n and math.abs(n) >= 2 ^ 53 and opts and opts.bigInts == "string" then + return (string.gsub(t, "^%+", "")), nil + end + end + if not n then + return nil, "bad integer " .. string.sub(t, 1, 30) + end + return n, nil + elseif name == "real" then + local t = string.lower(string.match(Xml.text(node), "^%s*(.-)%s*$") :: string) + local n = tonumber(t) + if not n then + if t == "nan" or t == "+nan" or t == "-nan" then + n = 0 / 0 + elseif t == "inf" or t == "+inf" or t == "infinity" or t == "+infinity" then + n = math.huge + elseif t == "-inf" or t == "-infinity" then + n = -math.huge + end + end + if not n then + return nil, "bad real " .. string.sub(t, 1, 30) + end + return n, nil + elseif name == "true" then + return true, nil + elseif name == "false" then + return false, nil + elseif name == "date" then + local d = Types.Date.parse((string.match(Xml.text(node), "^%s*(.-)%s*$"))) + if not d then + return nil, "bad date" + end + return d, nil + elseif name == "data" then + local b, e = Base64.decode(Xml.text(node)) + if not b then + return nil, e + end + return b, nil + end + return nil, "unknown element <" .. tostring(name) .. ">" +end + +function Plist.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local len = r.limit - r.base + if len >= 8 and buffer.readstring(r.buf, r.base, 6) == "bplist" then + local v, e = Binary.decode(r.buf, r.base, len, opts) + if e then + return nil, Err.new(if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED else Err.CORRUPT, e) + end + return v, nil + end + local doc, err = Xml.decode(buffer.readstring(r.buf, r.base, len), { whitespace = true }) + if not doc then + return nil, err + end + local root = (doc :: any).root + if root.name == "plist" then + local kids = Xml.children(root) + if #kids ~= 1 then + return nil, Err.new(Err.CORRUPT, " must hold exactly one value") + end + root = kids[1] + end + local v, e = xmlValue(root, opts, 0) + if e then + return nil, Err.new(Err.CORRUPT, e) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local HEADER = '\n\n\n' + +local function esc(s: string): (string?, string?) + if string.find(s, "[%z\1-\8\11\12\14-\31]") then + return nil, "strings cannot contain control characters" + end + s = string.gsub(string.gsub(s, "\r\n", "\n"), "\r", "\n") + return (string.gsub(s, "[&<>]", { ["&"] = "&", ["<"] = "<", [">"] = ">" })), nil +end + +local function keyLess(a: any, b: any): boolean + return a < b +end + +function Plist.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local sort = not (opts and opts.sortKeys == false) + local out: { string } = { HEADER } + local err: string? = nil + local function line(level: number, s: string) + table.insert(out, string.rep("\t", level) .. s .. "\n") + end + local write: (v: any, level: number, depth: number) -> boolean + function write(v: any, level: number, depth: number): boolean + if depth > 512 then + err = "nested deeper than 512 (a cycle?)" + return false + end + local tv = type(v) + if tv == "string" then + local s, e = esc(v) + if not s then + err = e + return false + end + line(level, "" .. s .. "") + elseif tv == "boolean" then + line(level, if v then "" else "") + elseif tv == "number" then + if v == math.floor(v) and math.abs(v) < 2 ^ 63 then + line(level, "" .. string.format("%d", v) .. "") + else + local s = Json.number(v) + if not s then + s = if v ~= v then "nan" elseif v > 0 then "inf" else "-inf" + end + line(level, "" .. s .. "") + end + elseif tv == "buffer" then + line(level, "") + local maxLine = math.max(16, 76 - 8 * level) + for l in string.gmatch(Base64.encode(v, maxLine // 4 * 3), "[^\n]+") do + line(level, l) + end + line(level, "") + elseif tv == "table" and Types.Date.is(v) then + local d = Types.Date.fromUnix(math.floor(Types.Date.toUnix(v))) + line(level, string.format("%04d-%02d-%02dT%02d:%02d:%02dZ", d.year :: number, d.month :: number, d.day :: number, d.hour :: number, d.minute :: number, d.second :: number)) + elseif tv == "table" and Binary.isUid(v) then + err = "UIDs can only be written to binary plists" + return false + elseif tv == "table" and v ~= Types.null then + local n = #v + local isArray = false + if not Types.isObject(v) then + local c = 0 + for _ in next, v do + c += 1 + end + isArray = c == n + end + if isArray then + if n == 0 then + line(level, "") + return true + end + line(level, "") + for k = 1, n do + if not write(v[k], level + 1, depth + 1) then + return false + end + end + line(level, "") + else + local keys: { any } + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + end + for _, k in keys do + if type(k) ~= "string" then + err = "dict keys must be strings" + return false + end + end + if sort and not Types.isObject(v) then + table.sort(keys, keyLess) + end + if #keys == 0 then + line(level, "") + return true + end + line(level, "") + for _, k in keys do + local ks, e = esc(k) + if not ks then + err = e + return false + end + line(level + 1, "" .. ks .. "") + if not write(v[k], level + 1, depth + 1) then + return false + end + end + line(level, "") + end + else + err = "cannot write " .. (if v == Types.null then "null" else "a " .. tv) .. " in a plist" + return false + end + return true + end + if not write(value, 0, 0) then + return nil, Err.new(Err.ARG, err or "cannot encode") + end + table.insert(out, "\n") + return buffer.fromstring(table.concat(out)), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Plist.uid = Binary.uid -- uid(n) -> a UID value (binary plists, NSKeyedArchiver) +Plist.isUid = Binary.isUid + +return Plist diff --git a/src/Formats/data/toml/Decode.luau b/src/Formats/data/toml/Decode.luau new file mode 100644 index 0000000..b03b941 --- /dev/null +++ b/src/Formats/data/toml/Decode.luau @@ -0,0 +1,643 @@ +--!strict +-- data/toml/Decode: the TOML 1.0.0 parser behind data/toml. Tables (and inline tables) are Types.object values with +-- their key order; arrays are arrays; datetimes are Types.Date values. Checks the 1.0 validity rules: UTF-8, control +-- characters, table / key redefinition (explicit, implicit, dotted, inline and array-of-tables), number grammar and +-- 64-bit range, escapes, datetimes. Never throws: failures return nil, message, offset (0-based). +local Types = require("@formats/Types") + +local Decode = {} + +local byte, sub, find, match, gsub, char = string.byte, string.sub, string.find, string.match, string.gsub, string.char + +export type Options = { + bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their digits (default "number") +} + +local function utf8char(c: number): string + if c < 0x80 then + return char(c) + elseif c < 0x800 then + return char(0xC0 + c // 64, 0x80 + c % 64) + elseif c < 0x10000 then + return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) + end + return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) +end + +local ESC: { [number]: string } = { [98] = "\b", [116] = "\t", [110] = "\n", [102] = "\f", [114] = "\r", [34] = '"', [92] = "\\" } + +-- digits with single underscores between them +local function digitsOk(d: string, class: string): boolean + return d ~= "" and not find(d, "__", 1, true) and byte(d, 1) ~= 95 and byte(d, #d) ~= 95 and find(d, "^[" .. class .. "_]+$") ~= nil +end + +function Decode.decode(s: string, opts: Options?): (any, any, number?) + local bigStrings = opts ~= nil and opts.bigInts == "string" + local errMsg: string = "" + local errAt = 0 + local function fail(msg: string, at: number): nil + errMsg, errAt = msg, at - 1 + return nil + end + + -- input checks: BOM, UTF-8, control characters, bare CR + if sub(s, 1, 3) == "\239\187\191" then + s = sub(s, 4) + end + do + local bad = find(s, "[%z\1-\8\11\12\14-\31\127]") + if bad then + return nil, "control character", bad - 1 + end + local cr = find(s, "\r[^\n]") or (if byte(s, #s) == 13 then #s else nil) + if cr then + return nil, "carriage return without a line feed", cr - 1 + end + if find(s, "[\128-\255]") then + if not utf8.len(s) then + return nil, "invalid UTF-8", 0 + end + local sur = find(s, "\237[\160-\191]") + if sur then + return nil, "invalid UTF-8 (surrogate)", sur - 1 + end + end + if find(s, "\r", 1, true) then + s = gsub(s, "\r\n", "\n") + end + end + local n = #s + + -- table bookkeeping: kind = "explicit" | "implicit" | "dotted" | "inline"; section = where dotted tables were made + local kinds: { [any]: string } = {} + local sections: { [any]: number } = {} + local aot: { [any]: boolean } = {} -- arrays of tables ([[x]]); other arrays are static + local arrays: { [any]: boolean } = {} + local section = 0 + local building: { any }? = nil -- tables created inside the inline table being parsed (frozen when it closes) + + local function newTable(kind: string): any + local t = Types.object({}, {}) + kinds[t] = kind + if building then + table.insert(building, t) + end + return t + end + + local function ws(i: number): number + return match(s, "^[ \t]*()", i) :: any + end + -- whitespace, newlines and comments (inside arrays) + local function wsnl(i: number): number + while true do + i = match(s, "^[ \t\n]*()", i) :: any + if byte(s, i) == 35 then + i = find(s, "\n", i, true) or (n + 1) + else + return i + end + end + end + + local function escape(p: number, parts: { string }): number? + local e = byte(s, p + 1) + local simple = if e then ESC[e] else nil + if simple then + table.insert(parts, simple) + return p + 2 + elseif e == 117 or e == 85 then + local len = if e == 117 then 4 else 8 + local h = match(s, "^" .. string.rep("%x", len), p + 2) + if not h then + return fail("bad unicode escape", p) + end + local cp = tonumber(h, 16) :: number + if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then + return fail("unicode escape is not a scalar value", p) + end + table.insert(parts, utf8char(cp)) + return p + 2 + len + end + return fail("bad escape", p) + end + + -- strings: value, next | nil + local function basic(i: number): (string?, number) + local parts = {} + local j = i + 1 + while true do + local p = find(s, '["\\\n]', j) + if not p or byte(s, p) == 10 then + return fail("unterminated string", p or n + 1), 0 + end + table.insert(parts, sub(s, j, p - 1)) + if byte(s, p) == 34 then + return table.concat(parts), p + 1 + end + local nj = escape(p, parts) + if not nj then + return nil, 0 + end + j = nj + end + end + local function multiBasic(i: number): (string?, number) + local j = i + 3 + if byte(s, j) == 10 then + j += 1 + end + local parts = {} + while true do + local p = find(s, '["\\]', j) + if not p then + return fail("unterminated multi-line string", i), 0 + end + table.insert(parts, sub(s, j, p - 1)) + if byte(s, p) == 34 then + if sub(s, p, p + 2) == '"""' then + local q = p + 3 + local extra = 0 + while byte(s, q) == 34 and extra < 2 do + extra += 1 + q += 1 + end + if byte(s, q) == 34 then + return fail("too many quotes", q), 0 + end + table.insert(parts, string.rep('"', extra)) + return table.concat(parts), q + end + table.insert(parts, '"') + j = p + 1 + else + local k = match(s, "^\\[ \t]*\n[ \t\n]*()", p) + if k then + j = k :: any + else + local nj = escape(p, parts) + if not nj then + return nil, 0 + end + j = nj + end + end + end + end + local function literal(i: number): (string?, number) + local e = find(s, "['\n]", i + 1) + if not e or byte(s, e) == 10 then + return fail("unterminated literal string", e or n + 1), 0 + end + return sub(s, i + 1, e - 1), e + 1 + end + local function multiLiteral(i: number): (string?, number) + local j = i + 3 + if byte(s, j) == 10 then + j += 1 + end + local e = find(s, "'''", j, true) + if not e then + return fail("unterminated multi-line literal string", i), 0 + end + local q = e + 3 + local extra = 0 + while byte(s, q) == 39 and extra < 2 do + extra += 1 + q += 1 + end + if byte(s, q) == 39 then + return fail("too many quotes", q), 0 + end + return sub(s, j, e - 1) .. string.rep("'", extra), q + end + + -- a (dotted) key: { parts }, next | nil + local function key(i: number): ({ string }?, number) + local keys = {} + while true do + i = ws(i) + local c = byte(s, i) + local k: string? + if c == 34 then + if sub(s, i, i + 2) == '"""' then + return fail("multi-line string as a key", i), 0 + end + k, i = basic(i) + elseif c == 39 then + if sub(s, i, i + 2) == "'''" then + return fail("multi-line string as a key", i), 0 + end + k, i = literal(i) + else + k = match(s, "^[%w_%-]+", i) + if k then + i += #k + else + return fail("expected a key", i), 0 + end + end + if k == nil then + return nil, 0 + end + table.insert(keys, k) + i = ws(i) + if byte(s, i) == 46 then + i += 1 + else + return keys, i + end + end + end + + -- numbers and datetimes + local function number(i: number): (any, number) + local tok = match(s, "^[%+%-]?[%w_%.]+", i) + if not tok then + return fail("expected a value", i), 0 + end + local last = byte(tok, #tok) + if (last == 101 or last == 69) and not find(tok, "^[%+%-]?0[xob]") then + local ext = match(s, "^[%+%-][%w_]*", i + #tok) + if ext then + tok ..= ext + end + end + local nexti = i + #tok + local sign, body = match(tok, "^([%+%-]?)(.*)$") + if body == "inf" or body == "nan" then + return (if body == "nan" then 0 / 0 elseif sign == "-" then -math.huge else math.huge), nexti + end + local prefix = sub(body :: string, 1, 2) + if prefix == "0x" or prefix == "0o" or prefix == "0b" then + if sign ~= "" then + return fail("sign on a non-decimal integer", i), 0 + end + local d = sub(body :: string, 3) + local class = if prefix == "0x" then "%x" elseif prefix == "0o" then "0-7" else "01" + if not digitsOk(d, class) then + return fail("bad integer", i), 0 + end + d = gsub(gsub(d, "_", ""), "^0+", "") + local over = if prefix == "0x" then #d > 16 or (#d == 16 and (tonumber(sub(d, 1, 1), 16) :: number) >= 8) + elseif prefix == "0o" then #d > 21 + else #d > 63 + if over then + return fail("integer out of 64-bit range", i), 0 + end + if d == "" then + return 0, nexti + end + local v = tonumber(d, if prefix == "0x" then 16 elseif prefix == "0o" then 8 else 2) :: number + if bigStrings and v >= 9007199254740992 then + return prefix .. d, nexti + end + return v, nexti + end + local ip, rest = match(body :: string, "^([%d_]+)(.*)$") + if not ip or not digitsOk(ip, "%d") then + return fail("bad number", i), 0 + end + local digits = gsub(ip, "_", "") + if #digits > 1 and byte(digits, 1) == 48 then + return fail("leading zero", i), 0 + end + if rest == "" then + local limit = if sign == "-" then "9223372036854775808" else "9223372036854775807" + if #digits > 19 or (#digits == 19 and digits > limit) then + return fail("integer out of 64-bit range", i), 0 + end + local v = tonumber(digits) :: number + if bigStrings and v >= 9007199254740992 then + return (if sign == "-" then "-" else "") .. digits, nexti + end + return if sign == "-" then -v else v, nexti + end + local text = sign .. digits + local frac, r2 = match(rest :: string, "^%.([%d_]*)(.*)$") + if frac then + if not digitsOk(frac, "%d") then + return fail("bad fraction", i), 0 + end + text ..= "." .. gsub(frac, "_", "") + rest = r2 + end + if rest ~= "" then + local es, ed = match(rest :: string, "^[eE]([%+%-]?)([%d_]*)$") + if not es or not digitsOk(ed, "%d") then + return fail("bad float", i), 0 + end + text ..= "e" .. es .. gsub(ed, "_", "") + end + local v = tonumber(text) + if v == nil then + return fail("bad float", i), 0 + end + return v, nexti + end + + local function datetime(i: number): (any, number) + local j = i + if match(s, "^%d%d%d%d%-%d%d%-%d%d", i) then + j = i + 10 + local c = byte(s, j) + if (c == 84 or c == 116 or c == 32) and match(s, "^%d%d:", j + 1) then + j += 1 + elseif c == 84 or c == 116 then + return fail("bad datetime", i), 0 + else + local d = Types.Date.parse(sub(s, i, j - 1)) + if not d then + return fail("bad date", i), 0 + end + return d, j + end + end + local t = match(s, "^%d%d:%d%d:%d%d", j) + if not t then + return fail("bad time (seconds are required)", j), 0 + end + j += 8 + local frac = match(s, "^%.%d+", j) + if frac then + j += #frac + elseif byte(s, j) == 46 then + return fail("bad fraction", j), 0 + end + if j - i > 19 or match(s, "^%d%d%d%d%-", i) then + local off = match(s, "^[Zz]", j) or match(s, "^[%+%-]%d%d:%d%d", j) + if off then + j += #off + end + end + local d = Types.Date.parse(sub(s, i, j - 1)) + if not d then + return fail("bad datetime", i), 0 + end + return d, j + end + + local value: (i: number) -> (any, number) + local assign: (tbl: any, keys: { string }, v: any, sid: number, at: number) -> boolean + + local function array(i: number): (any, number) + local arr = {} + arrays[arr] = true + i += 1 + while true do + i = wsnl(i) + local c = byte(s, i) + if c == 93 then + return arr, i + 1 + elseif c == nil then + return fail("unterminated array", i), 0 + end + local v, ni = value(i) + if v == nil then + return nil, 0 + end + table.insert(arr, v) + i = wsnl(ni) + c = byte(s, i) + if c == 44 then + i += 1 + elseif c == 93 then + return arr, i + 1 + else + return fail(if c == nil then "unterminated array" else "expected ',' or ']'", i), 0 + end + end + end + + local function inline(i: number): (any, number) + local outer = building + local mine = {} + building = mine + local t = newTable("inline") + section += 1 + local sid = section + i = ws(i + 1) + if byte(s, i) == 125 then + building = outer + return t, i + 1 + end + while true do + local keys, ni = key(i) + if not keys then + return nil, 0 + end + i = ws(ni) + if byte(s, i) ~= 61 then + return fail("expected '='", i), 0 + end + local v, vi = value(ws(i + 1)) + if v == nil then + return nil, 0 + end + if not assign(t, keys, v, sid, i) then + return nil, 0 + end + i = ws(vi) + local c = byte(s, i) + if c == 44 then + i = ws(i + 1) + if byte(s, i) == 125 then + return fail("trailing comma in an inline table", i), 0 + end + elseif c == 125 then + break + else + return fail(if c == 10 then "newline in an inline table" else "expected ',' or '}'", i), 0 + end + end + for _, x in mine do + kinds[x] = "inline" + end + building = outer + if outer then + for _, x in mine do + table.insert(outer, x) + end + end + return t, i + 1 + end + + function value(i: number): (any, number) + local c = byte(s, i) + if c == 34 then + if sub(s, i, i + 2) == '"""' then + return multiBasic(i) + end + return basic(i) + elseif c == 39 then + if sub(s, i, i + 2) == "'''" then + return multiLiteral(i) + end + return literal(i) + elseif c == 116 then + if match(s, "^true", i) and not match(s, "^[%w_%-]", i + 4) then + return true, i + 4 + end + elseif c == 102 then + if match(s, "^false", i) and not match(s, "^[%w_%-]", i + 5) then + return false, i + 5 + end + elseif c == 91 then + return array(i) + elseif c == 123 then + return inline(i) + elseif c and ((c >= 48 and c <= 57) or c == 43 or c == 45 or c == 105 or c == 110) then + if match(s, "^%d%d%d%d%-", i) or match(s, "^%d%d:", i) then + return datetime(i) + end + return number(i) + end + return fail(if c == nil or c == 10 then "expected a value" else "bad value", i), 0 + end + + function assign(tbl: any, keys: { string }, v: any, sid: number, at: number): boolean + local t = tbl + for j = 1, #keys - 1 do + local k = keys[j] + local x = t[k] + if x == nil then + local nt = newTable("dotted") + sections[nt] = sid + Types.set(t, k, nt) + t = nt + elseif kinds[x] == "implicit" or (kinds[x] == "dotted" and sections[x] == sid) then + t = x + else + fail("cannot add to " .. k .. " with a dotted key (already defined)", at) + return false + end + end + local k = keys[#keys] + if t[k] ~= nil then + fail("duplicate key " .. k, at) + return false + end + Types.set(t, k, v) + return true + end + + -- after a key / value or a header: spaces, an optional comment, then a newline or the end + local function eol(i: number): number? + i = ws(i) + local c = byte(s, i) + if c == 35 then + return find(s, "\n", i, true) or (n + 1) + elseif c == 10 or c == nil then + return i + end + return fail("expected the end of the line", i) + end + + local root = newTable("explicit") + local cur = root + local i = 1 + while true do + i = ws(i) + local c = byte(s, i) + if c == nil then + break + elseif c == 10 then + i += 1 + elseif c == 35 then + i = find(s, "\n", i, true) or (n + 1) + elseif c == 91 then + local at = i + local isAot = byte(s, i + 1) == 91 + local keys, ni = key(i + (if isAot then 2 else 1)) + if not keys then + return nil, errMsg, errAt + end + ni = ws(ni) + if isAot then + if sub(s, ni, ni + 1) ~= "]]" then + return nil, "expected ']]'", ni - 1 + end + ni += 2 + else + if byte(s, ni) ~= 93 then + return nil, "expected ']'", ni - 1 + end + ni += 1 + end + -- walk to the parent + local t = root + for j = 1, #keys - 1 do + local k = keys[j] + local x = t[k] + if x == nil then + local nt = newTable("implicit") + Types.set(t, k, nt) + t = nt + elseif kinds[x] and kinds[x] ~= "inline" then + t = x + elseif aot[x] then + t = x[#x] + else + return nil, "cannot define a table under " .. k .. " (already defined)", at - 1 + end + end + local k = keys[#keys] + local x = t[k] + if isAot then + local arr = x + if arr == nil then + arr = {} + aot[arr] = true + Types.set(t, k, arr) + elseif not aot[arr] then + return nil, "cannot define an array of tables " .. k .. " (already defined)", at - 1 + end + local nt = newTable("explicit") + table.insert(arr, nt) + cur = nt + else + if x == nil then + local nt = newTable("explicit") + Types.set(t, k, nt) + cur = nt + elseif kinds[x] == "implicit" then + kinds[x] = "explicit" + cur = x + else + return nil, "table " .. k .. " defined twice", at - 1 + end + end + section += 1 + local e = eol(ni) + if not e then + return nil, errMsg, errAt + end + i = e + else + local at = i + local keys, ni = key(i) + if not keys then + return nil, errMsg, errAt + end + ni = ws(ni) + if byte(s, ni) ~= 61 then + return nil, "expected '='", ni - 1 + end + local v, vi = value(ws(ni + 1)) + if v == nil then + return nil, errMsg, errAt + end + if not assign(cur, keys, v, section, at) then + return nil, errMsg, errAt + end + local e = eol(vi) + if not e then + return nil, errMsg, errAt + end + i = e + end + end + return root, nil, nil +end + +return Decode diff --git a/src/Formats/data/toml/Encode.luau b/src/Formats/data/toml/Encode.luau new file mode 100644 index 0000000..664e467 --- /dev/null +++ b/src/Formats/data/toml/Encode.luau @@ -0,0 +1,214 @@ +--!strict +-- data/toml/Encode: the TOML 1.0.0 writer behind data/toml. A table's plain values come first, then its sub-tables +-- as [a.b] sections and arrays of tables as [[a.b]]; keys in Types.object order (plain tables: sorted); strings as +-- basic strings with escapes; numbers as integers when integral (|x| < 2^63) else round-trip float text; Types.Date +-- values as datetimes. Never throws: bad values (null, buffers, functions, cycles, non-string keys) return nil, +-- message. +local Types = require("@formats/Types") +local Json = require("@formats/codecs/Json") + +local Encode = {} + +local format, gsub, find = string.format, string.gsub, string.find + +export type Options = { + inline: boolean?, -- write every sub-table as an inline table (default false: [sections]) + indent: (number | string)?, -- indent keys of nested sections (default none) +} + +local ESC: { [string]: string } = { ['"'] = '\\"', ["\\"] = "\\\\", ["\b"] = "\\b", ["\t"] = "\\t", ["\n"] = "\\n", ["\f"] = "\\f", ["\r"] = "\\r", ["\127"] = "\\u007F" } +for c = 0, 31 do + local ch = string.char(c) + if not ESC[ch] then + ESC[ch] = format("\\u%04X", c) + end +end + +local function quote(str: string): string + return '"' .. gsub(str, '[%z\1-\31"\\\127]', ESC) .. '"' +end +Encode.quote = quote + +local function keyText(k: string): string + if find(k, "^[%w_%-]+$") then + return k + end + return quote(k) +end + +-- isMap(t): a table written as a TOML table (Types.object, or keys other than 1..n); empty plain tables are arrays +local function isMap(t: { [any]: any }): boolean + if Types.isObject(t) then + return true + end + local n = #t + if n == 0 then + return next(t) ~= nil + end + local count = 0 + for _ in next, t do + count += 1 + end + return count ~= n +end + +local function isDate(v: any): boolean + return Types.Date.is(v) +end + +-- an array of tables: non-empty, every element a map +local function isAot(v: any): boolean + if type(v) ~= "table" or isDate(v) or isMap(v) or #v == 0 then + return false + end + for _, x in v do + if type(x) ~= "table" or isDate(x) or not isMap(x) then + return false + end + end + return true +end + +local function keysOf(t: { [any]: any }): ({ string }?, string?) + local keys = Types.keys(t) + for _, k in keys do + if type(k) ~= "string" then + return nil, "table key of type " .. type(k) + end + end + return keys :: any, nil +end + +type State = { seen: { [any]: boolean }, err: string? } + +local inlineValue: (st: State, v: any) -> string? + +local function scalar(st: State, v: any): string? + local tv = type(v) + if v == Types.null then + st.err = "TOML has no null" + return nil + elseif tv == "string" then + return quote(v) + elseif tv == "boolean" then + return if v then "true" else "false" + elseif tv == "number" then + if v ~= v then + return "nan" + elseif v == math.huge then + return "inf" + elseif v == -math.huge then + return "-inf" + elseif v == math.floor(v) and math.abs(v) < 2 ^ 63 then + return format("%d", v) + end + local t = Json.number(v) :: string + if not find(t, "[%.eEn]") then + t ..= ".0" + end + return t + elseif tv == "table" and isDate(v) then + return tostring(v) + elseif tv == "table" then + return inlineValue(st, v) + end + st.err = "cannot encode a " .. tv + return nil +end + +function inlineValue(st: State, v: any): string? + if st.seen[v] then + st.err = "a table contains itself" + return nil + end + st.seen[v] = true + local parts = {} + if isMap(v) then + local keys, kerr = keysOf(v) + if not keys then + st.err = kerr + return nil + end + for _, k in keys do + local s = scalar(st, v[k]) + if not s then + return nil + end + table.insert(parts, keyText(k) .. " = " .. s) + end + st.seen[v] = nil + return if #parts == 0 then "{}" else "{ " .. table.concat(parts, ", ") .. " }" + end + for i = 1, #v do + local s = scalar(st, v[i]) + if not s then + return nil + end + parts[i] = s + end + st.seen[v] = nil + return "[" .. table.concat(parts, ", ") .. "]" +end + +local function section(st: State, t: any, path: string, out: { string }, inlineAll: boolean, ind: string, depth: number): boolean + if st.seen[t] then + st.err = "a table contains itself" + return false + end + st.seen[t] = true + local keys, kerr = keysOf(t) + if not keys then + st.err = kerr + return false + end + local pad = string.rep(ind, depth) + local subs = {} + for _, k in keys do + local v = t[k] + if not inlineAll and type(v) == "table" and not isDate(v) and (isMap(v) or isAot(v)) then + table.insert(subs, k) + else + local s = scalar(st, v) + if not s then + return false + end + table.insert(out, pad .. keyText(k) .. " = " .. s .. "\n") + end + end + for _, k in subs do + local v = t[k] + local p = (if path == "" then "" else path .. ".") .. keyText(k) + if isMap(v) then + table.insert(out, (if #out > 0 then "\n" else "") .. pad .. "[" .. p .. "]\n") + if not section(st, v, p, out, inlineAll, ind, depth + 1) then + return false + end + else + for _, el in v do + table.insert(out, (if #out > 0 then "\n" else "") .. pad .. "[[" .. p .. "]]\n") + if not section(st, el, p, out, inlineAll, ind, depth + 1) then + return false + end + end + end + end + st.seen[t] = nil + return true +end + +-- encode(t, opts) -> text | nil, message +function Encode.encode(t: any, opts: Options?): (string?, string?) + if type(t) ~= "table" or isDate(t) or (not isMap(t) and next(t) ~= nil) then + return nil, "the top level must be a table with string keys" + end + local o: Options = opts or {} + local ind = if type(o.indent) == "number" then string.rep(" ", o.indent) elseif type(o.indent) == "string" then o.indent else "" + local st: State = { seen = {}, err = nil } + local out = {} + if not section(st, t, "", out, o.inline == true, ind, 0) then + return nil, st.err + end + return table.concat(out), nil +end + +return Encode diff --git a/src/Formats/data/toml/init.luau b/src/Formats/data/toml/init.luau new file mode 100644 index 0000000..093bca1 --- /dev/null +++ b/src/Formats/data/toml/init.luau @@ -0,0 +1,70 @@ +--!strict +-- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0). New code. Supports: decode of the whole 1.0 grammar (tables, +-- inline tables, arrays of tables, dotted keys, every string kind, integers in every base with the 64-bit range +-- check, floats incl. inf / nan, booleans, offset / local datetimes, local dates and times) with the validity rules +-- (redefinitions, UTF-8, control characters, number grammar), tested against toml-test; encode from plain tables / +-- Types.object (key order kept) / Types.Date. Tables decode to Types.object values (key order kept), datetimes to +-- Types.Date. Not supported: TOML 1.1 additions; the integer / float distinction is lost (Luau numbers: integral +-- values are written as integers). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Decode = require("@formats/data/toml/Decode") +local Encode = require("@formats/data/toml/Encode") + +-- ------------------------------------------------------------------------------------------------ contract +local Toml = { + name = "toml", + category = "data", + extensions = { "toml" }, + mime = { "application/toml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + caps = { decode = true, encode = true, ordered = true, dates = true }, +} + +export type DecodeOptions = Decode.Options +export type EncodeOptions = Encode.Options + +-- ------------------------------------------------------------------------------------------------ sniff +-- text that starts (after comments / blank lines) with a [table] header or a key = value line; INI looks the same, +-- so this stays low and the extension decides +function Toml.sniff(r: Bytes.Reader): number + local head = r:peek(512) + if string.find(head, "%z") then + return 0 + end + for line in string.gmatch(head, "[^\n]+") do + local l = string.match(line, "^[ \t]*(.-)[ \t\r]*$") :: string + if l ~= "" and string.sub(l, 1, 1) ~= "#" then + if string.match(l, "^%[%[?[%w_%-%.\"' ]+%]%]?$") or string.match(l, "^[%w_%-%.\"']+[ \t]*=[ \t]*[\"'%[{%dtf%+%-in]") then + return 0.2 + end + return 0 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Toml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + local v, msg, at = Decode.decode(s, opts) + if v == nil then + local m = tostring(msg) + local code = if string.find(m, "unterminated", 1, true) then Err.TRUNCATED else Err.CORRUPT + return nil, Err.new(code, m, at) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Toml.encode(value: any, opts: EncodeOptions?): (buffer?, 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 buffer.fromstring(s), nil +end + +return Toml diff --git a/src/Formats/data/xml/init.luau b/src/Formats/data/xml/init.luau new file mode 100644 index 0000000..c992418 --- /dev/null +++ b/src/Formats/data/xml/init.luau @@ -0,0 +1,57 @@ +--!strict +-- data/xml: XML 1.0 files, a thin wrapper over codecs/Xml (which see for the node shape and options). Supports: +-- decode to a "#document" XmlNode tree (doc.root = the root element), encode a document or an element. Not +-- supported: external entities / DTDs, validation. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Xml = require("@formats/codecs/Xml") + +-- ------------------------------------------------------------------------------------------------ contract +local XmlFormat = { + name = "xml", + category = "data", + extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, + mime = { "application/xml", "text/xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml" }, + caps = { decode = true, encode = true, namespaces = true, streaming = true }, +} + +export type DecodeOptions = Xml.DecodeOptions +export type EncodeOptions = Xml.EncodeOptions + +-- ------------------------------------------------------------------------------------------------ sniff +function XmlFormat.sniff(r: Bytes.Reader): number + local head = r:peek(64) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + if string.match(head, "^<%?xml[ \t\r\n]") or string.sub(head, 1, 4) == "\255\254<\0" or string.sub(head, 1, 4) == "\254\255\0<" then + return 0.5 + end + if string.match(head, "^[ \t\r\n]*<[%a!]") then + return 0.3 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function XmlFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.XmlNode?, Err.Err?) + return Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), opts) +end + +-- ------------------------------------------------------------------------------------------------ encode +function XmlFormat.encode(node: Types.XmlNode, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(node) ~= "table" or type(node.name) ~= "string" then + return nil, Err.new(Err.ARG, "expected an XmlNode") + end + local s, err = Xml.encode(node, opts) + if not s then + return nil, err + end + return buffer.fromstring(s), nil +end + +return XmlFormat diff --git a/src/Formats/data/yaml/Emit.luau b/src/Formats/data/yaml/Emit.luau new file mode 100644 index 0000000..6fbacac --- /dev/null +++ b/src/Formats/data/yaml/Emit.luau @@ -0,0 +1,339 @@ +--!strict +-- data/yaml/Emit: the YAML writer behind data/yaml. Block style; empty collections as [] / {}; strings plain when +-- they read back as the same string (core schema, and not a YAML 1.1 boolean like "yes"), literal block scalars +-- for multi-line text, double-quoted otherwise; numbers with the shortest round-trip text, .inf / .nan; buffers as +-- !!binary; dates as their RFC 3339 text; tables referenced twice get an anchor and aliases. Never throws: bad +-- values (cycles, functions, collection keys) return nil, message. +local Types = require("@formats/Types") +local Parse = require("@formats/data/yaml/Parse") + +local Emit = {} + +export type Options = { + indent: number?, -- spaces per level (default 2) + all: boolean?, -- the value is an array of documents, written with "---" separators + explicitStart: boolean?, -- start the (first) document with "---" (default false) + sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keys keep their order) + null: any?, -- the value written as null besides Types.null +} + +local format, byte, find, gsub = string.format, string.byte, string.find, string.gsub + +local YAML11 = { + y = true, Y = true, yes = true, Yes = true, YES = true, n = true, N = true, no = true, No = true, NO = true, + on = true, On = true, ON = true, off = true, Off = true, OFF = true, +} + +local function number(x: number): string + if x ~= x then + return ".nan" + elseif x == math.huge then + return ".inf" + elseif x == -math.huge then + return "-.inf" + elseif x == math.floor(x) and math.abs(x) < 2 ^ 53 then + if x == 0 and 1 / x < 0 then + return "-0.0" + end + return format("%d", x) + end + for _, f in { "%.15g", "%.16g", "%.17g" } do + local t = format(f, x) + if tonumber(t) == x then + if not find(t, "[%.eEn]") then + t ..= ".0" + end + return t + end + end + return format("%.17g", x) +end + +local DQ: { [string]: string } = { + ["\\"] = "\\\\", + ['"'] = '\\"', + ["\n"] = "\\n", + ["\t"] = "\\t", + ["\r"] = "\\r", + ["\0"] = "\\0", + ["\27"] = "\\e", +} +local function dquote(s: string): string + s = gsub(s, '[%z\1-\31\127\\"]', function(c: string): string + return DQ[c] or format("\\x%02x", byte(c)) + end) + -- the Unicode line / paragraph separators and NEL would be folded as line breaks: escape them + s = gsub(s, "\226\128\168", "\\L") + s = gsub(s, "\226\128\169", "\\P") + s = gsub(s, "\194\133", "\\N") + return '"' .. s .. '"' +end + +local function plainOk(s: string): boolean + if s == "" or YAML11[s] then + return false + end + if Parse.resolve(s, Types.null) ~= s then + return false + end + if find(s, "^[%s]") or find(s, "[%s]$") then + return false + end + if find(s, "^[%-%?:,%[%]{}#&%*!|>'\"%%@`]") or find(s, "^%.%.%.") then + return false + end + if find(s, ": ", 1, true) or find(s, " #", 1, true) or find(s, ":$") or find(s, "[%z\1-\31\127]") then + return false + end + if find(s, "\226\128\168") or find(s, "\226\128\169") or find(s, "\194\133") or find(s, "\239\187\191") then + return false + end + -- not invalid UTF-8 (the reader treats the text as bytes, but other tools will not) + if find(s, "[\128-\255]") and not utf8.len(s) then + return false + end + return true +end + +-- a string as a scalar on a line at indentation ind (for block scalars) +local function str(s: string, ind: string, key: boolean): string + if plainOk(s) then + return s + end + if not key and find(s, "\n", 1, true) and not find(s, "[%z\1-\9\11-\31\127]") and not find(s, "[ ]\n") and not find(s, " $") + and not find(s, "^[ \n]") and not find(s, "\226\128[\168\169]") and not find(s, "\194\133") and (not find(s, "[\128-\255]") or utf8.len(s)) + then + local trailing = #(string.match(s, "\n*$") :: string) + local body = string.sub(s, 1, #s - trailing) + local chomp = if trailing == 0 then "-" elseif trailing == 1 then "" else "+" + local lines = string.split(body, "\n") + local out = { "|" .. chomp } + for _, l in lines do + table.insert(out, if l == "" then "" else ind .. l) + end + for _ = 2, trailing do + table.insert(out, "") + end + return table.concat(out, "\n") + end + return dquote(s) +end + +local function b64(b: buffer): string + local A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + local out = {} + local n = buffer.len(b) + for i = 0, n - 1, 3 do + local a1 = buffer.readu8(b, i) + local a2 = if i + 1 < n then buffer.readu8(b, i + 1) else 0 + local a3 = if i + 2 < n then buffer.readu8(b, i + 2) else 0 + local v = a1 * 65536 + a2 * 256 + a3 + local c1, c2, c3, c4 = v // 262144, (v // 4096) % 64, (v // 64) % 64, v % 64 + table.insert(out, string.sub(A, c1 + 1, c1 + 1) .. string.sub(A, c2 + 1, c2 + 1) + .. (if i + 1 < n then string.sub(A, c3 + 1, c3 + 1) else "=") .. (if i + 2 < n then string.sub(A, c4 + 1, c4 + 1) else "=")) + end + return table.concat(out) +end + +local function isArray(t: { [any]: any }): boolean + if Types.isObject(t) then + return false + end + local n = #t + if n == 0 then + return next(t) == nil + end + if next(t, n) ~= nil then + return false + end + local c = 0 + for _ in next, t do + c += 1 + end + return c == n +end + +local function keyLess(a: any, b: any): boolean + local ta, tb = type(a), type(b) + if ta ~= tb then + return ta < tb + end + if ta == "number" or ta == "string" then + return a < b + end + return tostring(a) < tostring(b) +end + +type St = { out: { string }, step: number, sort: boolean, null: any, refs: { [any]: number }, anchors: { [any]: string }, nextId: number, err: string? } + +-- count references to tables (anchors for those seen twice); false on a cycle +local function count(st: St, v: any, onStack: { [any]: boolean }): boolean + if type(v) ~= "table" or v == Types.null or v == st.null or Types.Date.is(v) then + return true + end + if onStack[v] then + st.err = "a cycle (YAML aliases cannot point at their own ancestors here)" + return false + end + local r = st.refs[v] + st.refs[v] = (r or 0) + 1 + if r then + return true + end + onStack[v] = true + for k, x in next, v do + if not count(st, k, onStack) or not count(st, x, onStack) then + return false + end + end + onStack[v] = nil + return true +end + +-- scalar text for a non-collection value, or nil +local function scalar(st: St, v: any, ind: string, key: boolean): string? + local tv = type(v) + if v == nil or v == Types.null or (st.null ~= nil and v == st.null) then + return "null" + elseif tv == "boolean" then + return if v then "true" else "false" + elseif tv == "number" then + return number(v) + elseif tv == "string" then + return str(v, ind, key) + elseif tv == "buffer" then + return "!!binary " .. b64(v) + elseif tv == "table" and Types.Date.is(v) then + return tostring(v) + end + return nil +end + +local write: (st: St, v: any, depth: number) -> string? + +-- the text of v as a node whose first line follows "key:" / "- " (it starts with a space or a newline) +function write(st: St, v: any, depth: number): string? + local ind = string.rep(" ", st.step * (depth + 1)) + local s = scalar(st, v, ind, false) + if s then + return " " .. s + end + if type(v) ~= "table" then + st.err = "cannot write a " .. type(v) + return nil + end + local prefix = "" + if st.refs[v] and st.refs[v] > 1 then + local a = st.anchors[v] + if a then + return " *" .. a + end + st.nextId += 1 + a = "id" .. format("%03d", st.nextId) + st.anchors[v] = a + prefix = " &" .. a + end + local pad = string.rep(" ", st.step * depth) + if isArray(v) and not Types.isObject(v) then + if #v == 0 then + return prefix .. " []" + end + local parts = {} + for _, x in v do + local t = write(st, x, depth + 1) + if not t then + return nil + end + table.insert(parts, pad .. "-" .. t) + end + return prefix .. "\n" .. table.concat(parts, "\n") + end + local keys + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + if #keys == 0 then + return prefix .. " {}" + end + local parts = {} + for _, k in keys do + local ks = scalar(st, k, "", true) + if not ks or (type(k) == "table" and not Types.Date.is(k) and k ~= Types.null) then + st.err = "mapping keys must be scalars" + return nil + end + local t = write(st, v[k], depth + 1) + if not t then + return nil + end + table.insert(parts, pad .. ks .. ":" .. t) + end + return prefix .. "\n" .. table.concat(parts, "\n") +end + +local function document(st: St, v: any): string? + local t = write(st, v, 0) + if not t then + return nil + end + -- the top level: drop the separator write() put before the first line + if string.sub(t, 1, 1) == "\n" then + return string.sub(t, 2) + end + local body = string.sub(t, 2) + if string.sub(body, 1, 1) == "&" then + -- "&id001\n- a": an anchored top-level collection + return body + end + return body +end + +-- encode(v, opts) -> text | nil, message +function Emit.encode(v: any, opts: Options?): (string?, string?) + local o: Options = opts or {} + local st: St = { + out = {}, + step = math.clamp(math.floor(o.indent or 2), 1, 10), + sort = o.sortKeys ~= false, + null = o.null, + refs = {}, + anchors = {}, + nextId = 0, + err = nil, + } + local docs = if o.all then v else { v } + if type(docs) ~= "table" then + return nil, "all: expected an array of documents" + end + local parts = {} + for i, d in docs do + st.refs, st.anchors = {}, {} + if not count(st, d, {}) then + return nil, st.err + end + local t = document(st, d) + if not t then + return nil, st.err + end + local start = i > 1 or o.explicitStart + if start then + -- a scalar / [] / {} can share the "---" line; a collection starts on the next one + local block = type(d) == "table" and d ~= Types.null and not Types.Date.is(d) and next(d) ~= nil + local sep = if block and not string.find(t, "^&") then "---\n" else "--- " + table.insert(parts, sep .. t .. "\n") + else + table.insert(parts, t .. "\n") + end + end + return table.concat(parts), nil +end + +return Emit diff --git a/src/Formats/data/yaml/Parse.luau b/src/Formats/data/yaml/Parse.luau new file mode 100644 index 0000000..fc84c87 --- /dev/null +++ b/src/Formats/data/yaml/Parse.luau @@ -0,0 +1,1360 @@ +--!strict +-- data/yaml/Parse: the YAML 1.2 parser behind data/yaml. Recursive descent over the text (line breaks normalized): +-- block mappings / sequences (compact forms included), flow collections, plain / single / double-quoted scalars with +-- line folding, literal / folded block scalars (indentation and chomping indicators), anchors and aliases (shared +-- references, with an expansion-size limit), tags (core types + !!binary, !!timestamp; others UNSUPPORTED unless +-- opts.tags = "ignore"), %YAML / %TAG directives, multi-document streams, comments. Scalars resolve with the core +-- schema. Not supported: complex keys ("? "), collections as keys, recursive aliases, merge keys "<<" (kept as a +-- normal key). Internally raises { yamlErr } tables caught by run(); never throws past it. +local Types = require("@formats/Types") + +local Parse = {} + +local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char + +export type Options = { + all: boolean?, -- every document as an array (default false: the first document; none -> Types.null) + tags: ("error" | "ignore")?, -- unknown tags: an UNSUPPORTED error (default) or resolved as if untagged + maxAliasNodes: number?, -- the total size of aliased nodes (default 1e6): the billion laughs guard + maxDepth: number?, -- nesting limit (default 500) + null: any?, -- the value for null (default Types.null) +} + +type St = { + s: string, + n: number, + anchors: { [string]: any }, + handles: { [string]: string }, + depth: number, + maxDepth: number, + aliasNodes: number, + maxAlias: number, + sizes: { [any]: number }, + ignoreTags: boolean, + null: any, +} + +local CORE = "tag:yaml.org,2002:" + +local function raise(code: string, msg: string, p: number) + error({ yamlErr = true, code = code, msg = msg, at = p - 1 }, 0) +end +local function corrupt(msg: string, p: number) + raise("CORRUPT", msg, p) +end + +-- ------------------------------------------------------------------------------------------------ helpers +local function col(s: string, p: number): number + local q = p + while q > 1 and byte(s, q - 1) ~= 10 do + q -= 1 + end + return p - q +end + +local function isWsEnd(c: number?): boolean -- space, tab, newline or the end + return c == nil or c == 32 or c == 9 or c == 10 +end + +local function docMarker(s: string, p: number): boolean + if p ~= 1 and byte(s, p - 1) ~= 10 then + return false + end + local m = sub(s, p, p + 2) + return (m == "---" or m == "...") and isWsEnd(byte(s, p + 3)) +end + +-- skip spaces, tabs, comments and line breaks: the next content position (n + 1 at the end) +local function skip(s: string, p: number): number + local n = #s + while p <= n do + local c = byte(s, p) + if c == 32 or c == 9 or c == 10 then + p += 1 + elseif c == 35 and (p == 1 or isWsEnd(byte(s, p - 1))) then + local e = find(s, "\n", p, true) + if not e then + return n + 1 + end + p = e + 1 + else + return p + end + end + return p +end + +-- the number of leading spaces on p's line, and whether a tab comes before p on it +local function lineIndent(s: string, p: number): (number, boolean) + local q = p + while q > 1 and byte(s, q - 1) ~= 10 do + q -= 1 + end + local sp = (match(s, "^ *()", q) :: number) - q + return sp, find(sub(s, q, p - 1), "\t", 1, true) ~= nil +end + +-- block content at p on a new line must not be indented with tabs: a tab before p is an error when the spaces before +-- it do not already indent the line past ind (siblings: pass ind = their column - 1... any tab is an error) +local function noTabs(s: string, p: number, ind: number?) + local sp, tab = lineIndent(s, p) + if tab and (ind == nil or sp <= ind) then + error({ yamlErr = true, code = "CORRUPT", msg = "tab in indentation", at = p - 1 }, 0) + end +end + +-- skip spaces / tabs on the line +local function skipLine(s: string, p: number): number + return match(s, "^[ \t]*()", p) :: any +end + +-- after a node on its line: only spaces and a comment may follow before the line break +local function endOfLine(s: string, p: number): boolean + local q = skipLine(s, p) + local c = byte(s, q) + return c == nil or c == 10 or (c == 35 and q > p) +end + +local function utf8char(c: number): string + if c < 0x80 then + return char(c) + elseif c < 0x800 then + return char(0xC0 + c // 64, 0x80 + c % 64) + elseif c < 0x10000 then + return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) + end + return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) +end + +-- ------------------------------------------------------------------------------------------------ resolution +-- the core schema: a plain scalar's value +function Parse.resolve(t: string, nullv: any): any + if t == "" or t == "~" or t == "null" or t == "Null" or t == "NULL" then + return nullv + end + local c = byte(t) + if c == 116 or c == 84 or c == 102 or c == 70 then + if t == "true" or t == "True" or t == "TRUE" then + return true + elseif t == "false" or t == "False" or t == "FALSE" then + return false + end + return t + end + if not ((c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46) then + return t + end + if match(t, "^[-+]?%d+$") then + return tonumber(if c == 43 then sub(t, 2) else t) + end + local o = match(t, "^0o([0-7]+)$") + if o then + return tonumber(o, 8) + end + local x = match(t, "^0x(%x+)$") + if x then + return tonumber(x, 16) + end + if match(t, "^[-+]?%d+%.?%d*$") or match(t, "^[-+]?%.%d+$") or match(t, "^[-+]?%d+%.?%d*[eE][-+]?%d+$") or match(t, "^[-+]?%.%d+[eE][-+]?%d+$") then + local v = tonumber(if c == 43 then sub(t, 2) else t) + if v then + return v + end + end + local inf = match(t, "^([-+]?)%.[iI][nN][fF]$") + if inf and (t == inf .. ".inf" or t == inf .. ".Inf" or t == inf .. ".INF") then + return if inf == "-" then -math.huge else math.huge + end + if t == ".nan" or t == ".NaN" or t == ".NAN" then + return 0 / 0 + end + return t +end + +local B64: { [number]: number } = {} +do + local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + for i = 1, 64 do + B64[byte(alphabet, i)] = i - 1 + end +end +local function base64(t: string): buffer? + t = string.gsub(t, "[%s]", "") + t = string.gsub(t, "=+$", "") + local n = #t + if n % 4 == 1 then + return nil + end + local out = buffer.create(n * 3 // 4) + local o = 0 + local acc, bits = 0, 0 + for i = 1, n do + local v = B64[byte(t, i)] + if v == nil then + return nil + end + acc = acc * 64 + v + bits += 6 + if bits >= 8 then + bits -= 8 + local b = acc // (2 ^ bits) + buffer.writeu8(out, o, b) + o += 1 + acc -= b * 2 ^ bits + end + end + return out +end + +-- a scalar's value given its tag (nil = untagged, "!" = non-specific) +local function scalarValue(st: St, raw: string, plain: boolean, tag: string?, p: number): any + if tag == nil then + return if plain then Parse.resolve(raw, st.null) else raw + end + if tag == "!" or tag == CORE .. "str" then + return raw + end + if sub(tag, 1, #CORE) == CORE then + local kind = sub(tag, #CORE + 1) + local v = Parse.resolve(raw, st.null) + if kind == "null" then + if v ~= st.null then + corrupt("bad !!null " .. raw, p) + end + return v + elseif kind == "bool" then + if type(v) ~= "boolean" then + corrupt("bad !!bool " .. raw, p) + end + return v + elseif kind == "int" then + if type(v) ~= "number" or not (match(raw, "^[-+]?%d+$") or match(raw, "^0[ox]")) then + corrupt("bad !!int " .. raw, p) + end + return v + elseif kind == "float" then + if type(v) ~= "number" then + corrupt("bad !!float " .. raw, p) + end + return v + elseif kind == "binary" then + local b = base64(raw) + if not b then + corrupt("bad !!binary data", p) + end + return b + elseif kind == "timestamp" then + local d = Types.Date.parse(raw) + if not d then + corrupt("bad !!timestamp " .. raw, p) + end + return d + elseif kind == "map" or kind == "seq" then + corrupt("!!" .. kind .. " on a scalar", p) + end + end + if st.ignoreTags then + return if plain then Parse.resolve(raw, st.null) else raw + end + raise("UNSUPPORTED", "tag " .. tag, p) + return nil +end + +local function collectionTag(st: St, tag: string?, kind: string, p: number) + if tag == nil or tag == "!" or tag == CORE .. kind then + return + end + if sub(tag, 1, #CORE) == CORE then + local k = sub(tag, #CORE + 1) + if k == "map" or k == "seq" or k == "str" or k == "int" or k == "float" or k == "bool" or k == "null" or k == "binary" then + corrupt("!!" .. k .. " on a " .. kind, p) + end + end + if not st.ignoreTags then + raise("UNSUPPORTED", "tag " .. tag, p) + end +end + +-- expansion size of a value (nodes), memoized +local function size(st: St, v: any): number + if type(v) ~= "table" or v == st.null then + return 1 + end + local m = st.sizes[v] + if m then + return m + end + local total = 1 + for k, x in next, v do + total += size(st, k) + size(st, x) + end + st.sizes[v] = total + return total +end + +-- ------------------------------------------------------------------------------------------------ properties +type Props = { anchor: string?, tag: string?, at: number } + +-- anchors / tags at p -> props?, the position after them (and the spaces after them) +local function properties(st: St, p: number): (Props?, number) + local s = st.s + local props: Props? = nil + while true do + local c = byte(s, p) + if c == 38 then -- & + local name = match(s, "^&([^%s,%[%]{}]+)", p) + if not name then + corrupt("bad anchor", p) + end + local pr: Props = props or { at = p } + props = pr + if pr.anchor then + corrupt("two anchors on one node", p) + end + pr.anchor = name + p = skipLine(s, p + 1 + #(name :: string)) + elseif c == 33 then -- ! + local pr: Props = props or { at = p } + props = pr + if pr.tag then + corrupt("two tags on one node", p) + end + local tag: string + if byte(s, p + 1) == 60 then -- ! + local v = match(s, "^!<([^>%s]+)>", p) + if not v then + corrupt("bad verbatim tag", p) + end + tag = v :: string + p += #tag + 3 + else + local handle, suffix = match(s, "^(![%w%-]*!)([^%s,%[%]{}]*)", p) + if handle then + local prefix = st.handles[handle] + if not prefix then + corrupt("undefined tag handle " .. handle, p) + end + if suffix == "" then + corrupt("empty tag", p) + end + tag = prefix .. string.gsub(suffix :: string, "%%(%x%x)", function(h: string): string + return char(tonumber(h, 16) :: number) + end) + else + local sfx = match(s, "^!([^%s,%[%]{}]*)", p) :: string + if sfx == "" then + tag = "!" + else + tag = st.handles["!"] .. sfx + end + end + p += #(match(s, "^![^%s,%[%]{}]*", p) :: string) + end + pr.tag = tag + if not isWsEnd(byte(s, p)) and byte(s, p) ~= 44 and byte(s, p) ~= 93 and byte(s, p) ~= 125 then + corrupt("bad tag", p) + end + p = skipLine(s, p) + else + return props, p + end + end +end + +local function finish(st: St, props: Props?, v: any): any + if props and props.anchor then + st.anchors[props.anchor] = v + end + return v +end + +local function alias(st: St, p: number): (any, number) + local s = st.s + local name = match(s, "^%*([^%s,%[%]{}]+)", p) + if not name then + corrupt("bad alias", p) + end + local v = st.anchors[name :: string] + if v == nil then + corrupt("undefined alias *" .. (name :: string), p) + end + st.aliasNodes += size(st, v) + if st.aliasNodes > st.maxAlias then + raise("LIMIT", "alias expansion over " .. st.maxAlias .. " nodes", p) + end + return v, p + 1 + #(name :: string) +end + +-- ------------------------------------------------------------------------------------------------ scalars +-- fold the line break(s) at p (p at a '\n'): the text they become and the position of the next line's content. +-- Lines holding only spaces / tabs count as empty. +local function fold(s: string, p: number): (string, number) + local empties = 0 + local q = p + 1 + while true do + local r = skipLine(s, q) + if byte(s, r) == 10 then + empties += 1 + q = r + 1 + else + return (if empties == 0 then " " else string.rep("\n", empties)), q + end + end +end + +local ESC: { [number]: string } = { + [48] = "\0", + [97] = "\a", + [98] = "\b", + [116] = "\t", + [9] = "\t", + [110] = "\n", + [118] = "\v", + [102] = "\f", + [114] = "\r", + [101] = "\27", + [32] = " ", + [34] = '"', + [47] = "/", + [92] = "\\", + [78] = "\194\133", + [95] = "\194\160", + [76] = "\226\128\168", + [80] = "\226\128\169", +} + +-- a quoted scalar at p ('"' or "'") -> text, the position after the closing quote +local function quoted(st: St, p: number, ind: number): (string, number) + local s = st.s + local dq = byte(s, p) == 34 + local parts: { string } = {} + local i = p + 1 + local stop = if dq then '[\\"\n]' else "['\n]" + while true do + local j = find(s, stop, i) + if not j then + raise("TRUNCATED", "unterminated quoted scalar", p) + end + local jj = j :: number + local seg = sub(s, i, jj - 1) + local c = byte(s, jj) + if c == 10 then + table.insert(parts, (string.gsub(seg, "[ \t]+$", ""))) + local f, q = fold(s, jj) + if docMarker(s, q) then + corrupt("document marker inside a quoted scalar", q) + end + if ind >= 0 and (match(s, "^ *()", q) :: number) - q <= ind then + corrupt("a quoted scalar's continuation line is not indented", q) + end + table.insert(parts, f) + i = skipLine(s, q) + elseif dq and c == 92 then + table.insert(parts, seg) + local e = byte(s, jj + 1) + if e == 10 then -- escaped line break: joined without a space + local r = jj + 2 + while true do + local q = skipLine(s, r) + if byte(s, q) == 10 then + table.insert(parts, "\n") + r = q + 1 + else + i = q + break + end + end + elseif e == 120 or e == 117 or e == 85 then + local len = if e == 120 then 2 elseif e == 117 then 4 else 8 + local h = sub(s, jj + 2, jj + 1 + len) + if #h ~= len or not match(h, "^%x+$") then + corrupt("bad escape", jj) + end + local cp = tonumber(h, 16) :: number + if cp > 0x10FFFF then + corrupt("bad escape", jj) + end + table.insert(parts, utf8char(cp)) + i = jj + 2 + len + else + local r = if e then ESC[e] else nil + if not r then + corrupt("bad escape", jj) + end + table.insert(parts, r :: string) + i = jj + 2 + end + elseif not dq and byte(s, jj + 1) == 39 then + table.insert(parts, seg .. "'") + i = jj + 2 + else + table.insert(parts, seg) + return table.concat(parts), jj + 1 + end + end +end + +-- a plain scalar at p -> text, the position after it. ind: continuation lines must be indented deeper than ind +-- (block context); flow: the flow-context rules (stops at , [ ] { }). +local function plain(st: St, p: number, ind: number, flow: boolean): (string, number) + local s = st.s + local parts: { string } = {} + local i = p + local lastEnd = p + while true do + -- one line's worth + local j = i + local stopAt = nil + while true do + local c = byte(s, j) + if c == nil or c == 10 then + break + elseif c == 58 then -- : + local d = byte(s, j + 1) + if isWsEnd(d) or (flow and (d == 44 or d == 91 or d == 93 or d == 123 or d == 125)) then + stopAt = j + break + end + elseif c == 35 and (byte(s, j - 1) == 32 or byte(s, j - 1) == 9) then + stopAt = j + break + elseif flow and (c == 44 or c == 91 or c == 93 or c == 123 or c == 125) then + stopAt = j + break + end + j += 1 + end + local seg = string.gsub(sub(s, i, j - 1), "[ \t]+$", "") + table.insert(parts, seg) + lastEnd = i + #seg + if stopAt or byte(s, j) == nil then + return table.concat(parts), lastEnd + end + -- a continuation line? + local f, q = fold(s, j) + local r = skipLine(s, q) + local c = byte(s, r) + if c == nil or docMarker(s, q) or c == 35 or (not flow and (match(s, "^ *()", q) :: number) - q <= ind) then + return table.concat(parts), lastEnd + end + if flow and (c == 44 or c == 93 or c == 125 or (c == 58 and isWsEnd(byte(s, r + 1)))) then + return table.concat(parts), lastEnd + end + table.insert(parts, f) + i = r + end +end + +-- a block scalar at p ('|' or '>'); ind = the parent's indentation -> text, the position after it +local function blockScalar(st: St, p: number, ind: number): (string, number) + local s = st.s + local folded = byte(s, p) == 62 + local q = p + 1 + local explicit: number? = nil + local chomp = "clip" + for _ = 1, 2 do + local c = byte(s, q) + if c and c >= 49 and c <= 57 and not explicit then + explicit = c - 48 + q += 1 + elseif (c == 43 or c == 45) and chomp == "clip" then + chomp = if c == 43 then "keep" else "strip" + q += 1 + end + end + if not endOfLine(s, q) then + corrupt("bad block scalar header", q) + end + local nl = find(s, "\n", q, true) + local lines: { string } = {} + local trailing = 0 -- empty lines after the last content line + if not nl then + return "", #s + 1 + end + local ls = (nl :: number) + 1 + local indent: number + if explicit then + indent = math.max(ind + explicit, 0) -- n + the indicator (n = -1 at the top level) + else + -- auto-detect: the first non-empty line; leading empty lines may not be longer + local maxEmpty = 0 + local r = ls + indent = -1 + while true do + local sp = (match(s, "^ *()", r) :: number) - r + local c = byte(s, r + sp) + if c == 10 then + maxEmpty = math.max(maxEmpty, sp) + r = r + sp + 1 + elseif c == nil then + maxEmpty = math.max(maxEmpty, sp) + indent = math.max(maxEmpty, ind + 1) + break + else + if docMarker(s, r) then + indent = math.max(maxEmpty, ind + 1) + break + end + indent = sp + if sp < maxEmpty then + corrupt("leading empty lines indented more than the block scalar", r) + end + break + end + end + if indent <= ind then + indent = ind + 1 + end + end + -- the lines + local r = ls + local pendingEmpty = 0 + local endPos = ls + while r <= #s do + if docMarker(s, r) then + break + end + local sp = (match(s, "^ *()", r) :: number) - r + local e = find(s, "\n", r, true) or (#s + 1) + if sp >= indent then + local text = sub(s, r + indent, e - 1) + for _ = 1, pendingEmpty do + table.insert(lines, "") + end + pendingEmpty = 0 + table.insert(lines, text) + elseif r + sp == e then + pendingEmpty += 1 + else + if byte(s, r + sp) == 9 then + corrupt("tab in block scalar indentation", r + sp) + end + break + end + r = e + 1 + endPos = math.min(r, #s + 1) + end + trailing = pendingEmpty + local body: string + if #lines == 0 then + body = "" + elseif not folded then + body = table.concat(lines, "\n") + else + local out: { string } = {} + local prevMore = false + local empties = 0 + local first = true + for _, l in lines do + if l == "" then + empties += 1 + else + local more = byte(l) == 32 or byte(l) == 9 + if first then + table.insert(out, string.rep("\n", empties)) + elseif empties == 0 then + table.insert(out, if more or prevMore then "\n" else " ") + else + table.insert(out, string.rep("\n", if more or prevMore then empties + 1 else empties)) + end + table.insert(out, l) + first = false + prevMore = more + empties = 0 + end + end + trailing += empties -- empty lines after the last content line (or all of them) + body = table.concat(out) + end + if not folded then + -- literal: trailing "" lines inside `lines` are content-indented empty lines; count them as trailing + local k = #lines + while k > 0 and lines[k] == "" do + k -= 1 + trailing += 1 + end + body = table.concat(lines, "\n", 1, k) + if k == 0 then + body = "" + end + lines = table.move(lines, 1, k, 1, {}) + end + local hasContent = false + for _, l in lines do + if l ~= "" then + hasContent = true + break + end + end + if chomp == "strip" then + return body, endPos + elseif chomp == "clip" then + return (if hasContent then body .. "\n" else ""), endPos + end + return (if hasContent then body .. "\n" else "") .. string.rep("\n", trailing), endPos +end + +-- ------------------------------------------------------------------------------------------------ flow +local parseFlow: (st: St, p: number, ind: number) -> (any, number) + +local function enter(st: St, p: number) + st.depth += 1 + if st.depth > st.maxDepth then + raise("LIMIT", "nested deeper than " .. st.maxDepth, p) + end +end + +-- a flow node at p (after skip) -> value, next, wasEmpty +local function flowNode(st: St, p: number, ind: number): (any, number, boolean) + local s = st.s + local props, q = properties(st, p) + if props then + q = skip(s, q) + end + local c = byte(s, q) + local v: any + if c == 42 then -- * + if props then + corrupt("properties on an alias", q) + end + return alias(st, q) + elseif c == 91 or c == 123 then + v, q = parseFlow(st, q, ind) + collectionTag(st, props and props.tag, if c == 91 then "seq" else "map", q) + return finish(st, props, v), q, false + elseif c == 34 or c == 39 then + local t, r = quoted(st, q, ind) + return finish(st, props, scalarValue(st, t, false, props and props.tag, q)), r, false + elseif c == nil or c == 44 or c == 93 or c == 125 or (c == 58 and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125)) then + -- an empty node + return finish(st, props, scalarValue(st, "", true, props and props.tag, q)), (if props then q else p), true + elseif c == 35 or c == 38 or c == 33 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 then + corrupt("unexpected character in a flow collection", q) + elseif (c == 45 or c == 63 or c == 58) and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125) then + if c == 63 then + raise("UNSUPPORTED", "explicit keys (?) in flow collections", q) + end + corrupt("unexpected '" .. char(c :: number) .. "' in a flow collection", q) + end + local t, r = plain(st, q, ind, true) + return finish(st, props, scalarValue(st, t, true, props and props.tag, q)), r, false +end + +local function checkKey(st: St, k: any, p: number): any + if type(k) == "table" and k ~= st.null and not Types.Date.is(k) then + raise("UNSUPPORTED", "collections as mapping keys", p) + end + if k ~= k then + corrupt("NaN as a mapping key", p) + end + return k +end + +function parseFlow(st: St, p: number, ind: number): (any, number) + local s = st.s + enter(st, p) + local isMap = byte(s, p) == 123 + local close = if isMap then 125 else 93 + local t: { [any]: any } = {} + local order: { any } = {} + local count = 0 + local q = p + 1 + local function flowSkip(from: number): number + local r = skip(s, from) + if ind >= 0 and r <= #s and find(sub(s, from, r), "\n", 1, true) and (lineIndent(s, r)) <= ind then + corrupt("a flow collection's line is not indented", r) + end + return r + end + while true do + q = flowSkip(q) + local c = byte(s, q) + if c == nil then + raise("TRUNCATED", "unterminated flow collection", p) + end + if docMarker(s, q) then + corrupt("document marker inside a flow collection", q) + end + if c == close then + q += 1 + break + end + local explicitKey = false + if c == 63 and isWsEnd(byte(s, q + 1)) then + explicitKey = true + q = flowSkip(q + 1) + end + local startLine = q + local k, r, empty = flowNode(st, q, ind) + r = flowSkip(r) + local hasColon = false + if byte(s, r) == 58 then + local d = byte(s, r + 1) + local jsonLike = byte(s, q) == 34 or byte(s, q) == 39 or byte(s, q) == 91 or byte(s, q) == 123 + if isWsEnd(d) or d == 44 or d == 93 or d == 125 or jsonLike then + hasColon = true + -- an implicit key must sit on one line + if not isMap and not explicitKey and find(sub(s, startLine, r), "\n", 1, true) then + corrupt("multi-line implicit key", startLine) + end + r += 1 + end + end + if isMap then + local v: any = st.null + if hasColon then + local r2 = flowSkip(r) + local cc = byte(s, r2) + if cc ~= 44 and cc ~= 125 then + v, r = flowNode(st, r2, ind) + end + end + if empty and not hasColon and not explicitKey then + corrupt("expected a mapping entry", q) + end + k = checkKey(st, k, q) + if t[k] == nil then + table.insert(order, k) + end + t[k] = v + else + local item = k + if hasColon or explicitKey then + local v: any = st.null + local r2 = if hasColon then flowSkip(r) else r + local cc = byte(s, r2) + if hasColon and cc ~= 44 and cc ~= 93 then + v, r = flowNode(st, r2, ind) + end + k = checkKey(st, k, q) + item = Types.object({ [k] = v }, { k }) + elseif empty then + corrupt("empty sequence entry", q) + end + count += 1 + t[count] = item + end + r = flowSkip(r) + local cc = byte(s, r) + if cc == 44 then + q = r + 1 + elseif cc == close then + q = r + 1 + break + elseif cc == nil then + raise("TRUNCATED", "unterminated flow collection", p) + else + corrupt(if isMap then "expected ',' or '}'" else "expected ',' or ']'", r) + end + end + st.depth -= 1 + if isMap then + return Types.object(t, order), q + end + return t, q +end + +-- ------------------------------------------------------------------------------------------------ block +local blockNode: (st: St, ind: number, p: number, inline: boolean, mapParent: boolean) -> (any, number) + +-- an implicit key at p (on one line, followed by ':' and a space / the end of the line) -> key, position after ':' +local function implicitKey(st: St, p: number): (any, number?) + local s = st.s + local c = byte(s, p) + if c == 34 or c == 39 then + local ok, t, q = pcall(quoted, st, p, -1) + if not ok then + return nil, nil + end + if find(sub(s, p, q - 1), "\n", 1, true) then + return nil, nil + end + local r = skipLine(s, q) + if byte(s, r) == 58 and isWsEnd(byte(s, r + 1)) then + return t, r + 1 + end + return nil, nil + elseif c == 42 then + local name = match(s, "^%*([^%s,%[%]{}]+)", p) + if not name then + return nil, nil + end + local r = skipLine(s, p + 1 + #name) + if byte(s, r) == 58 and isWsEnd(byte(s, r + 1)) then + return true, r + 1 + end + return nil, nil + elseif c == 91 or c == 123 then + -- a flow collection used as a key? + local e = find(s, "\n", p, true) or #s + 1 + local line = sub(s, p, e - 1) + if match(line, "[%]}]%s*:%s") or match(line, "[%]}]%s*:$") then + local ok, _, q = pcall(parseFlow, st, p, -1) + if ok and byte(s, skipLine(s, q)) == 58 then + raise("UNSUPPORTED", "collections as mapping keys", p) + end + end + return nil, nil + end + if c == nil or c == 10 or c == 35 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 or c == 44 or c == 93 or c == 125 then + return nil, nil + end + if (c == 45 or c == 63 or c == 58) and isWsEnd(byte(s, p + 1)) then + return nil, nil + end + local j = p + while true do + local d = byte(s, j) + if d == nil or d == 10 then + return nil, nil + elseif d == 58 and isWsEnd(byte(s, j + 1)) then + break + elseif d == 35 and (byte(s, j - 1) == 32 or byte(s, j - 1) == 9) then + return nil, nil + end + j += 1 + end + local t = string.gsub(sub(s, p, j - 1), "[ \t]+$", "") + return t, j + 1 +end + +local function readKey(st: St, p: number, props: Props?): (any, number) + local s = st.s + local c = byte(s, p) + local tag = props and props.tag + local k: any + local q: number + if c == 42 then + if props then + corrupt("properties on an alias", p) + end + k, q = alias(st, p) + q = skipLine(s, q) + q += 1 -- the ':' + elseif c == 34 or c == 39 then + local t, r = quoted(st, p, -1) + if find(sub(s, p, r - 1), "\n", 1, true) then + corrupt("multi-line implicit key", p) + end + k = scalarValue(st, t, false, tag, p) + q = skipLine(s, r) + 1 + else + local t, after = implicitKey(st, p) + if t == nil then + corrupt("expected a mapping key", p) + end + k = scalarValue(st, t, true, tag, p) + q = after :: number + end + k = finish(st, props, k) + return checkKey(st, k, p), q +end + +-- a node on the lines after p's line (content deeper than ind; or a sequence at ind when seqAt) -> value, next | null +local function nextLineNode(st: St, ind: number, p: number, seqAt: boolean, mapParent: boolean): (any, number) + local s = st.s + local r = skip(s, p) + if r <= #s and not docMarker(s, r) then + local c = col(s, r) + if c > ind or (seqAt and c == ind and byte(s, r) == 45 and isWsEnd(byte(s, r + 1))) then + noTabs(s, r, ind) + return blockNode(st, ind, r, false, mapParent) + end + end + return st.null, p +end + +-- the value after a ':' (at p, just past it) of a mapping at column mc +local function mapValue(st: St, mc: number, p: number, explicit: boolean): (any, number) + local s = st.s + local r = skipLine(s, p) + local cc = byte(s, r) + if cc == nil or cc == 10 or (cc == 35 and r > p) then + return nextLineNode(st, mc, r, true, true) + end + return blockNode(st, mc, r, not explicit, true) +end + +local function blockMap(st: St, mc: number, p: number, firstProps: Props?): (any, number) + local s = st.s + enter(st, p) + local t: { [any]: any } = {} + local order: { any } = {} + local q = p + local first = true + while true do + local props: Props? = nil + if first and firstProps then + props = firstProps + else + props, p = properties(st, p) + end + first = false + local c = byte(s, p) + local k: any + local v: any + if ((c == 63 and not props) or c == 58) and isWsEnd(byte(s, p + 1)) then + -- "? key" (explicit) and ": value" (an empty key) + k = st.null + q = p + if c == 63 then + local r = skipLine(s, p + 1) + local cc = byte(s, r) + if cc == nil or cc == 10 or (cc == 35 and r > p + 1) then + k, q = nextLineNode(st, mc, r, true, false) + else + k, q = blockNode(st, mc, r, false, false) + end + k = checkKey(st, k, p) + local r3 = skip(s, q) + if r3 <= #s and not docMarker(s, r3) and col(s, r3) == mc and byte(s, r3) == 58 and isWsEnd(byte(s, r3 + 1)) then + v, q = mapValue(st, mc, r3 + 1, true) + else + v = st.null + end + else + k = finish(st, props, scalarValue(st, "", true, props and props.tag, p)) + v, q = mapValue(st, mc, p + 1, true) + end + else + local after + k, after = readKey(st, p, props) + v, q = mapValue(st, mc, after, false) + end + if t[k] == nil then + table.insert(order, k) + end + t[k] = v + local r3 = skip(s, q) + if r3 > #s or docMarker(s, r3) then + break + end + local cc3 = col(s, r3) + if cc3 == mc then + noTabs(s, r3) + if byte(s, r3) == 45 and isWsEnd(byte(s, r3 + 1)) then + corrupt("a sequence entry where a mapping key is expected", r3) + end + p = r3 + elseif cc3 < mc then + break + else + corrupt("bad indentation of a mapping entry", r3) + end + end + st.depth -= 1 + return Types.object(t, order), q +end + +local function blockSeq(st: St, sc: number, p: number): (any, number) + local s = st.s + enter(st, p) + local t: { any } = {} + local q = p + while true do + local r = skipLine(s, p + 1) + local c = byte(s, r) + local v: any + if c == nil or c == 10 or (c == 35 and r > p + 1) then + v, q = nextLineNode(st, sc, r, false, false) + else + if find(sub(s, p + 1, r - 1), "\t", 1, true) and (((c == 45 or c == 63 or c == 58) and isWsEnd(byte(s, r + 1))) or implicitKey(st, r) ~= nil) then + corrupt("tab before a compact collection", r) + end + v, q = blockNode(st, sc, r, false, false) + end + table.insert(t, v) + local r3 = skip(s, q) + if r3 > #s or docMarker(s, r3) then + break + end + local cc = col(s, r3) + if cc == sc and byte(s, r3) == 45 and isWsEnd(byte(s, r3 + 1)) then + noTabs(s, r3) + p = r3 + elseif cc <= sc then + break + else + corrupt("bad indentation of a sequence entry", r3) + end + end + st.depth -= 1 + return t, q +end + +-- the node at q after its properties (props may be nil); start = where the properties began +local function afterProps(st: St, ind: number, start: number, q: number, props: Props?, inline: boolean, mapParent: boolean): (any, number) + local s = st.s + local tag = props and props.tag + local c = byte(s, q) + if c == 42 then + if props then + corrupt("properties on an alias", q) + end + if implicitKey(st, q) ~= nil then + if inline then + corrupt("a mapping cannot start on its key's line", q) + end + return blockMap(st, col(s, q), q, nil) + end + local v, e = alias(st, q) + if not endOfLine(s, e) then + corrupt("unexpected text after an alias", e) + end + return v, e + end + if c == 45 and isWsEnd(byte(s, q + 1)) then + if inline or props then + corrupt("a sequence cannot start here", q) + end + return blockSeq(st, col(s, q), q) + elseif (c == 63 or c == 58) and isWsEnd(byte(s, q + 1)) then + if inline or (props and c == 63) then + corrupt("a mapping cannot start here", q) + end + return blockMap(st, col(s, start), q, props) + elseif c == 124 or c == 62 then + local text, e = blockScalar(st, q, ind) + return finish(st, props, scalarValue(st, text, false, tag, q)), e + elseif c == 91 or c == 123 then + implicitKey(st, q) -- raises UNSUPPORTED for a flow collection used as a key + local v, e = parseFlow(st, q, ind) + collectionTag(st, tag, if c == 91 then "seq" else "map", q) + if not endOfLine(s, e) then + corrupt("unexpected text after a flow collection", e) + end + return finish(st, props, v), e + end + if implicitKey(st, q) ~= nil then + if inline then + corrupt("a mapping cannot start on its key's line", q) + end + -- properties on the key's line belong to the first key + return blockMap(st, col(s, start), q, props) + end + if c == 34 or c == 39 then + local text, e = quoted(st, q, ind) + if not endOfLine(s, e) then + corrupt("unexpected text after a quoted scalar", e) + end + return finish(st, props, scalarValue(st, text, false, tag, q)), e + end + if c == 35 or c == 37 or c == 64 or c == 96 or c == 44 or c == 93 or c == 125 or c == 38 or c == 33 then + corrupt("unexpected character '" .. char(c :: number) .. "'", q) + end + local text, e = plain(st, q, ind, false) + if not endOfLine(s, e) then + corrupt("unexpected ':' (mapping values are not allowed here)", e) + end + return finish(st, props, scalarValue(st, text, true, tag, q)), e +end + +-- a block node at p (content; col(p) > ind, or == ind for a sequence that is a mapping's value). inline: on the +-- same line as its mapping key (no new block collection may start). mapParent: a sequence at the parent's +-- indentation may follow properties that end their line. +function blockNode(st: St, ind: number, p: number, inline: boolean, mapParent: boolean): (any, number) + local s = st.s + local props, q = properties(st, p) + if not props then + return afterProps(st, ind, p, q, nil, inline, mapParent) + end + -- properties ending their line apply to the node on the next lines; more properties there merge in, unless + -- they start a mapping key + local c = byte(s, q) + if not (c == nil or c == 10 or (c == 35 and q > p)) then + return afterProps(st, ind, p, q, props, inline, mapParent) + end + while true do + local r = skip(s, q) + if r > #s or docMarker(s, r) then + break + end + local cr = col(s, r) + if not (cr > ind or (mapParent and cr == ind and byte(s, r) == 45 and isWsEnd(byte(s, r + 1)))) then + break + end + noTabs(s, r, ind) + local cc = byte(s, r) + if cc == 38 or cc == 33 then + local p2, q2 = properties(st, r) + local c2 = byte(s, q2) + if c2 == nil or c2 == 10 or (c2 == 35 and q2 > r) then + local pr = props :: Props + if (p2 :: Props).anchor then + if pr.anchor then + corrupt("two anchors on one node", r) + end + pr.anchor = (p2 :: Props).anchor + end + if (p2 :: Props).tag then + if pr.tag then + corrupt("two tags on one node", r) + end + pr.tag = (p2 :: Props).tag + end + q = q2 + continue + end + if implicitKey(st, q2) ~= nil then + local v, e = blockMap(st, cr, r, nil) + collectionTag(st, (props :: Props).tag, "map", r) + return finish(st, props, v), e + end + -- properties then a scalar on the next line: merge + local pr = props :: Props + if (p2 :: Props).anchor and pr.anchor or (p2 :: Props).tag and pr.tag then + corrupt("two anchors or tags on one node", r) + end + pr.anchor = pr.anchor or (p2 :: Props).anchor + pr.tag = pr.tag or (p2 :: Props).tag + return afterProps(st, ind, r, q2, pr, false, mapParent) + end + local tag = (props :: Props).tag + if cc == 45 and isWsEnd(byte(s, r + 1)) then + local v, e = blockSeq(st, cr, r) + collectionTag(st, tag, "seq", r) + return finish(st, props, v), e + elseif ((cc == 63 or cc == 58) and isWsEnd(byte(s, r + 1))) or (cc ~= 91 and cc ~= 123 and implicitKey(st, r) ~= nil) then + local v, e = blockMap(st, cr, r, nil) + collectionTag(st, tag, "map", r) + return finish(st, props, v), e + elseif cc == 42 then + corrupt("properties on an alias", r) + end + return afterProps(st, ind, r, r, props, false, mapParent) + end + return finish(st, props, scalarValue(st, "", true, (props :: Props).tag, q)), q +end + +-- ------------------------------------------------------------------------------------------------ stream +local function stream(st: St): { any } + local s = st.s + local n = #s + local docs = {} + local p = 1 + local needEnd = false -- a bare document after a document must follow "..." or "---" + while true do + p = skip(s, p) + if p > n then + break + end + local sawDirective = false + st.handles = { ["!"] = "!", ["!!"] = CORE } + local yamlSeen = false + while byte(s, p) == 37 and col(s, p) == 0 do -- % + if needEnd then + corrupt("a directive needs '...' after the previous document", p) + end + local e = find(s, "\n", p, true) or n + 1 + local line = string.gsub(sub(s, p, e - 1), "%s+#.*$", "") + local name = match(line, "^%%(%S+)") + if name == "YAML" then + if yamlSeen then + corrupt("two %YAML directives", p) + end + yamlSeen = true + local v = match(line, "^%%YAML[ \t]+(%d+%.%d+)[ \t]*$") + if not v then + corrupt("bad %YAML directive", p) + end + elseif name == "TAG" then + local h, prefix = match(line, "^%%TAG[ \t]+(![%w%-]*!?)[ \t]+(%S+)[ \t]*$") + if not h then + corrupt("bad %TAG directive", p) + end + st.handles[h :: string] = prefix :: string + end + sawDirective = true + p = skip(s, e) + end + local explicit = false + if docMarker(s, p) and sub(s, p, p + 2) == "---" then + explicit = true + p += 3 + elseif sawDirective then + corrupt("directives without '---'", p) + elseif docMarker(s, p) then -- "..." + if not endOfLine(s, p + 3) then + corrupt("text after '...'", p + 3) + end + p += 3 + needEnd = false + continue + elseif needEnd then + corrupt("a second document needs '---'", p) + end + st.anchors = {} + local q = skip(s, p) + local value: any + if q > n or docMarker(s, q) then + value = st.null + p = q + else + if explicit and not find(sub(s, p, q), "\n", 1, true) then + -- content on the "---" line + local ok, _, q2 = pcall(properties, st, q) + local c = byte(s, q2) + if ok and c ~= 124 and c ~= 62 and not endOfLine(s, q2) and implicitKey(st, q2) ~= nil then + corrupt("a block mapping cannot start on the '---' line", q) + end + end + value, p = blockNode(st, -1, q, false, false) + local r = skip(s, p) + if r <= n and not docMarker(s, r) then + corrupt("unexpected content after the document", r) + end + p = r + end + table.insert(docs, value) + needEnd = true + if p <= n and docMarker(s, p) and sub(s, p, p + 2) == "..." then + if not endOfLine(s, p + 3) then + corrupt("text after '...'", p + 3) + end + p += 3 + needEnd = false + elseif p <= n and docMarker(s, p) then + needEnd = false + end + end + return docs +end + +-- run(text, opts) -> docs | nil, code, message, offset +function Parse.run(text: string, opts: Options?): (any, any, any, any) + local o: Options = opts or {} + local s = text + if sub(s, 1, 3) == "\239\187\191" then + s = sub(s, 4) + end + if find(s, "\r", 1, true) then + s = string.gsub(string.gsub(s, "\r\n", "\n"), "\r", "\n") + end + local st: St = { + s = s, + n = #s, + anchors = {}, + handles = {}, + depth = 0, + maxDepth = o.maxDepth or 500, + aliasNodes = 0, + maxAlias = o.maxAliasNodes or 1e6, + sizes = setmetatable({}, { __mode = "k" }) :: any, + ignoreTags = o.tags == "ignore", + null = if o.null ~= nil then o.null else Types.null, + } + local ok, res = pcall(stream, st) + if ok then + return res, nil, nil, nil + end + if type(res) == "table" and res.yamlErr then + return nil, res.code, res.msg, res.at + end + local msg = tostring(res) + if string.find(msg, "stack overflow", 1, true) then + return nil, "LIMIT", "nested too deeply", 0 + end + return nil, "CORRUPT", "internal error: " .. msg, 0 +end + +return Parse diff --git a/src/Formats/data/yaml/init.luau b/src/Formats/data/yaml/init.luau new file mode 100644 index 0000000..fd605b7 --- /dev/null +++ b/src/Formats/data/yaml/init.luau @@ -0,0 +1,77 @@ +--!strict +-- data/yaml: YAML 1.2 (core schema), new code. Supports: block and flow styles, compact nested collections, plain / +-- quoted / literal / folded scalars (indentation and chomping indicators), comments, anchors and aliases (decoded as +-- shared references; an expansion-size limit guards against alias bombs), tags !!str !!int !!float !!bool !!null +-- !!map !!seq !!binary (-> buffer) !!timestamp (-> Types.Date) and verbatim / %TAG forms, multi-document streams. +-- Maps decode to Types.object (key order kept), null to Types.null. Writes block style (anchors for shared tables). +-- Not supported (Err.UNSUPPORTED): complex keys "? ", collections as keys, other tags unless opts.tags = "ignore"; +-- merge keys "<<" stay ordinary keys; YAML 1.1 types (yes / no, sexagesimal, ...) are strings. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Parse = require("@formats/data/yaml/Parse") +local Emit = require("@formats/data/yaml/Emit") + +-- ------------------------------------------------------------------------------------------------ contract +local Yaml = { + name = "yaml", + category = "data", + extensions = { "yaml", "yml" }, + mime = { "application/yaml", "application/x-yaml", "text/yaml" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true }, +} + +export type DecodeOptions = Parse.Options +export type EncodeOptions = Emit.Options + +-- ------------------------------------------------------------------------------------------------ sniff +function Yaml.sniff(r: Bytes.Reader): number + local head = r:peek(256) + if string.find(head, "%z") then + return 0 + end + if string.match(head, "^%%YAML ") then + return 0.9 + end + if string.match(head, "^%-%-%-[ \r\n]") then + return 0.5 + end + local line = string.match(head, "^[ \t\r\n]*([^\r\n]*)") + if line and (string.match(line, "^[%w_%-\"']+[%w_%- \"']*:[ ]") or string.match(line, "^[%w_%-]+:$") or string.match(line, "^%- ")) then + return 0.2 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> the first document (Types.null when there is none) | every document (opts.all) | nil, Err +function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local docs, code, msg, at = Parse.run(text, opts) + if not docs then + return nil, Err.new(code, msg, at) + end + if opts and opts.all then + return docs, nil + end + local first = docs[1] + if first == nil then + return if opts and opts.null ~= nil then opts.null else Types.null, nil + end + return first, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(value, opts?) -> buffer | nil, Err (opts.all: value is an array of documents) +function Yaml.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local s, err = Emit.encode(value, opts) + if not s then + return nil, Err.new(Err.ARG, err or "cannot encode") + end + return buffer.fromstring(s), nil +end + +return Yaml diff --git a/tests/codecs/json.luau b/tests/codecs/json.luau new file mode 100644 index 0000000..dacb399 --- /dev/null +++ b/tests/codecs/json.luau @@ -0,0 +1,210 @@ +-- codecs/Json tests: the JSONTestSuite parsing corpus (y_ must parse to Python's value, n_ must fail, i_ must not +-- throw), Python json.dumps output in four styles parsed and reproduced byte for byte (compact sorted, ordered, +-- indent 2, ensure_ascii), events / lines / decodeAt / writer, options, error codes, and the fuzz pass. +-- Fixtures: tools/fixtures/json.py. +local T = require("@tests/T") +local Json = require("@formats/codecs/Json") +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") +local Canon = require("@tests/data/Canon") +local Suite = require("@tests/gen/json_suite") +local Corpus = require("@tests/gen/json_corpus") + +local t = T.suite("json") + +-- events() rebuilt into a value (checks the pull tokenizer agrees with decode) +local function fromEvents(s: string): (any, any) + local stack, keys = {}, {} + local top: any = nil + local key: any = nil + local function add(v: any) + local cur = stack[#stack] + if cur == nil then + top = v + elseif keys[#stack] ~= false then + cur[key] = v + else + table.insert(cur, v) + end + end + for ev, v in Json.events(s) do + if ev == "error" then + return nil, v + elseif ev == "object" or ev == "array" then + local tbl = if ev == "object" then Types.object() else {} + add(tbl) + table.insert(stack, tbl) + keys[#stack] = if ev == "object" then true else false + elseif ev == "endObject" or ev == "endArray" then + keys[#stack] = nil + table.remove(stack) + elseif ev == "key" then + key = v + else + add(v) + end + end + return top, nil +end + +-- 1. JSONTestSuite +local counts = { y = 0, n = 0, i = 0, iok = 0 } +for _, c in Suite do + local v, err = Json.decode(c.data) + local ev, everr = fromEvents(c.data) + if c.expect == "y" then + t:check(v ~= nil, c.name .. ": parses (" .. tostring(err) .. ")") + t:eq(Canon.of(v), c.canon, c.name .. ": value") + t:check(ev ~= nil, c.name .. ": events parse (" .. tostring(everr) .. ")") + t:eq(Canon.of(ev), c.canon, c.name .. ": events value") + -- and our output reads back the same + local s = Json.encode(v) + t:check(s ~= nil, c.name .. ": encodes") + t:eq(Canon.of(Json.decode(s :: string)), c.canon, c.name .. ": round trip") + elseif c.expect == "n" then + t:check(v == nil and Err.is(err), c.name .. ": rejected") + t:check(ev == nil, c.name .. ": events reject") + else + counts.iok += if v ~= nil then 1 else 0 + end + counts[c.expect] += 1 +end +t:note("JSONTestSuite: %d y_ accepted, %d n_ rejected, %d of %d i_ accepted", counts.y, counts.n, counts.iok, counts.i) + +-- 2. Python's json.dumps output: parse, compare, re-encode byte for byte +for i, c in Corpus do + local v, err = Json.decode(c.compact) + t:check(v ~= nil, "corpus " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "corpus " .. i .. ": value") + t:eq(Json.encode(v), c.compact, "corpus " .. i .. ": compact text") + t:eq(Json.encode(v, { indent = 2 }), c.pretty, "corpus " .. i .. ": indent 2 text") + t:eq(Json.encode(v, { ascii = true }), c.ascii, "corpus " .. i .. ": ensure_ascii text") + local o = Json.decode(c.ordered, { ordered = true }) + t:eq(Json.encode(o), c.ordered, "corpus " .. i .. ": ordered text") + t:eq(Canon.of(Json.decode(c.ascii)), c.canon, "corpus " .. i .. ": ascii parse") + t:eq(Canon.of(Json.decode(c.pretty)), c.canon, "corpus " .. i .. ": pretty parse") +end + +-- 3. options and API +do + local v = Json.decode('[12345678901234567890, -9007199254740993, 9007199254740991, 1.5e300]', { bigInts = "string" }) + t:eq(v[1], "12345678901234567890", "bigInts string") + t:eq(v[2], "-9007199254740993", "bigInts negative") + t:eq(v[3], 9007199254740991, "2^53 - 1 stays a number") + t:eq(v[4], 1.5e300, "floats stay numbers") + t:eq(Json.decode("[null]", { null = false })[1], false, "opts.null") + t:eq(Json.decode("null"), Types.null, "top-level null") + t:eq(Json.decode("\239\187\191[1]")[1], 1, "BOM skipped") + t:eq(Json.decode(buffer.fromstring(" 7 ")), 7, "buffer input") + local e = Json.decode('{"b":1,"a":{},"c":[]}') + t:eq(Json.encode(e), '{"a":{},"b":1,"c":[]}', "empty object stays an object") + local o = Json.decode('{"z":1,"a":2,"m":{"y":1,"b":2}}', { ordered = true }) + t:eq(Json.encode(o), '{"z":1,"a":2,"m":{"y":1,"b":2}}', "ordered keys") + Types.set(o, "b", 3) + o.a = nil + t:eq(Json.encode(o), '{"z":1,"m":{"y":1,"b":2},"b":3}', "ordered set / remove") + t:eq(Json.encode({}, { emptyTable = "object" }), "{}", "emptyTable object") + t:eq(Json.encode({ [1] = "a", [3] = "c" }), '{"1":"a","3":"c"}', "sparse array -> object") + t:eq(Json.encode({ 1, 2, x = 1 }), '{"1":1,"2":2,"x":1}', "mixed table -> object") + t:eq(Json.encode("a/b", { escapeSlash = true }), '"a\\/b"', "escapeSlash") + t:eq(Json.encode(0 / 0, { nan = "null" }), "null", "nan null") + local _, ne = Json.encode(math.huge) + t:eq(ne and ne.code, Err.ARG, "inf is an error") + local cyc = {} + cyc.self = cyc + local _, ce = Json.encode(cyc) + t:eq(ce and ce.code, Err.ARG, "cycle is an error") + local _, fe = Json.encode({ f = print }) + t:eq(fe and fe.code, Err.ARG, "function is an error") + t:eq(Json.encode(Types.Date.parse("1979-05-27T07:32:00Z")), '"1979-05-27T07:32:00Z"', "dates as strings") + for _, x in { 0.1, 1 / 3, -2.5e-8, 1e300, 123456789012345, 2 ^ 53, 5e-324, 1.7976931348623157e308 } do + t:eq(Json.decode(Json.encode(x) :: string), x, "number round trip " .. string.format("%.17g", x)) + end +end + +-- 4. streaming: lines, decodeAt, writer +do + local got = {} + for _, v in Json.lines('{"a":1}\n[2]\n"x"\n 3 ') do + table.insert(got, (Json.encode(v))) + end + t:eq(table.concat(got, "|"), '{"a":1}|[2]|"x"|3', "lines") + local n, last = 0, nil + for _, v, e in Json.lines("1 2 [") do + if e then + last = e + else + n += 1 + end + end + t:eq(n, 2, "lines stop at the bad value") + t:eq(last and last.code, Err.TRUNCATED, "lines report the error") + local v, p = Json.decodeAt("[1] [2]", 1) + t:eq(v[1], 1, "decodeAt value") + t:eq(p, 4, "decodeAt next") + t:eq(Json.decodeAt(" ", 1), nil, "decodeAt at the end") + + local w = Json.writer({ indent = 2 }) + w:beginObject():key("a"):value({ 1, 2 }):key("b"):beginArray():value("x"):beginObject():endObject():endArray():endObject() + local s = w:tostring() + t:eq(s, Json.encode(Json.decode('{"a":[1,2],"b":["x",{}]}', { ordered = true }), { indent = 2 }), "writer pretty") + local w2 = Json.writer() + w2:beginArray() + local parts = {} + for i = 1, 5 do + w2:value(i) + table.insert(parts, w2:flush()) + end + w2:endArray() + table.insert(parts, w2:flush()) + t:eq(table.concat(parts), "[1,2,3,4,5]", "writer flush chunks") + t:eq(w2:tostring(), "[1,2,3,4,5]", "writer tostring after flushes") + local w3 = Json.writer() + w3:beginArray():key("x") + t:check(w3.err ~= nil, "writer: key in array") + local w4 = Json.writer() + w4:beginObject():value(1) + t:check(w4.err ~= nil, "writer: value without key") + local w5 = Json.writer() + w5:beginObject() + t:check(w5:tostring() == nil, "writer: unclosed") +end + +-- 5. errors +local function code(s: string, opts: any?): string? + local _, e = Json.decode(s, opts) + return e and e.code +end +t:eq(code('{"a":'), Err.TRUNCATED, "truncated object") +t:eq(code('"abc'), Err.TRUNCATED, "truncated string") +t:eq(code("[1 2]"), Err.CORRUPT, "missing comma") +t:eq(code("[1] x"), Err.CORRUPT, "trailing data") +t:eq(code(string.rep("[", 50) .. string.rep("]", 50), { maxDepth = 10 }), Err.LIMIT, "maxDepth") +t:eq(code(string.rep("[", 100000)), Err.LIMIT, "100000 opening brackets") +t:eq(code(""), Err.TRUNCATED, "empty input") +local _, ae = Json.decode(42 :: any) +t:eq(ae and ae.code, Err.ARG, "bad argument") +do + local _, e = Json.decode('{"a": tru}') + t:eq(e and e.offset, 6, "error offset") +end + +-- 6. fuzz +local samples = {} +for i = 1, 40 do + table.insert(samples, Corpus[i].compact) +end +for _, c in Suite do + if #samples < 120 and c.expect == "y" and #c.data < 200 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return Json.decode(b) +end, samples) +t:fuzz("events", function(b: buffer) + for _ in Json.events(b) do + end + return nil +end, samples, { garbage = 50 }) +t:done() diff --git a/tests/codecs/xml.luau b/tests/codecs/xml.luau new file mode 100644 index 0000000..dac3f32 --- /dev/null +++ b/tests/codecs/xml.luau @@ -0,0 +1,197 @@ +-- codecs/Xml tests: random documents (namespaces, escapes, CDATA, comments, PIs, DOCTYPE entities, UTF-16, Latin-1) +-- against Python's ElementTree trees; encode -> decode round trips; well-formedness verdicts against expat +-- (hand-written cases and random mutations); events, helpers, options, error codes; the fuzz pass. +-- Fixtures: tools/fixtures/xml.py. +local T = require("@tests/T") +local Xml = require("@formats/codecs/Xml") +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") +local Docs = require("@tests/gen/xml_docs") +local Wf = require("@tests/gen/xml_wf") + +local t = T.suite("xml") + +-- ElementTree's view of an element (tools/fixtures/xml.py canon): Clark names, xmlns attributes dropped, text / tail +local function s(x: string?): string + x = x or "" + return #(x :: string) .. ":" .. (x :: string) +end +local function canon(e: any, tail: string?): string + local out = { "(" .. s(Xml.clark(e)) } + local keys = {} + local vals = {} + for _, k in Types.keys(e.attrs) do + if k ~= "xmlns" and string.sub(k, 1, 6) ~= "xmlns:" then + local ck = Xml.clark(e, k) + table.insert(keys, ck) + vals[ck] = e.attrs[k] + end + end + table.sort(keys) + for _, k in keys do + table.insert(out, "|" .. s(k) .. "=" .. s(vals[k])) + end + -- text: strings before the first element child; each child's tail: strings after it + local text = {} + local i = 1 + local ch = e.children + while i <= #ch and (type(ch[i]) == "string" or ch[i].name == "#cdata") do + table.insert(text, Xml.text(ch[i])) + i += 1 + end + table.insert(out, "|t" .. s(table.concat(text))) + while i <= #ch do + local c = ch[i] + i += 1 + local tl = {} + while i <= #ch and (type(ch[i]) == "string" or ch[i].name == "#cdata") do + table.insert(tl, Xml.text(ch[i])) + i += 1 + end + table.insert(out, canon(c, table.concat(tl))) + end + return table.concat(out) .. ")t" .. s(tail) +end + +-- 1. documents vs ElementTree, and round trips +for i, d in Docs do + local doc, err = Xml.decode(d.data, { whitespace = true }) + t:check(doc, "doc " .. i .. ": " .. tostring(err)) + t:eq(canon((doc :: any).root), d.canon, "doc " .. i .. ": tree") + -- keep everything, encode, decode again: the same tree + local full = Xml.decode(d.data, { whitespace = true, comments = true, cdata = true, pi = true }) :: any + local out, eerr = Xml.encode(full) + t:check(out, "doc " .. i .. ": encodes (" .. tostring(eerr) .. ")") + local again, aerr = Xml.decode(out :: string, { whitespace = true }) + t:check(again, "doc " .. i .. ": re-decodes (" .. tostring(aerr) .. ")") + t:eq(canon((again :: any).root), d.canon, "doc " .. i .. ": round trip") + local pretty = Xml.encode(full, { indent = 2 }) :: string + t:check(Xml.decode(pretty), "doc " .. i .. ": pretty output parses") + -- the namespace option agrees with the clark helper + local nsdoc = Xml.decode(d.data, { namespaces = true }) :: any + local root = nsdoc.root + local want = string.match(Xml.clark(root), "^{([^}]*)}") + t:eq(root.ns, want, "doc " .. i .. ": node.ns") +end + +-- 2. well-formedness against expat +local agree, total, accepted, rejected = 0, 0, 0, 0 +for i, c in Wf do + local doc = Xml.decode(c.data) + local ok = doc ~= nil + total += 1 + if ok == c.ok then + agree += 1 + elseif i <= 60 then + t:check(false, "wf case " .. i .. " " .. string.format("%q", c.data) .. ": expat says " .. tostring(c.ok)) + end + if c.ok then + accepted += 1 + else + rejected += 1 + end +end +t:note("well-formedness: %d of %d verdicts agree with expat (%d well-formed, %d not)", agree, total, accepted, rejected) +t:check(agree >= total * 0.99, "well-formedness agreement >= 99%") + +-- 3. API details +do + local src = '\n]>\nt]]>u\n' + local doc = Xml.decode(src, { comments = true, cdata = true, pi = true, namespaces = true }) :: any + t:eq(doc.declaration.version, "1.0", "declaration") + t:eq(doc.doctype.name, "r", "doctype name") + t:eq(doc.doctype.entities.e, "E&", "doctype entities (char refs expanded once)") + t:eq(doc.children[1].name, "#comment", "prolog comment kept") + local r = doc.root + t:eq(table.concat(Types.keys(r.attrs), ","), "xmlns,xmlns:p,z,a", "attribute order") + t:eq(r.ns, "urn:d", "default namespace") + local x = Xml.child(r, "x") :: any + t:eq(x.name, "p:x", "child by local name") + t:eq(x.ns, "urn:p", "prefixed namespace") + t:eq(Xml.clark(x, "p:k"), "{urn:p}k", "attribute clark") + t:eq(x.children[2].name, "#cdata", "cdata node") + t:eq(Xml.text(x), "tu", "text with cdata") + t:eq(r.children[2].name, "#pi", "pi node") + t:eq(r.children[2].target .. "|" .. r.children[2].text, "go|now", "pi target / data") + t:eq(#Xml.children(r), 2, "element children") + t:eq(#Xml.descendants(doc), 3, "descendants") + t:eq(x.parent, r, "parent link") + t:eq(Xml.decode("&e;") == nil, true, "undefined entity") + local d2 = Xml.decode(']>&e;') :: any + t:eq(d2.root.attrs.a, "E&", "entity in attribute") + t:eq(Xml.text(d2.root), "E&", "entity in text") + -- whitespace handling + local w = Xml.decode("\n x \n \n") :: any + t:eq(#w.root.children, 2, "whitespace-only text dropped") + t:eq(Xml.text(w.root.children[1]), " x ", "other text kept as is") + t:eq(w.root.children[2].children[1], " ", "xml:space preserve") + t:eq(#(Xml.decode("\n \n", { whitespace = true }) :: any).root.children, 3, "opts.whitespace") + -- attribute normalization and line endings + local n = Xml.decode("l1\r\nl2\rl3") :: any + t:eq(n.root.attrs.b, "x y z\n", "attribute value normalization") + t:eq(Xml.text(n.root), "l1\nl2\nl3", "line endings") + -- builders and encode + local e = Xml.element("svg", { width = "10", height = "5" }, { Xml.element("rect", { x = "1" }), "aa<b & "c"', "encode element") + local d3 = Xml.document(Xml.element("r", nil, { Xml.element("a"), Xml.element("b", nil, { "t" }) })) + t:eq(Xml.encode(d3, { indent = 2 }), '\n\n \n t\n\n', "pretty document") + t:eq(Xml.encode(Xml.element("a"), { selfClose = false }), "", "selfClose false") + local _, be = Xml.encode(Xml.element("1bad")) + t:eq(be and be.code, Err.ARG, "bad name on encode") + local cyc = Xml.element("a") + table.insert(cyc.children, cyc) + local _, ce = Xml.encode(cyc) + t:eq(ce and ce.code, Err.ARG, "cycle on encode") + t:eq(Xml.encode({ name = "#cdata", attrs = Types.object(), children = {}, text = "a]]>b" } :: any), "b]]>", "cdata split") + -- events + local evs = {} + for ev, a in Xml.events("t") do + table.insert(evs, ev .. (if type(a) == "string" then ":" .. a else "")) + end + t:eq(table.concat(evs, " "), "start:a start:b text:t end:b comment:c end:a", "events") + local last + for ev, a in Xml.events("") do + last = { ev, a } + end + t:eq(last[1], "error", "events error") + t:eq(last[2].code, Err.CORRUPT, "events error code") + -- UTF-16 without BOM and encodings + local u16 = buffer.create(8) + for k, ch in { 60, 0, 97, 0, 47, 0, 62, 0 } do + buffer.writeu8(u16, k - 1, ch) + end + t:eq((Xml.decode(u16) :: any).root.name, "a", "UTF-16LE without BOM") + local _, ue = Xml.decode("") + t:eq(ue and ue.code, Err.UNSUPPORTED, "unsupported encoding") +end + +-- 4. errors and limits +local function code(src: string, opts: any?): string? + local _, e = Xml.decode(src, opts) + return e and e.code +end +t:eq(code(""), Err.TRUNCATED, "unclosed") +t:eq(code(""), Err.CORRUPT, "mismatch") +t:eq(code(""), Err.CORRUPT, "duplicate attribute") +t:eq(code(string.rep("", 60) .. string.rep("", 60), { maxDepth = 50 }), Err.LIMIT, "maxDepth") +t:eq(code(']>&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;', { maxExpansion = 100000 }), Err.LIMIT, "billion laughs") +t:eq(code(']>&a;'), Err.CORRUPT, "recursive entity") +t:eq(code(']>&x;'), Err.UNSUPPORTED, "external entity") +t:eq(code("", { namespaces = true }), Err.CORRUPT, "undeclared prefix") +local _, ae = Xml.decode(5 :: any) +t:eq(ae and ae.code, Err.ARG, "bad argument") + +-- 5. fuzz +local samples = {} +for i = 1, 40 do + table.insert(samples, Docs[i].data) +end +t:fuzz("decode", function(b: buffer) + return Xml.decode(b, { comments = true, namespaces = true }) +end, samples) +t:fuzz("encode(decode)", function(b: buffer) + local d = Xml.decode(b, { comments = true, cdata = true, pi = true }) + return d and Xml.encode(d, { indent = 1 }) +end, samples, { garbage = 20 }) +t:done() diff --git a/tests/data/Canon.luau b/tests/data/Canon.luau new file mode 100644 index 0000000..9291fb2 --- /dev/null +++ b/tests/data/Canon.luau @@ -0,0 +1,86 @@ +-- tests/data/Canon: the canonical text of a decoded data value, the same as tools/fixtures/_data_common.py canon() on +-- Python's parse: null n, true t, false f, numbers #%d (integral under 2^53) or #%.17g, strings s:, +-- buffers b:, arrays [x,...], objects {k=v,...} sorted by key text, dates d. A module the data +-- tests require (running it alone does nothing). +local Types = require("@formats/Types") + +local Canon = {} + +local function num(x: number): string + if x ~= x then + return "#nan" + elseif x == math.huge then + return "#inf" + elseif x == -math.huge then + return "#-inf" + elseif x == math.floor(x) and math.abs(x) < 2 ^ 53 then + return string.format("#%d", x) + end + return "#" .. string.format("%.17g", x) +end + +local function isArray(t: { [any]: any }): boolean + if Types.isObject(t) then + return false + end + local n = #t + local c = 0 + for _ in next, t do + c += 1 + end + return c == n +end + +local function canon(v: any, out: { string }) + local tv = type(v) + if v == Types.null then + table.insert(out, "n") + elseif tv == "boolean" then + table.insert(out, if v then "t" else "f") + elseif tv == "number" then + table.insert(out, num(v)) + elseif tv == "string" then + table.insert(out, "s" .. #v .. ":" .. v) + elseif tv == "buffer" then + table.insert(out, "b" .. buffer.len(v) .. ":" .. buffer.tostring(v)) + elseif tv == "table" and Types.Date.is(v) then + table.insert(out, "d" .. tostring(v)) + elseif tv == "table" then + if isArray(v) then + table.insert(out, "[") + for i = 1, #v do + canon(v[i], out) + table.insert(out, ",") + end + table.insert(out, "]") + else + local items = {} + for k, x in next, v do + local ko = {} + canon(k, ko) + table.insert(items, { table.concat(ko), x }) + end + table.sort(items, function(a, b) + return a[1] < b[1] + end) + table.insert(out, "{") + for _, it in items do + table.insert(out, it[1] .. "=") + canon(it[2], out) + table.insert(out, ",") + end + table.insert(out, "}") + end + else + table.insert(out, "?" .. tv) + end +end + +-- of(v) -> the canonical text +function Canon.of(v: any): string + local out = {} + canon(v, out) + return table.concat(out) +end + +return Canon diff --git a/tests/data/cbor.luau b/tests/data/cbor.luau new file mode 100644 index 0000000..8501da2 --- /dev/null +++ b/tests/data/cbor.luau @@ -0,0 +1,121 @@ +-- data/cbor tests: the RFC 8949 Appendix A examples and random items encoded by Python's cbor2 decode to cbor2's +-- values (canonical form), re-encode to the same bytes, big integers as doubles and exact text, indefinite lengths, +-- tags / simple values / undefined, half floats, sequences, options, error codes, and the fuzz pass. +-- Fixtures: tools/fixtures/cbor.py. +local T = require("@tests/T") +local Cbor = require("@formats/data/cbor") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Canon = require("@tests/data/Canon") +local Fx = require("@tests/gen/cbor") + +local t = T.suite("data/cbor") + +t:eq(Cbor.name, "cbor", "name") +t:check(Cbor.caps.decode and Cbor.caps.encode, "caps") + +local function dec(s: string | buffer, opts: any?): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + return Cbor.decode(Bytes.reader(b), opts) +end + +-- the fixture's view of tags / simple values / undefined +local function plain(v: any): any + if v == Cbor.undefined then + return { "undefined" } + elseif Cbor.isSimple(v) then + return { "simple", v.value } + elseif Cbor.isTagged(v) then + return { "tag", v.tag, plain(v.value) } + elseif type(v) == "table" and not Types.Date.is(v) and v ~= Types.null then + local o = if Types.isObject(v) then Types.object() else {} + for k, x in next, v do + o[plain(k)] = plain(x) + end + return o + end + return v +end + +local nApp = 0 +for _, c in Fx.appendix do + local v, err = dec(c.data) + if c.error then + t:check(v == nil and err ~= nil, c.hex .. ": rejected like cbor2") + else + t:check(v ~= nil or err == nil, c.hex .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, c.hex .. ": value") + t:eq(Canon.of(plain(dec(c.data, { bigInts = "string" }))), c.canonStr, c.hex .. ": exact") + t:eq(Canon.of(plain(dec(Cbor.encode(v) :: buffer))), c.canon, c.hex .. ": round trip") + t:eq(Canon.of(plain(dec(Cbor.encode(v, { compactFloats = true }) :: buffer))), c.canon, c.hex .. ": compact round trip") + end + nApp += 1 +end +t:note("RFC 8949 appendix A: %d examples", nApp) + +for i, c in Fx.safe do + local v, err = dec(c.data) + t:check(v ~= nil, "safe " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, "safe " .. i .. ": value") + local b = Cbor.encode(v) :: buffer + t:check(b and buffer.tostring(b) == c.data, "safe " .. i .. ": same bytes") +end +for i, c in Fx.wide do + local v, err = dec(c.data) + t:check(v ~= nil, "wide " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, "wide " .. i .. ": value") + t:eq(Canon.of(plain(dec(c.data, { bigInts = "string" }))), c.canonStr, "wide " .. i .. ": exact") +end + +-- details +do + local function hex(b: buffer): string + return (string.gsub(buffer.tostring(b), ".", function(ch) + return string.format("%02x", string.byte(ch)) + end)) + end + t:eq(hex(Cbor.encode(1.5, { compactFloats = true }) :: buffer), "f93e00", "half float") + t:eq(hex(Cbor.encode(100000.0 + 0.5, { compactFloats = true }) :: buffer), "fa47c35040", "single float") + t:eq(hex(Cbor.encode(1.1) :: buffer), "fb3ff199999999999a", "double float") + t:eq(hex(Cbor.encode(-0.0, { compactFloats = true }) :: buffer), "f98000", "negative zero") + t:eq(hex(Cbor.encode(0 / 0, { compactFloats = true }) :: buffer), "f97e00", "nan") + t:eq(hex(Cbor.encode(-2 ^ 64) :: buffer), "3bffffffffffffffff", "-2^64") + t:eq(hex(Cbor.encode(Cbor.tagged(32, "x")) :: buffer), "d8206178", "tagged") + t:eq(hex(Cbor.encode(Cbor.simple(255)) :: buffer), "f8ff", "simple") + t:eq(hex(Cbor.encode(Cbor.undefined) :: buffer), "f7", "undefined") + t:eq(hex(Cbor.encode(Types.Date.parse("2013-03-21T20:04:00Z")) :: buffer), "c074323031332d30332d32315432303a30343a30305a", "date tag 0") + t:eq(hex(Cbor.encode(Types.Date.parse("2013-03-21T20:04:00Z"), { dates = "epoch" }) :: buffer), "c11a514b67b0", "date tag 1") + t:eq(hex(Cbor.encode({ 1 }, { selfDescribe = true }) :: buffer), "d9d9f78101", "self-describe") + t:eq(dec("\217\217\247\1"), 1, "self-describe stripped") + t:eq(Cbor.sniff(Bytes.reader(buffer.fromstring("\217\217\247\1"))), 1, "sniff self-describe") + t:eq(#dec("\1\2\3", { all = true }), 3, "sequence") + t:eq(hex(Cbor.encode({ 1, "a" }, { all = true }) :: buffer), "016161", "encode sequence") + local function code(s: string): string? + local _, e = dec(s) + return e and e.code + end + t:eq(code("\x9b\xff\xff\xff\xff\xff\xff\xff\xff"), Err.TRUNCATED, "huge array count") + t:eq(code("\x5f\x61\x61\xff"), Err.CORRUPT, "text chunk in a byte string") + t:eq(code("\xff"), Err.CORRUPT, "lone break") + t:eq(code("\x1c"), Err.CORRUPT, "reserved additional info") + t:eq(code("\x62\xc3\x28"), Err.CORRUPT, "invalid UTF-8") + t:eq(code("\x01\x02"), Err.CORRUPT, "trailing data") + t:eq(code("\xc0\x01"), Err.CORRUPT, "tag 0 on a number") + t:eq(code(string.rep("\x81", 600) .. "\x01"), Err.LIMIT, "depth") + t:eq(code("\x9f\x01"), Err.TRUNCATED, "unterminated indefinite array") +end + +local samples = {} +for _, c in Fx.appendix do + table.insert(samples, c.data) +end +for i = 1, 40 do + if #Fx.safe[i].data < 3000 then + table.insert(samples, Fx.safe[i].data) + end +end +t:fuzz("decode", function(b: buffer) + return Cbor.decode(Bytes.reader(b)) +end, samples, { mutations = 4 }) +t:done() diff --git a/tests/data/csv.luau b/tests/data/csv.luau new file mode 100644 index 0000000..fd098cf --- /dev/null +++ b/tests/data/csv.luau @@ -0,0 +1,76 @@ +-- data/csv tests: tables written by Python's csv.writer / DictWriter (every delimiter, quotes, line breaks inside +-- fields, empty fields) read back as csv.reader does, re-encoded byte for byte, keyed rows with a header, options, +-- error codes, and the fuzz pass. Fixtures: tools/fixtures/csv.py. +local T = require("@tests/T") +local F = require("@formats") +local Csv = require("@formats/data/csv") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Canon = require("@tests/data/Canon") +local Fx = require("@tests/gen/csv") + +local t = T.suite("data/csv") + +t:eq(Csv.name, "csv", "name") +t:check(Csv.caps.decode and Csv.caps.encode, "caps") + +local function dec(s: string, opts: any?): (any, any) + return Csv.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +for i, c in Fx do + local rows, err = dec(c.data, { delimiter = c.delimiter }) + t:check(rows ~= nil, "case " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(rows), Canon.of(c.rows), "case " .. i .. ": rows") + local b = Csv.encode(rows, { delimiter = c.delimiter, newline = c.newline }) :: buffer + t:eq(buffer.tostring(b), c.data, "case " .. i .. ": same text") + if c.delimiter ~= "," or i % 3 == 0 then + local auto = dec(c.data, { delimiter = "auto" }) + if c.rows[1] and #c.rows[1] > 1 and auto then + -- auto only has the first line to go on; it must at least split like the real delimiter there + t:check(#auto[1] >= 1, "case " .. i .. ": auto") + end + end + if c.keyed then + local keyed = dec(c.data, { header = true }) :: any + t:eq(#keyed, #c.rows - 1, "case " .. i .. ": keyed row count") + t:eq(table.concat(Types.keys(keyed[1]), "|"), table.concat(c.rows[1], "|"), "case " .. i .. ": column order") + local kb = Csv.encode(keyed) :: buffer + t:eq(buffer.tostring(kb), c.data, "case " .. i .. ": keyed re-encode (DictWriter text)") + end +end + +-- details +do + t:eq(Canon.of(dec("a,b\n\n1,2\r\n3,4\r5,6")), Canon.of({ { "a", "b" }, { "1", "2" }, { "3", "4" }, { "5", "6" } }), "line ends, blank lines") + t:eq(Canon.of(dec('"a""b",c"d,"e"x')), Canon.of({ { 'a"b', 'c"d', "ex" } }), "lenient quotes like Python") + t:eq(Canon.of(dec("a;b|c", { delimiter = "auto" })), Canon.of({ { "a", "b|c" } }), "auto delimiter") + t:eq(Canon.of(dec("x,1.5,-2,1e3,abc, 7 ", { numbers = true })), Canon.of({ { "x", 1.5, -2, 1000, "abc", 7 } }), "numbers") + t:eq(Canon.of(dec("a,b,c\n1,2")[1]), Canon.of({ "a", "b", "c" }), "ragged rows kept") + local k = dec("a,b\n1,2,3\n4", { header = true }) + t:eq(k[1].b, "2", "keyed") + t:eq(k[2].b, nil, "short keyed row") + t:eq(buffer.tostring(Csv.encode({ { 1, true, F.null, 0.5 } }) :: buffer), "1,true,,0.5\r\n", "field types") + t:eq(buffer.tostring(Csv.encode({ { "a", "b" } }, { quoteAll = true, newline = "\n" }) :: buffer), '"a","b"\n', "quoteAll") + t:eq(buffer.tostring(Csv.encode({ { "" } }) :: buffer), '""\r\n', "single empty field quoted") + local _, e = dec('a,"b') + t:eq(e and e.code, Err.TRUNCATED, "unterminated quote") + local _, e2 = dec("a", { delimiter = "ab" }) + t:eq(e2 and e2.code, Err.ARG, "bad delimiter") + local _, e3 = Csv.encode({ { {} } }) + t:eq(e3 and e3.code, Err.ARG, "bad field") + local _, e4 = dec("1\n2\n3", { maxRows = 2 }) + t:eq(e4 and e4.code, Err.LIMIT, "maxRows") + local v = F.load(buffer.fromstring("a,b\r\n1,2\r\n"), { format = "csv", header = true }) + t:eq(v[1].a, "1", "through the API") +end + +local samples = {} +for i = 1, 40 do + table.insert(samples, Fx[i].data) +end +t:fuzz("decode", function(b: buffer) + return Csv.decode(Bytes.reader(b), { delimiter = "auto", header = true, numbers = true }) +end, samples) +t:done() diff --git a/tests/data/ini.luau b/tests/data/ini.luau new file mode 100644 index 0000000..0cf8e6d --- /dev/null +++ b/tests/data/ini.luau @@ -0,0 +1,71 @@ +-- data/ini tests: configs written by Python's configparser read back to configparser's values and re-encoded byte for +-- byte, messy hand-written files read as configparser(strict = false) reads them, options (inline comments, keys +-- without values, types, strict), top-level keys, error codes, and the fuzz pass. Fixtures: tools/fixtures/ini.py. +local T = require("@tests/T") +local Ini = require("@formats/data/ini") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Canon = require("@tests/data/Canon") +local Fx = require("@tests/gen/ini") + +local t = T.suite("data/ini") + +t:eq(Ini.name, "ini", "name") +t:check(Ini.caps.decode and Ini.caps.encode, "caps") + +local function dec(s: string, opts: any?): (any, any) + return Ini.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +for i, c in Fx.written do + local v, err = dec(c.data) + t:check(v ~= nil, "written " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "written " .. i .. ": values") + t:eq(buffer.tostring(Ini.encode(v) :: buffer), c.data, "written " .. i .. ": same text") +end +for i, c in Fx.read do + local v, err = dec(c.data) + t:check(v ~= nil, "messy " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "messy " .. i .. ": values") +end + +do + local v = dec("top = 1\n[s]\na = 2 ; c\nflag\nn = 0x10\nb = Yes\n", { inlineComments = true, allowNoValue = true, types = true }) + t:eq(v.top, 1, "top-level key, typed") + t:eq(v.s.a, 2, "inline comment stripped") + t:eq(v.s.flag, true, "key without value") + t:eq(v.s.n, 16, "hex number") + t:eq(v.s.b, true, "yes -> true") + t:eq(table.concat(Types.keys(v), ","), "top,s", "order") + local o = Types.object() + Types.set(o, "name", "x") + local sub = Types.object() + Types.set(sub, "k", "multi\nline") + Types.set(sub, "inner", { z = 1 }) + Types.set(o, "sec", sub) + t:eq(buffer.tostring(Ini.encode(o) :: buffer), "name = x\n\n[sec]\nk = multi\n\tline\n\n[sec.inner]\nz = 1\n\n", "encode nested") + local function code(s: string, opts: any?): string? + local _, e = dec(s, opts) + return e and e.code + end + t:eq(code("[a]\njunk line\n"), Err.CORRUPT, "line without delimiter") + t:eq(code("[a]\nk=1\nk=2\n", { strict = true }), Err.CORRUPT, "strict duplicate key") + t:eq(code("[a]\n[a]\n", { strict = true }), Err.CORRUPT, "strict duplicate section") + t:eq(code("[a]\n= v\n"), Err.CORRUPT, "empty key") + local _, ee = Ini.encode({ ["bad=key"] = "v" }) + t:eq(ee and ee.code, Err.ARG, "unwritable key") + t:eq(Ini.sniff(Bytes.reader(buffer.fromstring("; c\n[section]\nk=v"))), 0.2, "sniff") +end + +local samples = {} +for _, c in Fx.read do + table.insert(samples, c.data) +end +for i = 1, 20 do + table.insert(samples, Fx.written[i].data) +end +t:fuzz("decode", function(b: buffer) + return Ini.decode(Bytes.reader(b), { types = true, inlineComments = true }) +end, samples) +t:done() diff --git a/tests/data/json.luau b/tests/data/json.luau new file mode 100644 index 0000000..b313221 --- /dev/null +++ b/tests/data/json.luau @@ -0,0 +1,71 @@ +-- data/json tests: the contract, the format through the API (F.load / F.save / sniffing), JSON Lines, Python's +-- json.dumps corpus through the format, and the fuzz pass. The codec itself is tested in tests/codecs/json.luau. +-- Fixtures: tools/fixtures/json.py. +local T = require("@tests/T") +local F = require("@formats") +local JsonF = require("@formats/data/json") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Canon = require("@tests/data/Canon") +local Corpus = require("@tests/gen/json_corpus") + +local t = T.suite("data/json") + +t:eq(JsonF.name, "json", "name") +t:eq(JsonF.category, "data", "category") +t:check(JsonF.caps.decode and JsonF.caps.encode, "caps") + +local function dec(s: string, opts: any?): (any, any) + return JsonF.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +for i, c in Corpus do + local v, err = dec(c.pretty) + t:check(v ~= nil, "corpus " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "corpus " .. i) + local b = JsonF.encode(v, { indent = 2 }) :: buffer + t:eq(buffer.tostring(b), c.pretty .. "\n", "corpus " .. i .. ": encode") +end + +-- through the API: sniffed, by name, saved +do + local v, err = F.load(buffer.fromstring('{"a": [1, 2], "b": null}')) + t:check(v ~= nil, "F.load sniffs json: " .. tostring(err)) + t:eq(v.b, F.null, "F.null") + local v2 = F.load(buffer.fromstring("[1, 2]"), { format = "json" }) + t:eq(v2[2], 2, "F.load format = json") + local s = F.saveString({ x = 1, y = { true, false } }, { format = "json" }) + t:eq(s, '{"x":1,"y":[true,false]}', "F.saveString json") + local back = F.data.load(buffer.fromstring(s :: string), { format = "json" }) + t:eq(back.y[1], true, "F.data.load") +end + +-- JSON Lines +do + local v = dec('{"a":1}\n{"a":2}\n\n[3]\n', { lines = true }) + t:eq(#v, 3, "lines decode count") + t:eq(v[2].a, 2, "lines decode value") + local b = JsonF.encode({ { a = 1 }, { 2, 3 } }, { lines = true }) :: buffer + t:eq(buffer.tostring(b), '{"a":1}\n[2,3]\n', "lines encode") + local _, e = dec("1\n[", { lines = true }) + t:eq(e and e.code, Err.TRUNCATED, "lines error") +end + +-- reader range: the data inside a bigger buffer +do + local big = buffer.fromstring("xx[1,2,3]yy") + local v = JsonF.decode(Bytes.reader(big, 2, 7)) + t:eq(#v, 3, "reader range") +end + +t:eq(JsonF.sniff(Bytes.reader(buffer.fromstring(' {"a":1}'))), 0.6, "sniff object") +t:eq(JsonF.sniff(Bytes.reader(buffer.fromstring("hello"))), 0, "sniff text") + +local samples = {} +for i = 1, 30 do + table.insert(samples, Corpus[i].pretty) +end +t:fuzz("decode", function(b: buffer) + return JsonF.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tests/data/msgpack.luau b/tests/data/msgpack.luau new file mode 100644 index 0000000..7b254c3 --- /dev/null +++ b/tests/data/msgpack.luau @@ -0,0 +1,96 @@ +-- data/msgpack tests: values packed by Python's msgpack decode to msgpack's own values (canonical form), re-encode to +-- the same bytes, 64-bit integers as doubles and as exact strings, timestamps / ext, streams, options, error codes, +-- and the fuzz pass. Fixtures: tools/fixtures/msgpack.py. +local T = require("@tests/T") +local Mp = require("@formats/data/msgpack") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Canon = require("@tests/data/Canon") +local Fx = require("@tests/gen/msgpack") + +local t = T.suite("data/msgpack") + +t:eq(Mp.name, "msgpack", "name") +t:check(Mp.caps.decode and Mp.caps.encode, "caps") + +local function dec(s: string | buffer, opts: any?): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + return Mp.decode(Bytes.reader(b), opts) +end + +-- ext values canonicalise like the fixture's ["ext", code, data] +local function plain(v: any): any + if Mp.isExt(v) then + return { "ext", v.type, v.data } + elseif type(v) == "table" and not Types.Date.is(v) and v ~= Types.null then + local o = if Types.isObject(v) then Types.object() else {} + for k, x in next, v do + o[k] = plain(x) + end + return o + end + return v +end + +for i, c in Fx.safe do + local v, err = dec(c.data) + t:check(v ~= nil, "safe " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, "safe " .. i .. ": value") + local b = Mp.encode(v) :: buffer + t:check(b and buffer.tostring(b) == c.data, "safe " .. i .. ": same bytes") +end +for i, c in Fx.wide do + local v, err = dec(c.data) + t:check(v ~= nil, "wide " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, "wide " .. i .. ": value") + local vs = dec(c.data, { bigInts = "string" }) + t:eq(Canon.of(plain(vs)), c.canonStr, "wide " .. i .. ": exact big integers") + t:eq(Canon.of(plain(dec(Mp.encode(v) :: buffer))), c.canon, "wide " .. i .. ": round trip") +end + +-- details +do + t:eq(Mp.isExt(dec("\xd4\x05\x07")), true, "fixext1") + local d = dec("\xd6\xff\x00\x00\x00\x00") + t:check(Types.Date.is(d) and tostring(d) == "1970-01-01T00:00:00Z", "timestamp32") + t:eq(dec("\xcf\xff\xff\xff\xff\xff\xff\xff\xff", { bigInts = "string" }), "18446744073709551615", "u64 max text") + t:eq(dec("\xd3\x80\x00\x00\x00\x00\x00\x00\x00", { bigInts = "string" }), "-9223372036854775808", "i64 min text") + t:eq(dec("\xd3\xff\xff\xff\xff\xff\xff\xff\xff"), -1, "i64 -1") + t:eq(buffer.tostring(Mp.encode(-2 ^ 40) :: buffer), "\xd3\xff\xff\xff\x00\x00\x00\x00\x00", "encode i64") + t:eq(buffer.tostring(Mp.encode(1.5, { float32 = true }) :: buffer), "\xca\x3f\xc0\x00\x00", "float32") + t:eq(buffer.tostring(Mp.encode({}) :: buffer), "\x90", "empty table = array") + t:eq(buffer.tostring(Mp.encode({}, { emptyTable = "map" }) :: buffer), "\x80", "emptyTable map") + t:eq(buffer.tostring(Mp.encode(Types.object()) :: buffer), "\x80", "Types.object = map") + t:eq(buffer.tostring(Mp.encode({ b = 1, a = 2 }) :: buffer), "\x82\xa1a\x02\xa1b\x01", "plain keys sorted") + t:eq(buffer.tostring(Mp.encode("ab", { stringsAsBin = true }) :: buffer), "\xc4\x02ab", "stringsAsBin") + t:eq(buffer.tostring(Mp.encode(Mp.ext(3, buffer.fromstring("xyz"))) :: buffer), "\xc7\x03\x03xyz", "ext8") + local all = dec("\x01\x02\xa1x", { all = true }) + t:eq(#all, 3, "stream") + t:eq(buffer.tostring(Mp.encode({ 1, "x" }, { all = true }) :: buffer), "\x01\xa1x", "encode stream") + t:eq(dec("\xc0"), Types.null, "nil -> null") + local cyc = {} + cyc[1] = cyc + local _, ce = Mp.encode(cyc) + t:eq(ce and ce.code, Err.ARG, "cycle") + local function code(s: string, o: any?): string? + local _, e = dec(s, o) + return e and e.code + end + t:eq(code("\xdd\xff\xff\xff\xff"), Err.TRUNCATED, "huge array count") + t:eq(code("\xa5ab"), Err.TRUNCATED, "short string") + t:eq(code("\xc1"), Err.CORRUPT, "reserved byte") + t:eq(code("\x01\x02"), Err.CORRUPT, "trailing data") + t:eq(code(string.rep("\x91", 600) .. "\x01"), Err.LIMIT, "depth") +end + +local samples = {} +for i = 5, 60 do + if #Fx.safe[i].data < 3000 then + table.insert(samples, Fx.safe[i].data) + end +end +t:fuzz("decode", function(b: buffer) + return Mp.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tests/data/plist.luau b/tests/data/plist.luau new file mode 100644 index 0000000..231a20f --- /dev/null +++ b/tests/data/plist.luau @@ -0,0 +1,86 @@ +-- data/plist tests: values written by Python's plistlib as XML and binary decode to plistlib's values; our XML writer +-- reproduces plistlib's XML byte for byte; binary-only values (UIDs, 64-bit integers); a hand-written XML plist; +-- error codes; the fuzz pass (XML and binary). Fixtures: tools/fixtures/plist.py. +local T = require("@tests/T") +local F = require("@formats") +local Plist = require("@formats/data/plist") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Canon = require("@tests/data/Canon") +local Fx = require("@tests/gen/plist") + +local t = T.suite("data/plist") + +t:eq(Plist.name, "plist", "name") +t:check(Plist.caps.decode and Plist.caps.encode, "caps") + +local function dec(s: string, opts: any?): (any, any) + return Plist.decode(Bytes.reader(buffer.fromstring(s)), opts) +end +local function plain(v: any): any + if Plist.isUid(v) then + return { "uid", v.uid } + elseif type(v) == "table" and not Types.Date.is(v) then + local o = if Types.isObject(v) then Types.object() else {} + for k, x in next, v do + o[k] = plain(x) + end + return o + end + return v +end + +for i, c in Fx.cases do + local v, err = dec(c.xml) + t:check(v ~= nil, "xml " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "xml " .. i .. ": value") + local vb, berr = dec(c.binary) + t:check(vb ~= nil, "binary " .. i .. ": " .. tostring(berr)) + t:eq(Canon.of(vb), c.canon, "binary " .. i .. ": value") + t:eq(buffer.tostring(Plist.encode(v) :: buffer), c.xml, "xml " .. i .. ": same text as plistlib") +end +for i, c in Fx.wide do + local v, err = dec(c.binary) + t:check(v ~= nil, "wide " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, "wide " .. i .. ": value") +end +do + local v = dec(Fx.extra) + t:eq(Canon.of(v), Fx.extraCanon, "hand-written plist") + t:eq(v.hex, 31, "hex integer") + local f = F.load(buffer.fromstring(Fx.cases[1].binary)) + t:check(f ~= nil, "F.load sniffs binary plists") + local fx = F.load(buffer.fromstring(Fx.cases[1].xml)) + t:eq(Canon.of(fx), Fx.cases[1].canon, "F.load sniffs XML plists over plain XML") + t:eq(dec("x"), "x", "bare root value") + local function code(s: string): string? + local _, e = dec(s) + return e and e.code + end + t:eq(code("a"), Err.CORRUPT, "key without value") + t:eq(code("x"), Err.CORRUPT, "bad integer") + t:eq(code("!!"), Err.CORRUPT, "bad base64") + t:eq(code(""), Err.CORRUPT, "unknown element") + t:eq(code("bplist00"), Err.TRUNCATED, "short binary") + local _, ne = Plist.encode({ a = F.null }) + t:eq(ne and ne.code, Err.ARG, "null cannot be written") + local _, ke = Plist.encode({ [1] = 1, x = 2 }) + t:eq(ke and ke.code, Err.ARG, "non-string key") + -- a binary plist with a cycle: array 0 -> [array 0] + local cyc = "bplist00" .. "\xa1\x00" .. "\x08" .. string.rep("\0", 6) .. "\1\1" .. "\0\0\0\0\0\0\0\1" .. "\0\0\0\0\0\0\0\0" .. "\0\0\0\0\0\0\0\10" + t:eq(code(cyc), Err.CORRUPT, "reference cycle") +end + +local samples = {} +for i = 1, 25 do + table.insert(samples, Fx.cases[i].xml) + table.insert(samples, Fx.cases[i].binary) +end +t:fuzz("decode", function(b: buffer) + return Plist.decode(Bytes.reader(b)) +end, samples, { keepHeader = 0 }) +t:fuzz("decode binary (header kept)", function(b: buffer) + return Plist.decode(Bytes.reader(b)) +end, { Fx.cases[3].binary, Fx.cases[4].binary, Fx.wide[1].binary }, { keepHeader = 8, mutations = 200, garbage = 0 }) +t:done() diff --git a/tests/data/toml.luau b/tests/data/toml.luau new file mode 100644 index 0000000..4e2babc --- /dev/null +++ b/tests/data/toml.luau @@ -0,0 +1,121 @@ +-- data/toml tests: the toml-test suite's TOML 1.0 files (every valid/ case decodes to its expected value, every +-- invalid/ case fails), a tomli-w corpus against Python's tomllib, encoder round trips (decode(encode(v)) is the same +-- value) and exact encoder output, options, error codes, the contract and the fuzz pass. Fixtures: tools/fixtures/toml.py. +local T = require("@tests/T") +local Toml = require("@formats/data/toml") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Canon = require("@tests/data/Canon") +local Suite = require("@tests/gen/toml_suite") +local Corpus = require("@tests/gen/toml_corpus") + +local t = T.suite("data/toml") + +t:eq(Toml.name, "toml", "name") +t:eq(Toml.category, "data", "category") +t:check(Toml.caps.decode and Toml.caps.encode, "caps") + +local function dec(s: string, opts: any?): (any, any) + return Toml.decode(Bytes.reader(buffer.fromstring(s)), opts) +end +local function enc(v: any, opts: any?): (string?, any) + local b, e = Toml.encode(v, opts) + return if b then buffer.tostring(b) else nil, e +end + +-- 1. toml-test +local nv, ni, rt = 0, 0, 0 +for _, c in Suite do + local v, err = dec(c.data) + if c.valid then + t:check(v ~= nil, c.name .. ": parses (" .. tostring(err) .. ")") + t:eq(Canon.of(v), c.canon, c.name .. ": value") + -- the encoder's output reads back as the same value (floats that are integral become integers, so compare + -- the decoded values, not the toml-test canon) + local s, eerr = enc(v) + t:check(s ~= nil, c.name .. ": encodes (" .. tostring(eerr) .. ")") + local back, berr = dec(s :: string) + t:check(back ~= nil, c.name .. ": re-decodes (" .. tostring(berr) .. ")\n" .. tostring(s)) + t:eq(Canon.of(back), Canon.of(v), c.name .. ": round trip") + nv += 1 + rt += 1 + else + t:check(v == nil and Err.is(err), c.name .. ": rejected") + ni += 1 + end +end +t:note("toml-test 1.0: %d valid decoded and round-tripped, %d invalid rejected", nv, ni) + +-- 2. tomli-w corpus vs tomllib +for i, c in Corpus do + local v, err = dec(c.data) + t:check(v ~= nil, "corpus " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "corpus " .. i .. ": value") + local s = enc(v) :: string + t:eq(Canon.of(dec(s)), c.canon, "corpus " .. i .. ": round trip") + t:eq(Canon.of(dec(enc(v, { inline = true }) :: string)), c.canon, "corpus " .. i .. ": inline round trip") +end + +-- 3. API details +do + local v = dec('z = 1\na = 2\n[t]\ny = "x"\nb = 1979-05-27T07:32:00.5-07:00\n[[arr]]\nk = 1\n[[arr]]\nk = 2\n') + t:eq(table.concat(Types.keys(v), ","), "z,a,t,arr", "key order") + t:check(Types.Date.is(v.t.b) and v.t.b.kind == "datetime" and v.t.b.offset == -420, "datetime value") + t:eq(tostring(v.t.b), "1979-05-27T07:32:00.5-07:00", "datetime text") + t:eq(v.arr[2].k, 2, "array of tables") + t:eq(enc(v), 'z = 1\na = 2\n\n[t]\ny = "x"\nb = 1979-05-27T07:32:00.5-07:00\n\n[[arr]]\nk = 1\n\n[[arr]]\nk = 2\n', "encode text") + t:eq(enc({ b = { 1, 2.5, "s" }, a = { x = true } }), 'b = [1, 2.5, "s"]\n\n[a]\nx = true\n', "plain tables: scalars first, sorted") + t:eq(enc({ ["a b"] = "q\"\n\1" }), '"a b" = "q\\"\\n\\u0001"\n', "key / string escapes") + t:eq(enc({ a = { x = 1 } }, { inline = true }), "a = { x = 1 }\n", "inline option") + t:eq(enc({ f = 0 / 0, g = math.huge, h = 1e300, i = -0.5 }), "f = nan\ng = inf\nh = 1e+300\ni = -0.5\n", "floats") + t:eq(enc({ a = { b = { c = 1 } } }, { indent = 2 }), "[a]\n\n [a.b]\n c = 1\n", "indent") + local big = dec("a = 9223372036854775807\nb = 0x7fffffffffffffff\nc = 12", { bigInts = "string" }) + t:eq(big.a, "9223372036854775807", "bigInts string") + t:eq(big.b, "0x7fffffffffffffff", "bigInts string hex") + t:eq(big.c, 12, "small ints stay numbers") + t:eq(dec("a = 9223372036854775807").a, 9223372036854775807, "bigInts number") + local _, e1 = enc({ a = Types.null }) + t:eq(e1 and e1.code, Err.ARG, "null is an error") + local cyc = {} + cyc.self = cyc + local _, e2 = enc(cyc) + t:eq(e2 and e2.code, Err.ARG, "cycle is an error") + local _, e3 = enc({ 1, 2 }) + t:eq(e3 and e3.code, Err.ARG, "top level must be a table") + local _, e4 = enc({ [1] = 1, x = 2 }) + t:eq(e4 and e4.code, Err.ARG, "non-string key") +end + +-- 4. errors +local function code(s: string): (string?, number?) + local _, e = dec(s) + return e and e.code, e and e.offset +end +t:eq(code('a = "abc'), Err.TRUNCATED, "unterminated string") +t:eq(code("a = 1\na = 2"), Err.CORRUPT, "duplicate key") +t:eq(code("[a]\n[a]"), Err.CORRUPT, "duplicate table") +t:eq(code("a = 01"), Err.CORRUPT, "leading zero") +t:eq(code("a = 9223372036854775808"), Err.CORRUPT, "int64 overflow") +t:eq(select(2, code("x = 1\na = tru")), 10, "error offset") +t:eq(Toml.sniff(Bytes.reader(buffer.fromstring("# c\n[server]\nport = 80\n"))), 0.2, "sniff") +t:eq(Toml.sniff(Bytes.reader(buffer.fromstring("{\"a\": 1}"))), 0, "sniff json") + +-- 5. fuzz +local samples = {} +for _, c in Suite do + if c.valid and #samples < 80 and #c.data < 400 then + table.insert(samples, c.data) + end +end +for i = 1, 20 do + table.insert(samples, Corpus[i].data) +end +t:fuzz("decode", function(b: buffer) + return Toml.decode(Bytes.reader(b)) +end, samples) +t:fuzz("encode(decode)", function(b: buffer) + local v = Toml.decode(Bytes.reader(b)) + return v and Toml.encode(v) +end, samples, { garbage = 20 }) +t:done() diff --git a/tests/data/xml.luau b/tests/data/xml.luau new file mode 100644 index 0000000..6edbe02 --- /dev/null +++ b/tests/data/xml.luau @@ -0,0 +1,49 @@ +-- data/xml tests: the contract, the format through the API (F.load / F.save / sniffing), documents from Python's +-- ElementTree fixtures decoded and re-encoded through the format, and the fuzz pass. The codec itself is tested in +-- tests/codecs/xml.luau. Fixtures: tools/fixtures/xml.py. +local T = require("@tests/T") +local F = require("@formats") +local XmlF = require("@formats/data/xml") +local Xml = require("@formats/codecs/Xml") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Docs = require("@tests/gen/xml_docs") + +local t = T.suite("data/xml") + +t:eq(XmlF.name, "xml", "name") +t:eq(XmlF.category, "data", "category") +t:check(XmlF.caps.decode and XmlF.caps.encode, "caps") + +for i = 1, 60 do + local d = Docs[i] + local doc, err = XmlF.decode(Bytes.reader(buffer.fromstring(d.data)), { comments = true, cdata = true, whitespace = true }) + t:check(doc ~= nil, "doc " .. i .. ": " .. tostring(err)) + local b, eerr = XmlF.encode(doc :: any) + t:check(b ~= nil, "doc " .. i .. ": encode " .. tostring(eerr)) + local again = XmlF.decode(Bytes.reader(b :: buffer), { comments = true, cdata = true, whitespace = true }) + t:check(again ~= nil, "doc " .. i .. ": re-decode") + t:eq(Xml.text((again :: any).root), Xml.text((doc :: any).root), "doc " .. i .. ": same text") +end + +do + local doc, err = F.load(buffer.fromstring('t')) + t:check(doc ~= nil, "F.load sniffs xml: " .. tostring(err)) + t:eq(doc.root.name, "r", "root") + local s = F.saveString(doc, { format = "xml" }) + t:eq(s, '\nt', "F.saveString") + local _, e = XmlF.encode(5 :: any) + t:eq(e and e.code, Err.ARG, "encode argument check") + local _, e2 = F.load(buffer.fromstring(""), { format = "xml" }) + t:eq(e2 and e2.code, Err.CORRUPT, "error through the API") + t:eq(e2 and e2.format, "xml", "error tagged with the format") +end + +local samples = {} +for i = 1, 30 do + table.insert(samples, Docs[i].data) +end +t:fuzz("decode", function(b: buffer) + return XmlF.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tests/data/yaml.luau b/tests/data/yaml.luau new file mode 100644 index 0000000..e804e39 --- /dev/null +++ b/tests/data/yaml.luau @@ -0,0 +1,198 @@ +-- data/yaml tests: the yaml-test-suite (every case with an in.json must decode to it, every error case must be +-- rejected, the valid cases without JSON must decode), a random corpus dumped by PyYAML in five styles (block, flow, +-- indent 4 with explicit markers, sorted / narrow, multi-document) compared with Python's values, encoder round trips, +-- options, errors and limits, the API, and the fuzz pass. Fixtures: tools/fixtures/yaml.py. +local T = require("@tests/T") +local F = require("@formats") +local Yaml = require("@formats/data/yaml") +local Json = require("@formats/codecs/Json") +local Types = require("@formats/Types") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Canon = require("@tests/data/Canon") +local Suite = require("@tests/gen/yaml_suite") +local Corpus = require("@tests/gen/yaml_corpus") + +local t = T.suite("data/yaml") + +t:eq(Yaml.name, "yaml", "name") +t:eq(Yaml.category, "data", "category") +t:check(Yaml.caps.decode and Yaml.caps.encode, "caps") + +local function dec(s: string, opts: any?): (any, any) + return Yaml.decode(Bytes.reader(buffer.fromstring(s)), opts) +end +local function enc(v: any, opts: any?): string? + local b = Yaml.encode(v, opts) + return if b then buffer.tostring(b) else nil +end + +-- 1. yaml-test-suite +local SKIP = { -- !!binary decodes to a buffer; the suite's JSON keeps the base64 text + ["565N"] = true, + ["name/construct-binary"] = true, +} +local pass, valid, rejected, errors, other, otherOk = 0, 0, 0, 0, 0, 0 +for _, c in Suite do + local v, e = dec(c.yaml, { all = true, tags = "ignore" }) + t:check(e == nil or not string.find(e.message, "internal error", 1, true), c.name .. ": " .. tostring(e)) + if c.error then + errors += 1 + t:check(v == nil, c.name .. ": an error case is rejected") + rejected += if v == nil then 1 else 0 + elseif c.json and not SKIP[c.name] then + valid += 1 + t:check(v ~= nil, c.name .. ": decodes (" .. tostring(e) .. ")") + local want = {} + for _, x in Json.lines(c.json) do + table.insert(want, Canon.of(x)) + end + local got = {} + for _, d in v do + local s = Json.encode(d, { nan = "null" }) + table.insert(got, if s then Canon.of(Json.decode(s)) else "?") + end + t:eq(table.concat(got, "|"), table.concat(want, "|"), c.name .. ": value") + pass += 1 + elseif not c.json then + other += 1 + otherOk += if v ~= nil or (e and e.code == Err.UNSUPPORTED) then 1 else 0 + end +end +t:note("yaml-test-suite: %d of %d JSON cases match, %d of %d error cases rejected, %d of %d other valid cases decode or say UNSUPPORTED", pass, valid, rejected, errors, otherOk, other) +t:check(otherOk == other, "valid cases without JSON never fail as CORRUPT") + +-- 2. PyYAML's output in five styles +for i, c in Corpus do + for style, text in c.texts do + if style == "multi" then + local v, e = dec(text, { all = true }) + t:check(v ~= nil, "corpus " .. i .. " " .. style .. ": " .. tostring(e)) + t:eq(Canon.of(v), c.multi, "corpus " .. i .. " " .. style) + else + local v, e = dec(text) + t:check(v ~= nil or e == nil, "corpus " .. i .. " " .. style .. ": " .. tostring(e)) + t:eq(Canon.of(v), c.canon, "corpus " .. i .. " " .. style) + end + end + -- our own output reads back the same (indent 2 and 4, explicit start) + local v = dec(c.texts.block) + for _, o in { {}, { indent = 4 }, { explicitStart = true } } do + local s = enc(v, o) + t:check(s ~= nil, "corpus " .. i .. ": encodes") + t:eq(Canon.of(dec(s :: string)), c.canon, "corpus " .. i .. ": round trip " .. tostring(s)) + end + local m = dec(c.texts.multi, { all = true }) + t:eq(Canon.of(dec(enc(m, { all = true }) :: string, { all = true })), c.multi, "corpus " .. i .. ": multi round trip") +end + +-- 3. details +do + local v = dec("b: 1\na: 2\nc: {}\nd: []\ne:\nf: ~\n") + t:eq(table.concat(Types.keys(v), ","), "b,a,c,d,e,f", "key order") + t:check(Types.isObject(v.c), "empty flow map is an object") + t:eq(v.e, Types.null, "empty value is null") + t:eq(enc(v), "b: 1\na: 2\nc: {}\nd: []\ne: null\nf: null\n", "encode keeps the order") + local s = dec("a: &x [1, 2]\nb: *x\n") + t:check(s.a == s.b, "aliases are shared references") + t:eq(enc(s), "a: &id001\n - 1\n - 2\nb: *id001\n", "shared tables get anchors") + local n = dec("[0o17, 0x1F, +12, -0.5e1, .5, .inf, -.Inf, .nan, 1_000, 0b11, yes, ~, Null, TRUE]") + t:eq(n[1], 15, "0o") + t:eq(n[2], 31, "0x") + t:eq(n[3], 12, "+int") + t:eq(n[4], -5, "float exp") + t:eq(n[5], 0.5, ".5") + t:eq(n[6], math.huge, ".inf") + t:eq(n[7], -math.huge, "-.Inf") + t:check(n[8] ~= n[8], ".nan") + t:eq(n[9], "1_000", "1.1 ints are strings") + t:eq(n[10], "0b11", "0b is a string") + t:eq(n[11], "yes", "yes is a string") + t:eq(n[12], Types.null, "~") + t:eq(n[13], Types.null, "Null") + t:eq(n[14], true, "TRUE") + local tg = dec("a: !!str 12\nb: !!float 3\nc: !!binary aGVsbG8=\nd: !!timestamp 2001-12-14T21:59:43Z\ne: !!int '7'\n") + t:eq(tg.a, "12", "!!str") + t:eq(tg.b, 3, "!!float") + t:eq(buffer.tostring(tg.c), "hello", "!!binary") + t:check(Types.Date.is(tg.d), "!!timestamp") + t:eq(tg.e, 7, "!!int on a quoted scalar") + local _, te = dec("a: !custom x") + t:eq(te and te.code, Err.UNSUPPORTED, "unknown tags are UNSUPPORTED") + t:eq(dec("a: !custom x", { tags = "ignore" }).a, "x", "tags = ignore") + t:eq(dec("--- 1\n--- 2\n"), 1, "the first document") + t:eq(#dec("--- 1\n--- 2\n", { all = true }), 2, "all documents") + t:eq(dec(""), Types.null, "empty stream") + t:eq(dec("k: |\n a\n b\n\nz: >+\n f\n g\n\n").k, "a\nb\n", "literal") + t:eq(dec("k: |\n a\n b\n\nz: >+\n f\n g\n\n").z, "f g\n\n", "folded keep") + t:eq(dec("? a\n: b\n").a, "b", "explicit key") + t:eq(dec("[a: 1, {b: 2}]")[1].a, 1, "single-pair flow mapping") + -- strings that need quoting survive + for _, str in { "", "true", "null", "12", "1.5", "- x", "a: b", "# c", "x #y", " lead", "tail ", "multi\nline", "two\n\n", "\ttab", "é", "\0\1", "'", '"', "yes", "on", "~", "[", "@", "&a", "*a", "!t", "%", "---", "...", "a\u{2028}b", ".inf", "0x10", "0o7", "-", "?", ":" } do + local v2 = dec(enc({ k = str }) :: string) + t:eq(v2 and v2.k, str, "string round trip " .. string.format("%q", str)) + end + for _, x in { 0.1, -2.5e-8, 1e300, 2 ^ 53, -0.0, 123456789, math.huge, -math.huge } do + t:eq(dec(enc({ x }) :: string)[1], x, "number round trip " .. tostring(x)) + end + local cyc = {} + cyc.self = cyc + local _, ce = Yaml.encode(cyc) + t:eq(ce and ce.code, Err.ARG, "cycles are an error") + local _, fe = Yaml.encode({ f = print }) + t:eq(fe and fe.code, Err.ARG, "functions are an error") + t:eq(enc(buffer.fromstring("hi")), "!!binary aGk=\n", "buffers as !!binary") +end + +-- 4. errors and limits +local function code(s: string, opts: any?): string? + local _, e = dec(s, opts) + return e and e.code +end +t:eq(code("a: [1, 2"), Err.TRUNCATED, "unterminated flow") +t:eq(code('a: "x'), Err.TRUNCATED, "unterminated quote") +t:eq(code("a: b: c"), Err.CORRUPT, "mapping on its key's line") +t:eq(code("a: *nope"), Err.CORRUPT, "undefined alias") +t:eq(code("a:\n b: 1\n c: 2"), Err.CORRUPT, "bad indentation") +t:eq(code("[[1]]: x"), Err.UNSUPPORTED, "collection keys") +t:eq(code(string.rep("[", 600) .. string.rep("]", 600)), Err.LIMIT, "depth limit") +do + local bomb = { "a: &a [x, x, x, x, x, x, x, x, x, x]" } + for i = 2, 8 do + local prev = string.char(96 + i - 1) + table.insert(bomb, string.format("%s: &%s [*%s, *%s, *%s, *%s, *%s, *%s, *%s, *%s, *%s, *%s]", string.char(96 + i), string.char(96 + i), prev, prev, prev, prev, prev, prev, prev, prev, prev, prev)) + end + t:eq(code(table.concat(bomb, "\n")), Err.LIMIT, "alias bomb") + t:check(dec(table.concat(bomb, "\n", 1, 3)) ~= nil, "small alias trees are fine") +end +do + local _, e = dec("a: 1\nb: [1, }\n") + t:eq(e and e.offset, 12, "error offset") +end + +-- 5. API +do + local v, err = F.load(buffer.fromstring("---\nname: x\nlist:\n - 1\n")) + t:check(v ~= nil, "F.load sniffs yaml: " .. tostring(err)) + t:eq(v.list[1], 1, "F.load value") + t:eq(F.saveString(v, { format = "yaml" }), "name: x\nlist:\n - 1\n", "F.saveString yaml") +end + +local samples = {} +for i = 1, 30 do + table.insert(samples, Corpus[i].texts.block) + table.insert(samples, Corpus[i].texts.flow) +end +for i = 1, 400, 7 do + if Suite[i] then + table.insert(samples, Suite[i].yaml) + end +end +t:fuzz("decode", function(b: buffer) + return Yaml.decode(Bytes.reader(b), { all = true }) +end, samples) +t:fuzz("encode(decode)", function(b: buffer) + local v = Yaml.decode(Bytes.reader(b)) + return v and Yaml.encode(v) +end, samples, { garbage = 20 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index e42b6c3..0923cd7 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -130,4 +130,45 @@ do end) end end +do + local Json = require("@formats/codecs/Json") + local JB = require("@tests/gen/json_bench") + local v = assert(Json.decode(JB.text)) + assert(Json.encode(v) == JB.compact, "json bench mismatch") + bench("json decode (indented)", 5, #JB.text, function() + Json.decode(JB.text) + end) + bench("json decode (compact)", 5, #JB.compact, function() + Json.decode(JB.compact) + end) + bench("json encode (compact, sorted)", 5, #JB.compact, function() + Json.encode(v) + end) +end +do + local Xml = require("@formats/codecs/Xml") + local XB = require("@tests/gen/xml_bench") + local doc = assert(Xml.decode(XB.text)) + bench("xml decode (DOM)", 5, #XB.text, function() + Xml.decode(XB.text) + end) + bench("xml events", 5, #XB.text, function() + for _ in Xml.events(XB.text) do + end + end) + bench("xml encode", 5, #XB.text, function() + Xml.encode(doc) + end) +end +do + local Yaml = require("@formats/data/yaml") + local YB = require("@tests/gen/yaml_bench") + local yb = buffer.fromstring(YB.text) + local v = assert(Yaml.decode(Bytes.reader(yb))) + bench("yaml decode (block)", 3, #YB.text, function() + Yaml.decode(Bytes.reader(yb)) + end) + bench("yaml encode", 3, #YB.text, function() + Yaml.encode(v) + end) end diff --git a/tools/bench.sh b/tools/bench.sh index 6b52612..64e3012 100644 --- a/tools/bench.sh +++ b/tools/bench.sh @@ -3,7 +3,7 @@ cd "$(dirname "$0")/.." || exit 1 LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')} LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')} -python3 -I tools/fixtures.py deflate png zstd brotli bzip2 lzma fonts > /dev/null || exit 1 +python3 -I tools/fixtures.py > /dev/null || exit 1 python3 -I tools/build.py luajit > /dev/null || exit 1 "$LUAU" --codegen -O2 tools/bench.luau "$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua diff --git a/tools/fixtures/_data_common.py b/tools/fixtures/_data_common.py new file mode 100644 index 0000000..4ac47e8 --- /dev/null +++ b/tools/fixtures/_data_common.py @@ -0,0 +1,110 @@ +# Shared helpers for the data-format fixture generators (json, xml, csv, toml, yaml, msgpack, cbor, plist, ...): +# fetch(url, sha256) -> a nix store path of an unpacked tarball (official test suites, pinned by hash) +# canon(value) -> the canonical text a Luau test computes too (tests/data/_canon.luau): typed, sorted keys, +# numbers as %.17g, so Python's parse and ours compare exactly. +import os, subprocess, datetime + + +def fetch(url, sha256): + expr = 'builtins.fetchTarball { url = "%s"; sha256 = "%s"; }' % (url, sha256) + out = subprocess.run(["nix", "eval", "--raw", "--impure", "--expr", expr], capture_output=True, check=True) + return out.stdout.decode() + + +def _b(s): + if isinstance(s, str): + return s.encode("utf-8", "surrogatepass") + return bytes(s) + + +def canon(v): + """null n; true t; false f; number #%d (integral, under 2^53) or #%.17g; string s:; + bytes b:; list [..]; dict {k v ...} with keys sorted by their canon bytes; dates d""" + out = bytearray() + _canon(v, out) + return bytes(out) + + +def num(x): + x = float(x) + if x != x: + return b"#nan" + if x in (float("inf"), float("-inf")): + return b"#inf" if x > 0 else b"#-inf" + if x == int(x) and abs(x) < 2 ** 53: + return b"#%d" % int(x) + return b"#" + ("%.17g" % x).encode() + + +def _canon(v, out): + if v is None: + out += b"n" + elif v is True: + out += b"t" + elif v is False: + out += b"f" + elif isinstance(v, (int, float)): + out += num(v) + elif isinstance(v, str): + b = _b(v) + out += b"s%d:" % len(b) + b + elif isinstance(v, (bytes, bytearray)): + out += b"b%d:" % len(v) + bytes(v) + elif isinstance(v, (list, tuple)): + out += b"[" + for x in v: + _canon(x, out) + out += b"," + out += b"]" + elif isinstance(v, dict): + items = [] + for k, x in v.items(): + kb = bytearray() + _canon(k, kb) + items.append((bytes(kb), x)) + items.sort(key=lambda p: p[0]) + out += b"{" + for kb, x in items: + out += kb + b"=" + _canon(x, out) + out += b"," + out += b"}" + elif isinstance(v, (datetime.datetime, datetime.date, datetime.time)): + out += b"d" + date_text(v).encode() + else: + raise TypeError("canon: %r" % type(v)) + + +def date_text(v): + """RFC 3339 the way Types.Date prints: fraction without trailing zeros, Z for +00:00""" + def frac(us): + return ("." + ("%06d" % us).rstrip("0")) if us else "" + + def tz(t): + off = t.utcoffset() + if off is None: + return "" + m = int(off.total_seconds()) // 60 + if m == 0: + return "Z" + sign = "-" if m < 0 else "+" + m = abs(m) + return "%s%02d:%02d" % (sign, m // 60, m % 60) + + if isinstance(v, datetime.datetime): + return "%04d-%02d-%02dT%02d:%02d:%02d%s%s" % (v.year, v.month, v.day, v.hour, v.minute, v.second, + frac(v.microsecond), tz(v)) + if isinstance(v, datetime.date): + return "%04d-%02d-%02d" % (v.year, v.month, v.day) + return "%02d:%02d:%02d%s" % (v.hour, v.minute, v.second, frac(v.microsecond)) + + +def python(ctx, packages, body): + """run body (with these helpers prepended, so canon() / date_text() exist) under a nix python with packages; + returns stdout bytes, raising with the script's stderr on failure""" + import subprocess as sp + src = open(os.path.abspath(__file__)).read() + try: + return ctx.python(packages, src + "\n" + body) + except sp.CalledProcessError as e: + raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:]) diff --git a/tools/fixtures/cbor.py b/tools/fixtures/cbor.py new file mode 100644 index 0000000..e0f3166 --- /dev/null +++ b/tools/fixtures/cbor.py @@ -0,0 +1,108 @@ +# data/cbor fixtures: RFC 8949 Appendix A examples and random values encoded by Python's cbor2 (through nix): every +# integer width (and bignums), floats, text / byte strings, nested arrays / maps, dates (tags 0 / 1), other tags, +# simple values, undefined, indefinite-length items (written by hand), with the canonical form of cbor2's decode. +# tests/gen/cbor.luau { appendix = { { hex, data, canon } }, safe = { { data, canon } }, wide = { { data, canon, +# canonStr } } } safe: our decode + encode gives the same bytes; wide: big integers (doubles / exact text) +import importlib.util, os, pickle + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + +APPENDIX = """00 01 0a 17 1818 1819 1864 1903e8 1a000f4240 1b000000e8d4a51000 1bffffffffffffffff c249010000000000000000 +3bffffffffffffffff c349010000000000000000 20 29 3863 3903e7 f90000 f98000 f93c00 fb3ff199999999999a f93e00 f97bff +fa47c35000 fa7f7fffff fb7e37e43c8800759c f90001 f90400 f9c400 fbc010666666666666 f97c00 f97e00 f9fc00 fa7f800000 +fa7fc00000 faff800000 fb7ff0000000000000 fb7ff8000000000000 fbfff0000000000000 f4 f5 f6 f7 f0 f818 f8ff +c074323031332d30332d32315432303a30343a30305a c11a514b67b0 c1fb41d452d9ec200000 d74401020304 +d818456449455446 d82076687474703a2f2f7777772e6578616d706c652e636f6d 40 4401020304 60 6161 6449455446 62225c +62c3bc 63e6b0b4 64f0908591 80 83010203 8301820203820405 98190102030405060708090a0b0c0d0e0f101112131415161718181819 +a0 a201020304 a26161016162820203 826161a161626163 a56161614161626142616361436164614461656145 5f42010243030405ff +7f657374726561646d696e67ff 9fff 9f018202039f0405ffff 9f01820203820405ff 83018202039f0405ff 83019f0203ff820405 +9f0102030405060708090a0b0c0d0e0f101112131415161718181819ff bf61610161629f0203ffff 826161bf61626163ff +bf6346756ef563416d7421ff""" + +BODY = r''' +import cbor2, pickle, random, sys, datetime +from collections.abc import Mapping +HEXES = sys.argv[1:] if False else HEXLIST +def conv(v): + if v is cbor2.undefined: + return ["undefined"] + if isinstance(v, cbor2.CBORSimpleValue): + return ["simple", v.value] + if isinstance(v, cbor2.CBORTag): + return ["tag", v.tag, conv(v.value)] + if isinstance(v, (list, tuple)): + return [conv(x) for x in v] + if isinstance(v, Mapping) or hasattr(v, "items"): + return {(tuple(conv(k)) if isinstance(k, list) else k): conv(x) for k, x in v.items()} + return v +def cstr(v): + if isinstance(v, cbor2.CBORTag): + return cbor2.CBORTag(v.tag, cstr(v.value)) + if isinstance(v, int) and not isinstance(v, bool) and abs(v) >= 2**53: + return str(v) + if isinstance(v, (list, tuple)): + return [cstr(x) for x in v] + if isinstance(v, Mapping) or hasattr(v, "items"): + return {k: cstr(x) for k, x in v.items()} + return v +out = {"appendix": [], "safe": [], "wide": []} +for h in HEXES: + data = bytes.fromhex(h) + try: + v = cbor2.loads(data) + except Exception: + out["appendix"].append({"hex": h, "data": data, "error": True}) # e.g. f818: invalid since RFC 8949 + continue + if type(v).__name__ in ("Decimal", "Fraction", "UUID") or (isinstance(v, str) and h.startswith("d820")): + continue # semantic tags cbor2 interprets and we keep tagged + out["appendix"].append({"hex": h, "data": data, "canon": canon(conv(v)), "canonStr": canon(conv(cstr(v)))}) +rng = random.Random(9) +def rint(wide): + lim = rng.choice([23, 24, 255, 256, 65535, 65536, 2**32 - 1, 2**32, 2**53 - 1]) + if wide and rng.random() < 0.4: + lim = rng.choice([2**64 - 1, 2**70]) + v = rng.randrange(0, lim + 1) + return -v - 1 if rng.random() < 0.5 else v +def rstr(): + return "".join(rng.choice("abé中\U0001f600 \n\x00") for _ in range(rng.choice([0, 1, 23, 24, 255, 300]))) +def rval(d, wide): + r = rng.random() + if d > 3 or r < 0.5: + k = rng.randrange(10) + if k == 0: return None + if k == 1: return rng.random() < 0.5 + if k in (2, 3): return rint(wide) + if k == 4: + f = rng.uniform(-1e6, 1e6) * 10 ** rng.randrange(-5, 5) + return f if not f.is_integer() else f + 0.5 + if k == 5: return rstr() + if k == 6: return rng.randbytes(rng.choice([0, 3, 24, 256])) + if k == 7: + return datetime.datetime.fromtimestamp(rng.randrange(0, 2**33), datetime.timezone.utc) + if k == 8: + return cbor2.CBORTag(rng.choice([6, 1000, 100000]), rval(d + 1, wide)) + return rng.choice([cbor2.undefined, cbor2.CBORSimpleValue(rng.choice([0, 19, 32, 255]))]) + if r < 0.75: + return [rval(d + 1, wide) for _ in range(rng.choice([0, 1, 3, 23, 24] if d < 2 else [0, 1, 3]))] + m = {} + for _ in range(rng.choice([0, 1, 3, 23, 24] if d < 2 else [0, 1, 3])): + key = rint(False) if rng.random() < 0.3 else "".join(rng.choice("abcé") for _ in range(rng.randrange(6))) + m[key] = rval(d + 1, wide) + return m +for i in range(250): + data = cbor2.dumps(rval(0, False)) + out["safe"].append({"data": data, "canon": canon(conv(cbor2.loads(data)))}) +for i in range(120): + data = cbor2.dumps(rval(0, True)) + v = cbor2.loads(data) + out["wide"].append({"data": data, "canon": canon(conv(v)), "canonStr": canon(conv(cstr(v)))}) +sys.stdout.buffer.write(pickle.dumps(out, protocol=4)) +''' + + +def generate(ctx): + hexes = APPENDIX.split() + out = pickle.loads(C.python(ctx, ["cbor2"], "HEXLIST = %r\n" % hexes + BODY)) + ctx.emit("cbor", out) diff --git a/tools/fixtures/csv.py b/tools/fixtures/csv.py new file mode 100644 index 0000000..4ec279f --- /dev/null +++ b/tools/fixtures/csv.py @@ -0,0 +1,43 @@ +# data/csv fixtures: random tables (quotes, delimiters, CR / LF / CRLF inside fields, empty fields, unicode) written +# by Python's csv.writer / DictWriter in several dialects, with the rows csv.reader reads back (blank rows dropped: +# we skip blank lines). +# tests/gen/csv.luau { { data, delimiter, rows = { { field } }, keyed? } } +# keyed: the file has a header row (DictWriter) +import csv, io + + +def rand_field(rng): + alph = 'ab ,;\t|"\n\ré中1.' + k = rng.random() + if k < 0.15: + return "" + if k < 0.3: + return str(rng.randrange(-1000, 1000)) + return "".join(rng.choice(alph) for _ in range(rng.randrange(1, 8))) + + +def generate(ctx): + rng = ctx.rng(13) + cases = [] + for i in range(200): + delim = rng.choice([",", ",", ";", "\t", "|"]) + ncol = rng.randrange(1, 6) + rows = [[rand_field(rng) for _ in range(ncol)] for _ in range(rng.randrange(1, 12))] + buf = io.StringIO(newline="") + lt = "\r\n" if delim == "," else rng.choice(["\r\n", "\n"]) + w = csv.writer(buf, delimiter=delim, lineterminator=lt) + w.writerows(rows) + data = buf.getvalue() + back = [r for r in csv.reader(io.StringIO(data, newline=""), delimiter=delim) if r] + cases.append({"data": data.encode(), "delimiter": delim, "newline": lt, "rows": back}) + for i in range(30): + cols = ["id", "name", "note é", "x,y"][: rng.randrange(1, 5)] + rows = [{c: rand_field(rng) for c in cols} for _ in range(rng.randrange(1, 8))] + buf = io.StringIO(newline="") + w = csv.DictWriter(buf, fieldnames=cols) + w.writeheader() + w.writerows(rows) + data = buf.getvalue() + back = [r for r in csv.reader(io.StringIO(data, newline="")) if r] + cases.append({"data": data.encode(), "delimiter": ",", "newline": "\r\n", "rows": back, "keyed": True}) + ctx.emit("csv", cases) diff --git a/tools/fixtures/ini.py b/tools/fixtures/ini.py new file mode 100644 index 0000000..412d4f7 --- /dev/null +++ b/tools/fixtures/ini.py @@ -0,0 +1,62 @@ +# data/ini fixtures: random configs written by Python's configparser (interpolation off, key case kept), and +# hand-written messy files (comments, ':' delimiters, continuation lines, odd spacing, duplicates) with what +# configparser(strict=False) reads from them. +# tests/gen/ini.luau { written = { { data, canon } }, read = { { data, canon } } } +import configparser, importlib.util, io, os + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + + +def parser(): + p = configparser.ConfigParser(interpolation=None, strict=False) + p.optionxform = str + return p + + +def as_dict(p): + return {s: dict(p.items(s, raw=True)) for s in p.sections()} + + +MESSY = [ + "[a]\nx=1\ny : two words \n; comment\n # indented comment\nz =\n", + "[s]\nkey = line one\n line two\n\tline three\nk2: v\n", + "# top comment\n[one]\na = 1\n[two]\nb = 2\n[one]\nc = 3\n", + "[dup]\na = 1\na = 2\n", + "[weird name with spaces]\n key with spaces = value with = sign \n", + "[s]\nurl = http://x:8080/p?a=b\npath: C:\\dir\n", + "[x]\r\nwin = yes\r\nmore = no\r\n", + "[\u00e9]\n\u4e2d = \u00fc\n", + "[a]\nk = v ; not a comment by default\n", + "[e]\nempty =\nalso:\n", +] + + +def generate(ctx): + rng = ctx.rng(17) + written = [] + alph = "ab xyz09_-.\u00e9/=:;#" + for i in range(80): + p = parser() + for s in range(rng.randrange(1, 5)): + name = "sec%d %s" % (s, rng.choice(["", "x", "\u00e9"])) + p.add_section(name) + for k in range(rng.randrange(0, 6)): + key = "k%d%s" % (k, rng.choice(["", "_a", ".b"])) + val = "".join(rng.choice(alph) for _ in range(rng.randrange(0, 12))).strip() + if rng.random() < 0.15: + val = val + "\nsecond line" + rng.choice(["", "\nthird"]) + p.set(name, key, val) + buf = io.StringIO() + p.write(buf) + data = buf.getvalue() + back = parser() + back.read_string(data) + written.append({"data": data.encode(), "canon": C.canon(as_dict(back))}) + read = [] + for m in MESSY: + p = parser() + p.read_string(m) + read.append({"data": m.encode(), "canon": C.canon(as_dict(p))}) + ctx.emit("ini", {"written": written, "read": read}) diff --git a/tools/fixtures/json.py b/tools/fixtures/json.py new file mode 100644 index 0000000..52776b6 --- /dev/null +++ b/tools/fixtures/json.py @@ -0,0 +1,91 @@ +# codecs/Json + data/json fixtures: the JSONTestSuite parsing corpus (nst/JSONTestSuite, pinned tarball through nix) +# with Python's json verdicts and canonical values, plus a random corpus written by Python's json.dumps in several +# styles (compact sorted, insertion order, indent 2, ensure_ascii) that the tests must parse and reproduce exactly. +# tests/gen/json_suite.luau { { name, expect = "y" | "n" | "i", data, canon? } } +# tests/gen/json_corpus.luau { { canon, compact, ordered, pretty, ascii } } +# tests/gen/json_bench.luau { text, compact } (~1 MB, indent 1; compact = sorted keys) +import importlib.util, json, os + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + +SUITE_URL = "https://github.com/nst/JSONTestSuite/archive/1ef36fa01286573e846ac449e8683f8833c5b26a.tar.gz" +SUITE_SHA = "0zp4gbpfxac9hfzlgjmqg70w8dhql6rbrkh8dhi3rn5aan0qqv5k" + + +def rand_value(rng, depth=0): + v = _rand_value(rng, depth) + if isinstance(v, float) and v.is_integer(): + return int(v) # Python writes 1.0, we write 1: keep integral numbers ints + return v + + +def _rand_value(rng, depth=0): + r = rng.random() + if depth > 4 or r < 0.45: + k = rng.randrange(9) + if k == 0: + return None + if k == 1: + return rng.random() < 0.5 + if k == 2: + return rng.randrange(-10 ** 15, 10 ** 15) + if k == 3: + return rng.randrange(-1000, 1000) + if k == 4: + return round(rng.uniform(-1e6, 1e6), rng.randrange(1, 8)) + if k == 5: + return rng.uniform(-1, 1) * 10 ** rng.randrange(-4, 14) + return rand_str(rng) + if r < 0.72: + return [rand_value(rng, depth + 1) for _ in range(rng.randrange(0, 7))] + d = {} + for _ in range(rng.randrange(0, 7)): + d[rand_str(rng)] = rand_value(rng, depth + 1) + return d + + +ALPH = "abcxyz ABC_019\"\\/\n\t\r\b\f\x01\x1f\x7féü中文\U0001f600
" + + +def rand_str(rng): + return "".join(rng.choice(ALPH) for _ in range(rng.randrange(0, 12))) + + +def generate(ctx): + root = C.fetch(SUITE_URL, SUITE_SHA) + d = os.path.join(root, "test_parsing") + cases = [] + for name in sorted(os.listdir(d)): + if not name.endswith(".json"): + continue + data = open(os.path.join(d, name), "rb").read() + c = {"name": name, "expect": name[0], "data": data} + try: + v = json.loads(data.decode("utf-8", "surrogatepass")) + c["canon"] = C.canon(v) + except Exception: + pass + cases.append(c) + ctx.emit("json_suite", cases) + + rng = ctx.rng(7) + corpus = [] + for _ in range(300): + v = rand_value(rng) + corpus.append({ + "canon": C.canon(v), + "compact": json.dumps(v, separators=(",", ":"), sort_keys=True, ensure_ascii=False), + "ordered": json.dumps(v, separators=(",", ":"), ensure_ascii=False), + "pretty": json.dumps(v, indent=2, sort_keys=True, ensure_ascii=False), + "ascii": json.dumps(v, separators=(",", ":"), sort_keys=True), + }) + ctx.emit("json_corpus", corpus) + + big = [rand_value(rng) for _ in range(3000)] + text = json.dumps(big, ensure_ascii=False, indent=1) + while len(text) < 1_000_000: + big = big + big + text = json.dumps(big, ensure_ascii=False, indent=1) + ctx.emit("json_bench", {"text": text, "compact": json.dumps(big, separators=(",", ":"), sort_keys=True, ensure_ascii=False)}) diff --git a/tools/fixtures/msgpack.py b/tools/fixtures/msgpack.py new file mode 100644 index 0000000..d395813 --- /dev/null +++ b/tools/fixtures/msgpack.py @@ -0,0 +1,94 @@ +# data/msgpack fixtures: random values packed by Python's msgpack (through nix): every integer width, floats, +# str / bin of every length class, nested arrays / maps (int and str keys), nil / bools, timestamps (all three +# widths) and other ext types; with the canonical form of msgpack's own unpacking. +# tests/gen/msgpack.luau { safe = { { data, canon } }, wide = { { data, canon, canonStr } } } +# safe: no integers past 2^53, no integral floats: our decode + encode must give the same bytes +# wide: 64-bit integers too (canon = as doubles, canonStr = exact text via bigInts = "string") +import importlib.util, os, pickle + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + +BODY = r''' +import msgpack, pickle, random, sys, datetime +rng = random.Random(5) +def rint(wide): + k = rng.randrange(8) + lim = [2**5, 2**7, 2**8, 2**15, 2**16, 2**31, 2**32, 2**53 - 1][k] + if wide and rng.random() < 0.4: + lim = rng.choice([2**63 - 1, 2**64 - 1]) + v = rng.randrange(0, lim + 1) + if lim == 2**63 - 1 and rng.random() < 0.5: + v = -v - 1 + return v + v = rng.randrange(-lim, lim + 1) + return v +def rstr(): + n = rng.choice([0, 1, 5, 31, 32, 200, 255, 256, 300]) + alph = "abé中\U0001f600 \n\x00" + return "".join(rng.choice(alph) for _ in range(n))[:n] +def rval(d, wide): + r = rng.random() + if d > 3 or r < 0.5: + k = rng.randrange(9) + if k == 0: return None + if k == 1: return rng.random() < 0.5 + if k in (2, 3): return rint(wide) + if k == 4: + f = rng.uniform(-1e6, 1e6) * 10 ** rng.randrange(-5, 5) + return f if not f.is_integer() else f + 0.5 + if k == 5: return rstr() + if k == 6: return rng.randbytes(rng.choice([0, 3, 255, 256])) + if k == 7: + sec = rng.choice([rng.randrange(0, 2**32), rng.randrange(0, 2**34), rng.randrange(-2**35, 2**37)]) + us = rng.choice([0, rng.randrange(1000000)]) + return msgpack.Timestamp(sec, us * 1000) + return msgpack.ExtType(rng.randrange(0, 128), rng.randbytes(rng.choice([1, 2, 4, 8, 16, 3, 300]))) + if r < 0.75: + return [rval(d + 1, wide) for _ in range(rng.choice([0, 1, 3, 15, 16, 20] if d < 2 else [0, 1, 3]))] + m = {} + for _ in range(rng.choice([0, 1, 3, 15, 16, 17] if d < 2 else [0, 1, 3])): + key = rint(False) if rng.random() < 0.3 else "".join(rng.choice("abc\u00e9") for _ in range(rng.randrange(6))) + m[key] = rval(d + 1, wide) + return m +def conv(v): + if isinstance(v, msgpack.Timestamp): + return v.to_datetime() + if isinstance(v, msgpack.ExtType): + return ["ext", v.code, v.data] + if isinstance(v, list): + return [conv(x) for x in v] + if isinstance(v, dict): + return {k: conv(x) for k, x in v.items()} + return v +def cstr(v): + if isinstance(v, int) and not isinstance(v, bool) and abs(v) >= 2**53: + return str(v) + if isinstance(v, list): + return [cstr(x) for x in v] + if isinstance(v, dict): + return {k: cstr(x) for k, x in v.items()} + return v +out = {"safe": [], "wide": []} +# the 32-bit length forms, once each +for v in ["x" * 70000, b"y" * 70000, list(range(70000)), {i: i for i in range(70000)}]: + data = msgpack.packb(v, use_bin_type=True) + out["safe"].append({"data": data, "canon": canon(msgpack.unpackb(data, strict_map_key=False))}) +for i in range(250): + v = rval(0, False) + data = msgpack.packb(v, use_bin_type=True) + back = msgpack.unpackb(data, raw=False, strict_map_key=False) + out["safe"].append({"data": data, "canon": canon(conv(back))}) +for i in range(150): + v = rval(0, True) + data = msgpack.packb(v, use_bin_type=True) + back = conv(msgpack.unpackb(data, raw=False, strict_map_key=False)) + out["wide"].append({"data": data, "canon": canon(back), "canonStr": canon(cstr(back))}) +sys.stdout.buffer.write(pickle.dumps(out, protocol=4)) +''' + + +def generate(ctx): + out = pickle.loads(C.python(ctx, ["msgpack"], BODY)) + ctx.emit("msgpack", out) diff --git a/tools/fixtures/plist.py b/tools/fixtures/plist.py new file mode 100644 index 0000000..f89f1dc --- /dev/null +++ b/tools/fixtures/plist.py @@ -0,0 +1,83 @@ +# data/plist fixtures: random values written by Python's plistlib as XML (insertion order) and as binary, with the +# canonical form of plistlib's own reading (aware UTC datetimes; UIDs as ["uid", n]). +# tests/gen/plist.luau { { xml, binary, canon } } (our XML writer must reproduce xml byte for byte) +# + wide = { { binary, canon } } (UIDs, 64-bit integers: binary only) +import datetime, importlib.util, os, plistlib + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + + +def rval(rng, d, wide): + r = rng.random() + if d > 3 or r < 0.5: + k = rng.randrange(8) + if k == 0: + return rng.random() < 0.5 + if k == 1: + return rng.randrange(-2 ** 31, 2 ** 31) + if k == 2: + return rng.choice([rng.randrange(-2 ** 63, 2 ** 63), rng.randrange(0, 2 ** 64)]) if wide else rng.randrange(-2 ** 53, 2 ** 53) + if k == 3: + f = rng.uniform(-1e6, 1e6) * 10 ** rng.randrange(-5, 5) + return f if not f.is_integer() else f + 0.5 + if k == 4: + return "".join(rng.choice("ab <>&\"'é中\U0001f600\n\t") for _ in range(rng.randrange(0, 12))) + if k == 5: + return rng.randbytes(rng.choice([0, 1, 2, 3, 40, 57, 58, 200])) + if k == 6: + return datetime.datetime.fromtimestamp(rng.randrange(-2 ** 31, 2 ** 33), datetime.timezone.utc) + return plistlib.UID(rng.randrange(0, 2 ** 32)) if wide else "x" + if r < 0.75: + return [rval(rng, d + 1, wide) for _ in range(rng.randrange(0, 6))] + return {"".join(rng.choice("abcé <&") for _ in range(rng.randrange(0, 6))): rval(rng, d + 1, wide) for _ in range(rng.randrange(0, 6))} + + +def conv(v): + if isinstance(v, plistlib.UID): + return ["uid", v.data] + if isinstance(v, list): + return [conv(x) for x in v] + if isinstance(v, dict): + return {k: conv(x) for k, x in v.items()} + return v + + +def generate(ctx): + rng = ctx.rng(21) + cases = [] + for i in range(200): + v = rval(rng, 0, False) + if not isinstance(v, (list, dict)) and rng.random() < 0.5: + v = {"root": v} + xml = plistlib.dumps(v, fmt=plistlib.FMT_XML, sort_keys=False, aware_datetime=True) + binary = plistlib.dumps(v, fmt=plistlib.FMT_BINARY, sort_keys=False, aware_datetime=True) + back = plistlib.loads(xml, aware_datetime=True) + assert C.canon(conv(plistlib.loads(binary, aware_datetime=True))) == C.canon(conv(back)) + cases.append({"xml": xml, "binary": binary, "canon": C.canon(conv(back))}) + wide = [] + for i in range(80): + v = [rval(rng, 1, True) for _ in range(4)] + binary = plistlib.dumps(v, fmt=plistlib.FMT_BINARY, aware_datetime=True) + wide.append({"binary": binary, "canon": C.canon(conv(plistlib.loads(binary, aware_datetime=True)))}) + # a hand-written XML plist with whitespace, comments, hex integers, odd reals, a bare value root + extra = b""" + + + + + hex 0x1F + neg -5 + real 2.5e3 + data + AAEC + AwQ= + + empty + date 2001-01-01T00:00:00Z + + +""" + ctx.emit("plist", {"cases": cases, "wide": wide, "extra": extra, + "extraCanon": C.canon(plistlib.loads(extra, aware_datetime=True))}) diff --git a/tools/fixtures/toml.py b/tools/fixtures/toml.py new file mode 100644 index 0000000..7ba5cc5 --- /dev/null +++ b/tools/fixtures/toml.py @@ -0,0 +1,120 @@ +# data/toml fixtures: the toml-test suite (toml-lang/toml-test v2.2.0, pinned tarball through nix; the files listed +# in tests/files-toml-1.0.0) with each valid case's expected value as the canonical text tests/data/Canon.luau +# computes, plus a random corpus written by tomli-w and read back by Python's tomllib. +# tests/gen/toml_suite.luau { { name, valid, data, canon? } } +# tests/gen/toml_corpus.luau { { data, canon } } +import datetime, importlib.util, json, os, re, tomllib + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + +SUITE_URL = "https://github.com/toml-lang/toml-test/archive/refs/tags/v2.2.0.tar.gz" +SUITE_SHA = "1nkgbfcdjaccqgf5pkjs49jh0z1pz4lval94qfxq4j6ikvmlg80s" +DATES = ("datetime", "datetime-local", "date-local", "time-local") + + +def norm_date(v): + """a toml-test datetime string the way Types.Date prints it""" + m = re.match(r"^(\d{4}-\d{2}-\d{2})?(?:[Tt ]?(\d{2}:\d{2}:\d{2})(?:\.(\d+))?)?([Zz]|[+-]\d{2}:\d{2})?$", v) + date, time, frac, off = m.groups() + out = date or "" + if time: + out += ("T" if date else "") + time + f = (frac or "")[:9].rstrip("0") + if f: + out += "." + f + if off: + out += "Z" if off in ("Z", "z", "+00:00", "-00:00") else off + return out + + +def tagged(v, out): + if isinstance(v, dict) and set(v) == {"type", "value"} and isinstance(v["type"], str) and isinstance(v["value"], str): + t, x = v["type"], v["value"] + if t == "string": + b = x.encode("utf-8", "surrogatepass") + out += b"s%d:" % len(b) + b + elif t == "integer": + out += C.num(int(x)) + elif t == "float": + out += C.num(float(x)) + elif t == "bool": + out += b"t" if x == "true" else b"f" + elif t in DATES: + out += b"d" + norm_date(x).encode() + else: + raise ValueError(t) + elif isinstance(v, list): + out += b"[" + for x in v: + tagged(x, out) + out += b"," + out += b"]" + else: + items = [] + for k, x in v.items(): + kb = k.encode("utf-8", "surrogatepass") + items.append((b"s%d:" % len(kb) + kb, x)) + items.sort(key=lambda p: p[0]) + out += b"{" + for kb, x in items: + out += kb + b"=" + tagged(x, out) + out += b"," + out += b"}" + + +GEN = r''' +import datetime, json, random, sys, tomli_w +rng = random.Random(5) +KEYS = ["a", "b-c", "d_e", "1", "with space", "dot.ted", "é", "quote\"", "", "tab\t"] +def scalar(): + k = rng.randrange(8) + if k == 0: return rng.randrange(-2**63, 2**63) + if k == 1: return rng.randrange(-1000, 1000) + if k == 2: return rng.choice([0.5, -1.25e-7, 3.14159, 1e300, float("inf"), -float("inf"), 6.02e23]) + if k == 3: return rng.random() < 0.5 + if k == 4: return "".join(rng.choice("ab \"\\\n\té中\U0001f600\x01\x7f'#=[]") for _ in range(rng.randrange(12))) + if k == 5: + tz = rng.choice([None, datetime.timezone.utc, datetime.timezone(datetime.timedelta(hours=-7, minutes=-30))]) + return datetime.datetime(rng.randrange(1, 9999), rng.randrange(1, 13), rng.randrange(1, 29), rng.randrange(24), rng.randrange(60), rng.randrange(60), rng.choice([0, 999999, 500000]), tzinfo=tz) + if k == 6: return datetime.date(rng.randrange(1, 9999), rng.randrange(1, 13), rng.randrange(1, 29)) + return datetime.time(rng.randrange(24), rng.randrange(60), rng.randrange(60), rng.choice([0, 123000])) +def table(depth): + d = {} + for _ in range(rng.randrange(1, 6)): + r = rng.random() + k = rng.choice(KEYS) + if depth < 3 and r < 0.2: d[k] = table(depth + 1) + elif depth < 3 and r < 0.3: d[k] = [table(depth + 1) for _ in range(rng.randrange(1, 3))] + elif r < 0.45: d[k] = [scalar() for _ in range(rng.randrange(0, 4))] + elif r < 0.5: d[k] = [[scalar()], [scalar(), scalar()], {"x": scalar()}] + else: d[k] = scalar() + return d +out = [] +for _ in range(200): + out.append(tomli_w.dumps(table(0), multiline_strings=rng.random() < 0.3)) +json.dump(out, sys.stdout) +''' + + +def generate(ctx): + root = os.path.join(C.fetch(SUITE_URL, SUITE_SHA), "tests") + names = [l.strip() for l in open(os.path.join(root, "files-toml-1.0.0")) if l.strip().endswith(".toml")] + cases = [] + for name in names: + data = open(os.path.join(root, name), "rb").read() + c = {"name": name, "valid": name.startswith("valid/"), "data": data} + if c["valid"]: + out = bytearray() + tagged(json.load(open(os.path.join(root, name[:-5] + ".json"), encoding="utf-8")), out) + c["canon"] = bytes(out) + cases.append(c) + ctx.emit("toml_suite", cases) + + texts = json.loads(ctx.python(["tomli-w"], GEN)) + corpus = [] + for t in texts: + corpus.append({"data": t.encode("utf-8"), "canon": C.canon(tomllib.loads(t))}) + ctx.emit("toml_corpus", corpus) diff --git a/tools/fixtures/xml.py b/tools/fixtures/xml.py new file mode 100644 index 0000000..14cf720 --- /dev/null +++ b/tools/fixtures/xml.py @@ -0,0 +1,174 @@ +# codecs/Xml + data/xml fixtures: random documents (namespaces, attributes with every escape, CDATA, comments, PIs, +# entities from an internal DOCTYPE, mixed content) written by hand, then parsed by Python's xml.etree (expat) for the +# reference tree; the same documents re-encoded as UTF-16 and Latin-1; and well-formedness cases (hand-written plus +# random mutations) with expat's verdict. +# tests/gen/xml_docs.luau { { data, canon } } canon: see canon() below (the test computes the same) +# tests/gen/xml_wf.luau { { data, ok } } ok: expat accepts it +# tests/gen/xml_bench.luau { text } (~1 MB) +import xml.etree.ElementTree as ET +from xml.parsers import expat + +NS = [("", None), ("a", "urn:a"), ("b", "http://example.com/b")] +TAGS = ["item", "x", "Data", "set-1", "q.r", "_u", "élément", "名"] +TXT = "ab <>&\"' é中\U0001f600\t\n ]]" + + +def s(x): + x = x or "" + b = x.encode("utf-8", "surrogatepass") + return b"%d:" % len(b) + b + + +def canon(e): + out = b"(" + s(e.tag) + for k in sorted(e.attrib): + out += b"|" + s(k) + b"=" + s(e.attrib[k]) + out += b"|t" + s(e.text) + for c in e: + out += canon(c) + return out + b")t" + s(e.tail) + + +def esc_text(t): + return t.replace("&", "&").replace("<", "<").replace(">", ">") + + +def esc_attr(t, q): + t = t.replace("&", "&").replace("<", "<") + return t.replace(q, """ if q == '"' else "'") + + +def rand_text(rng): + return "".join(rng.choice(TXT) for _ in range(rng.randrange(0, 10))) + + +def gen_elem(rng, depth, declared): + prefix = rng.choice([p for p in declared]) + local = rng.choice(TAGS) + name = (prefix + ":" + local) if prefix else local + attrs = [] + newdecl = set(declared) + if depth > 0 and rng.random() < 0.15: + p, uri = rng.choice(NS[1:]) + attrs.append(("xmlns:" + p, uri)) + newdecl.add(p) + if rng.random() < 0.1: + attrs.append(("xmlns", "urn:default%d" % rng.randrange(3))) + used = set(a for a, _ in attrs) + for _ in range(rng.randrange(0, 4)): + an = rng.choice(["id", "k", "v-1", "é", "x.y"]) + if rng.random() < 0.2 and len(newdecl) > 1: + an = rng.choice([p for p in newdecl if p]) + ":" + an + if an in used: + continue + used.add(an) + attrs.append((an, rand_text(rng))) + parts = ["<" + name] + for k, v in attrs: + q = rng.choice("\"'") + parts.append(" %s=%s%s%s" % (k, q, esc_attr(v, q), q)) + if depth > 4 or rng.random() < 0.15: + parts.append(rng.choice(["/>", " />"])) + return "".join(parts) + parts.append(">") + for _ in range(rng.randrange(0, 5)): + r = rng.random() + if r < 0.35: + parts.append(esc_text(rand_text(rng))) + elif r < 0.45: + parts.append("]]>") + elif r < 0.5: + parts.append("") + elif r < 0.53: + parts.append("") + elif r < 0.58: + parts.append(rng.choice(["&ent;", "é", "😀", "&", "<", " "])) + else: + parts.append(gen_elem(rng, depth + 1, newdecl)) + parts.append("" % name) + return "".join(parts) + + +def gen_doc(rng): + head = "" + if rng.random() < 0.5: + head += '\n' + head += '\n \n]>\n' + if rng.random() < 0.3: + head += "\n" + declared = {""} + body = gen_elem(rng, 0, declared) + # the root must declare every prefix it may use: declare all at the root + root_decl = " ".join('xmlns:%s="%s"' % (p, u) for p, u in NS[1:]) + i = body.index(">") if not body.startswith("<") else 0 + name_end = 1 + while body[name_end] not in " />": + name_end += 1 + body = body[:name_end] + " " + root_decl + body[name_end:] + return head + body + ("\n" if rng.random() < 0.5 else "") + + +def expat_ok(data): + p = expat.ParserCreate() + try: + p.Parse(data, True) + return True + except Exception: # ExpatError, or LookupError for an unknown encoding name + return False + + +WF = [ + "", "", "", "x", "", "", "", "text", "text", "", + "", "", "&undefined;", "�", "�", "�", "& ", + "", "", "]]>", "<1a/>", "", "", + "", " ", "", "", + "", "", "\x01", "", "", "", + "", "", "]>&e;", "", + "", "", "", "", "< a/>", "", "", + "é\U0001f600", "&<>"'", "", + "", "", "", " ", "xtrailing", "x ", +] + + +def generate(ctx): + rng = ctx.rng(11) + docs = [] + for k in range(250): + text = gen_doc(rng) + root = ET.fromstring(text.encode("utf-8")) + docs.append({"data": text.encode("utf-8"), "canon": canon(root)}) + # other encodings: UTF-16 (BOM, both byte orders) and Latin-1 + for k in range(10): + text = gen_doc(rng) + body = text.split("?>", 1)[1] if text.startswith("' + body).encode("utf-16"), "canon": c}) + docs.append({"data": b"\xfe\xff" + ('' + body).encode("utf-16-be"), "canon": c}) + for k in range(10): + text = "café ½ 中" + data = text.encode("latin-1") + docs.append({"data": data, "canon": canon(ET.fromstring(data))}) + ctx.emit("xml_docs", docs) + + wf = [{"data": d.encode("utf-8"), "ok": expat_ok(d.encode("utf-8"))} for d in WF] + # mutations of valid documents: delete / duplicate / replace one markup character + for k in range(400): + text = gen_doc(rng).encode("utf-8") + b = bytearray(text) + for _ in range(rng.randrange(1, 3)): + pos = rng.randrange(len(b)) + op = rng.randrange(3) + ch = rng.choice(b"<>/&;='\"![]-? ") + if op == 0: + del b[pos] + elif op == 1: + b.insert(pos, ch) + else: + b[pos] = ch + wf.append({"data": bytes(b), "ok": expat_ok(bytes(b))}) + ctx.emit("xml_wf", wf) + + parts = [] + while sum(map(len, parts)) < 1_000_000: + parts.append(gen_elem(rng, 1, {""})) + ctx.emit("xml_bench", {"text": "" + "\n".join(p for p in parts if "&ent;" not in p) + ""}) diff --git a/tools/fixtures/yaml.py b/tools/fixtures/yaml.py new file mode 100644 index 0000000..c45522c --- /dev/null +++ b/tools/fixtures/yaml.py @@ -0,0 +1,111 @@ +# data/yaml fixtures: the yaml-test-suite (data release 2022-01-17, pinned tarball through nix: every case's +# in.yaml, its in.json when there is one, and whether it is an error case), and a random corpus dumped by PyYAML +# (through nix) in several styles: block, flow, indent 4, explicit documents, allow_unicode, multi-document. The +# corpus avoids the strings where YAML 1.1 (PyYAML) and 1.2 resolve plain scalars differently. +# tests/gen/yaml_suite.luau { { name, yaml, json?, error } } +# tests/gen/yaml_corpus.luau { { canon, texts = { [style] = yaml } } } +# tests/gen/yaml_bench.luau { text } (~500 KB, block style) +import importlib.util, json, os, random + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + +SUITE_URL = "https://github.com/yaml/yaml-test-suite/archive/refs/tags/data-2022-01-17.tar.gz" +SUITE_SHA = "00xcny67bp56xkvz4iq6d2prvj9p48z7r705xrw49invvgyp4wnd" + +WORDS = ["a", "key", "value", "x y", "café", "中文", "\U0001f600", "multi\nline", "trail\n", "two\n\n", + " lead", "tail ", "a: b", "# c", "- x", "[x]", "{y}", "'q'", "\"dq\"", "true", "null", "~", "12", "1.5", + "0x1F", "yes", "no", "on", "-", "?", ":", "a#b", "tab\there", "back\\slash", "", "éé é", + "line1\n indented\nline3", "ends with colon:", "---", "...", "%x", "@x", "`x", "*x", "&x", "!x", "|", ">"] + + +def rand_value(rng, depth=0): + r = rng.random() + if depth > 3 or r < 0.5: + k = rng.randrange(8) + if k == 0: + return None + if k == 1: + return rng.random() < 0.5 + if k == 2: + return rng.randrange(-10 ** 12, 10 ** 12) + if k == 3: + v = round(rng.uniform(-1e5, 1e5), rng.randrange(1, 6)) + return int(v) if v.is_integer() else v + return rng.choice(WORDS) + (rng.choice(WORDS) if rng.random() < 0.3 else "") + if r < 0.75: + return [rand_value(rng, depth + 1) for _ in range(rng.randrange(0, 5))] + d = {} + for _ in range(rng.randrange(0, 5)): + k = rng.choice(WORDS[:30]) + if rng.random() < 0.15: + k = rng.randrange(100) + d[k] = rand_value(rng, depth + 1) + return d + + +DUMP = r''' +import json, sys, yaml +values = json.loads(sys.stdin.read()) +def fix(v): # JSON object keys are strings: restore the int keys marked "#int:" + if isinstance(v, dict): + return {(int(k[5:]) if k.startswith("#int:") else k): fix(x) for k, x in v.items()} + if isinstance(v, list): + return [fix(x) for x in v] + return v +out = [] +for v in values: + v = fix(v) + t = { + "block": yaml.safe_dump(v, default_flow_style=False, sort_keys=False, allow_unicode=True), + "flow": yaml.safe_dump(v, default_flow_style=True, sort_keys=False), + "indent4": yaml.safe_dump(v, default_flow_style=False, indent=4, explicit_start=True, explicit_end=True), + "auto": yaml.safe_dump(v, sort_keys=True, width=20), + "multi": yaml.safe_dump_all([v, {"second": v}], default_flow_style=False, allow_unicode=True), + } + back = yaml.safe_load(t["block"]) + out.append({"texts": t, "same": back == v}) +print(json.dumps(out)) +''' + + +def keyed(v): + if isinstance(v, dict): + return {("#int:%d" % k if isinstance(k, int) else k): keyed(x) for k, x in v.items()} + if isinstance(v, list): + return [keyed(x) for x in v] + return v + + +def generate(ctx): + root = C.fetch(SUITE_URL, SUITE_SHA) + cases = [] + for name in sorted(os.listdir(root)): + d = os.path.join(root, name) + if not os.path.isdir(d) or name.startswith("."): + continue + dirs = [d] if os.path.exists(os.path.join(d, "in.yaml")) else [os.path.join(d, x) for x in sorted(os.listdir(d))] + for dd in dirs: + if not os.path.exists(os.path.join(dd, "in.yaml")): + continue + c = {"name": os.path.relpath(dd, root), "yaml": open(os.path.join(dd, "in.yaml"), "rb").read(), + "error": os.path.exists(os.path.join(dd, "error"))} + if os.path.exists(os.path.join(dd, "in.json")): + c["json"] = open(os.path.join(dd, "in.json"), "rb").read() + cases.append(c) + ctx.emit("yaml_suite", cases) + + rng = ctx.rng(5) + values = [rand_value(rng) for _ in range(250)] + dumped = json.loads(ctx.python(["pyyaml"], DUMP, input=json.dumps([keyed(v) for v in values]).encode())) + corpus = [] + for v, d in zip(values, dumped): + if d["same"]: + corpus.append({"canon": C.canon(v), "multi": C.canon([v, {"second": v}]), "texts": d["texts"]}) + ctx.emit("yaml_corpus", corpus) + + big = [rand_value(rng) for _ in range(1500)] + text = json.loads(ctx.python(["pyyaml"], "import json, sys, yaml\nprint(json.dumps(yaml.safe_dump(json.loads(sys.stdin.read()), default_flow_style=False, allow_unicode=True)))", + input=json.dumps([x for x in big if not isinstance(x, dict) or all(isinstance(k, str) for k in x)]).encode())) + ctx.emit("yaml_bench", {"text": text})