--!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