From 86af9128420d33a66926ae6287f37c241270e6e3 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:54:13 -0500 Subject: [PATCH] data: data/yaml (YAML 1.2 core schema read / write: block + flow, compact collections, plain / quoted / literal / folded scalars, anchors + aliases as shared refs with an expansion limit, tags incl. !!binary / !!timestamp, %TAG, multi-document, explicit keys; writer with anchors for shared tables); yaml-test-suite + PyYAML fixtures; bench lines tools/bench.sh: also generates the yaml fixtures. Co-Authored-By: Claude Opus 5.5 --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/data/yaml/Emit.luau | 339 ++++++++ src/Formats/data/yaml/Parse.luau | 1360 ++++++++++++++++++++++++++++++ src/Formats/data/yaml/init.luau | 77 ++ tests/data/yaml.luau | 198 +++++ tools/bench.luau | 12 + tools/bench.sh | 2 +- tools/fixtures/yaml.py | 111 +++ 9 files changed, 2111 insertions(+), 1 deletion(-) create mode 100644 src/Formats/data/yaml/Emit.luau create mode 100644 src/Formats/data/yaml/Parse.luau create mode 100644 src/Formats/data/yaml/init.luau create mode 100644 tests/data/yaml.luau create mode 100644 tools/fixtures/yaml.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index d9372b9..be7d1d7 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -8,6 +8,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | | data | json | .json .jsonl .ndjson .geojson | yes | yes | ordered: true, streaming: true | `tests/data/json.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): diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index dafa3ee..240174b 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -50,6 +50,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 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/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 eb68b0a..c17cc8d 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -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 diff --git a/tools/bench.sh b/tools/bench.sh index 31f663a..5938a0d 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 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 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})