diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 562029f..666e2a8 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -9,6 +9,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | data | cbor | .cbor | yes | yes | binary: true, ordered: true, tags: true | `tests/data/cbor.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 | 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` | Codecs (layer 1, shared by formats; not loadable on their own): diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 61b78bc..07ad5eb 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -62,6 +62,18 @@ local list: { Entry } = { return require("@formats/data/msgpack") 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", 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/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/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)