Merge branch 'ws/data-yaml' into ws/data
This commit is contained in:
commit
8389c97143
9 files changed
+2111
-1
No files matched your search
@@ -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
|
||||
@@ -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
@@ -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
|
||||
Reference in new issue
Block a user