Merge branch 'ws/data-yaml' into ws/data

This commit is contained in:
4DBug committed 2026-10-31 08:56:36 -05:00
commit 8389c97143
9 files changed
+2111 -1

No files matched your search

+1
View File
@@ -14,6 +14,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| 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):
+12
View File
@@ -122,6 +122,18 @@ local list: { Entry } = {
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
+339
View File
@@ -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
File diff suppressed because it is too large. Load diff
+77
View File
@@ -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
+198
View File
@@ -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()
+12
View File
@@ -86,3 +86,15 @@ do
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
+1 -1
View File
@@ -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 json xml > /dev/null || exit 1
python3 -I tools/fixtures.py deflate png json xml yaml > /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
+111
View File
@@ -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})