merge ws/source (codecs/text/KeyValues for .vmt materials)

This commit is contained in:
4DBug committed 2026-11-01 18:46:27 -06:00
commit d8212c6839
15 files changed
+7929 -1132

No files matched your search

+3 -2
View File
@@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list
## Formats ## Formats
<!-- formats:begin --> <!-- formats:begin -->
175 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) 176 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
adds each format's capabilities. adds each format's capabilities.
| Category | Format | Extensions | Read | Write | | Category | Format | Extensions | Read | Write |
@@ -191,6 +191,7 @@ adds each format's capabilities.
| Data | plist | .plist | yes | yes | | Data | plist | .plist | yes | yes |
| Data | snbt | .snbt | yes | yes | | Data | snbt | .snbt | yes | yes |
| Data | toml | .toml | yes | yes | | Data | toml | .toml | yes | yes |
| Data | vdf | .vdf .acf .res .kv | yes | yes |
| Data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | | Data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes |
| Data | yaml | .yaml .yml | yes | yes | | Data | yaml | .yaml .yml | yes | yes |
| Vector graphics and tile maps | svg | .svg | yes | yes | | Vector graphics and tile maps | svg | .svg | yes | yes |
@@ -240,7 +241,7 @@ Shared by the formats, not loadable on their own (`src/Rosetta/codecs/<domain>/`
| font | Bitmap, Cff, GlyphNames, TrueType | | font | Bitmap, Cff, GlyphNames, TrueType |
| image | Bcn, Blend, Dct, Etc, Half, Jpeg, Pixels, Quantize, Raster, Texel, Texture, Vp8, Vp8L, Yuv | | image | Bcn, Blend, Dct, Etc, Half, Jpeg, Pixels, Quantize, Raster, Texel, Texture, Vp8, Vp8L, Yuv |
| model | Draco, Mat4, MeshFlatten, Minecraft, Polygon, Rbx, Rig, Sampler, SourceAnim, Vrml | | model | Draco, Mat4, MeshFlatten, Minecraft, Polygon, Rbx, Rig, Sampler, SourceAnim, Vrml |
| text | Json, Nbt, Text, Url, Xml | | text | Json, KeyValues, Nbt, Text, Url, Xml |
| video | Dsp, H263, H264, Legacy, Mpeg1, Mpeg2, Theora, Video | | video | Dsp, H263, H264, Legacy, Mpeg1, Mpeg2, Theora, Video |
| containers | Archive, AudioWrap, Avi, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip | | containers | Archive, AudioWrap, Avi, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip |
<!-- codecs:end --> <!-- codecs:end -->
+2737 -29
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+2737 -29
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+2
View File
@@ -147,6 +147,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| data | plist | .plist | yes | yes | binary: "read", ordered: true | `tests/data/plist.luau` | | data | plist | .plist | yes | yes | binary: "read", ordered: true | `tests/data/plist.luau` |
| data | snbt | .snbt | yes | yes | ordered: true, typed: true | `tests/data/snbt.luau` | | data | snbt | .snbt | yes | yes | ordered: true, typed: true | `tests/data/snbt.luau` |
| data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` | | data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` |
| data | vdf | .vdf .acf .res .kv | yes | yes | ordered: true, binary: true | `tests/data/vdf.luau` |
| data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.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` | | data | yaml | .yaml .yml | yes | yes | ordered: true, multiDocument: true, anchors: true | `tests/data/yaml.luau` |
| vector | svg | .svg | yes | yes | rasterize: true, text: false | `tests/vector/svg.luau` | | vector | svg | .svg | yes | yes | rasterize: true, text: false | `tests/vector/svg.luau` |
@@ -258,6 +259,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d. - codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d.
- **text** - **text**
- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
- codecs/text/KeyValues: Valve KeyValues text (tier1/KeyValues.cpp of the Source SDK 2013, srctools' reading of it)
- codecs/text/Nbt: Minecraft's Named Binary Tag format and SNBT (Minecraft wiki "NBT format", wiki.vg "NBT"). - codecs/text/Nbt: Minecraft's Named Binary Tag format and SNBT (Minecraft wiki "NBT format", wiki.vg "NBT").
- codecs/text/Text: text decoding helpers: BOM stripping, Windows-1252 for text that is not UTF-8, line splitting. - codecs/text/Text: text decoding helpers: BOM stripping, Windows-1252 for text that is not UTF-8, line splitting.
- codecs/text/Url: RFC 3986 reference resolution (section 5.2), local-path classification and percent-encoding. - codecs/text/Url: RFC 3986 reference resolution (section 5.2), local-path classification and percent-encoding.
+2 -1
View File
@@ -33,7 +33,7 @@ src/Rosetta/
audio/ Aac Ac3 Adpcm Alac Ape ApeTag Flac Hively Mdct MidiRender Mpa Musepack Opus Pcm Qoa Resample audio/ Aac Ac3 Adpcm Alac Ape ApeTag Flac Hively Mdct MidiRender Mpa Musepack Opus Pcm Qoa Resample
SoundFont Stream Tracker Tta Vorbis VorbisComment WavPack SoundFont Stream Tracker Tta Vorbis VorbisComment WavPack
video/ Dsp H263 H264 Legacy Mpeg1 Mpeg2 Theora Video (the video codec registry) video/ Dsp H263 H264 Legacy Mpeg1 Mpeg2 Theora Video (the video codec registry)
text/ Json Nbt Text Url Xml text/ Json KeyValues Nbt Text Url Xml
font/ Bitmap Cff GlyphNames TrueType font/ Bitmap Cff GlyphNames TrueType
model/ Draco Mat4 MeshFlatten Minecraft Polygon Rbx Rig Sampler SourceAnim Vrml model/ Draco Mat4 MeshFlatten Minecraft Polygon Rbx Rig Sampler SourceAnim Vrml
host/ host (layer 2) runtime adapters; only the api uses them host/ host (layer 2) runtime adapters; only the api uses them
@@ -244,6 +244,7 @@ them. Anything generic goes down a layer and is called:
| polygons with holes -> triangles | `codecs/model/Polygon` | | polygons with holes -> triangles | `codecs/model/Polygon` |
| studio model animation values (GoldSrc / Source run-length shorts, Quaternion48 / 64, bone records) | `codecs/model/SourceAnim` | | studio model animation values (GoldSrc / Source run-length shorts, Quaternion48 / 64, bone records) | `codecs/model/SourceAnim` |
| NBT / SNBT values; Minecraft block states and colours | `codecs/text/Nbt`, `codecs/model/Minecraft` | | NBT / SNBT values; Minecraft block states and colours | `codecs/text/Nbt`, `codecs/model/Minecraft` |
| Valve KeyValues (text, binary, the BSP entity lump) | `codecs/text/KeyValues` |
| Roblox instance trees and property values | `codecs/model/Rbx` | | Roblox instance trees and property values | `codecs/model/Rbx` |
| bitmap fonts as a Font; PostScript glyph names | `codecs/font/Bitmap`, `codecs/font/GlyphNames` | | bitmap fonts as a Font; PostScript glyph names | `codecs/font/Bitmap`, `codecs/font/GlyphNames` |
| CRC-16 (XMODEM / ARC), xxHash32 | `core/Crc16`, `codecs/compress/Xxh32` | | CRC-16 (XMODEM / ARC), xxHash32 | `core/Crc16`, `codecs/compress/Xxh32` |
+22 -1
View File
@@ -306,6 +306,26 @@ local xml = assert(F.saveString(p, { format = "plist" }))
assert(string.find(xml, "<key>CFBundleName</key>\n\t<string>Demo</string>", 1, true)) assert(string.find(xml, "<key>CFBundleName</key>\n\t<string>Demo</string>", 1, true))
``` ```
## VDF (Valve KeyValues)
`.vdf`, `.acf`, `.res` and other KeyValues files decode to `Types.object`s of strings; a key that repeats gets an array
of its values (`duplicates = "last"` / `"first"` keep one). `[$CONDITION]`s are evaluated for a PC (`defines =
{ OSX = true }` changes the flags, `defines = false` keeps every pair), `#include` / `#base` files come through
`resolve`, `escapes = false` reads backslashes as they are. `pairs = true` gives the ordered pair list of
`codecs/text/KeyValues` (`{ key, value, cond?, type? }`), which keeps everything. Binary KeyValues (`shortcuts.vdf`)
are sniffed; encode with `binary = true`.
```luau
local acf = assert(F.data.load('"AppState"\n{\n\t"appid"\t"440"\n\t"x" "1"\n\t"x" "2"\n}\n', { format = "vdf" }))
assert(acf.AppState.appid == "440" and acf.AppState.x[2] == "2")
local text = assert(F.saveString(acf, { format = "vdf" }))
assert(string.find(text, '\t"x"\t"1"\n\t"x"\t"2"\n', 1, true))
local pairs = assert(F.data.load('"r" { "a" "1" [$X360] }', { format = "vdf", pairs = true, defines = false }))
assert(pairs[1].value[1].cond == "$X360")
local bin = assert(F.save(acf, nil, { format = "vdf", binary = true }))
assert(F.data.load(bin, { format = "vdf" }).AppState.appid == "440")
```
## Save and convert ## Save and convert
Data values have no `kind`, so saving needs `opts.format` or a destination extension (an `XmlNode` document too): Data values have no `kind`, so saving needs `opts.format` or a destination extension (an `XmlNode` document too):
@@ -337,6 +357,7 @@ is an error there), CSV needs rows, INI needs sections of scalars, JSON has no b
| toml (`.toml`) | yes | yes | ordered tables, Dates | | toml (`.toml`) | yes | yes | ordered tables, Dates |
| csv (`.csv`, `.tsv`) | yes | yes | rows (arrays or records) | | csv (`.csv`, `.tsv`) | yes | yes | rows (arrays or records) |
| ini (`.ini`, `.cfg`, `.conf`, `.desktop`) | yes | yes | sections of strings | | ini (`.ini`, `.cfg`, `.conf`, `.desktop`) | yes | yes | sections of strings |
| vdf (`.vdf`, `.acf`, `.res`, `.kv`) | text + binary | text + binary | ordered objects of strings, or pairs |
| msgpack (`.msgpack`, `.mpk`) | yes | yes | values, buffers, Dates | | msgpack (`.msgpack`, `.mpk`) | yes | yes | values, buffers, Dates |
| cbor (`.cbor`) | yes | yes | values, buffers, Dates, tagged values | | cbor (`.cbor`) | yes | yes | values, buffers, Dates, tagged values |
| plist (`.plist`) | XML + binary | XML | values, buffers, Dates | | plist (`.plist`) | XML + binary | XML | values, buffers, Dates |
@@ -351,7 +372,7 @@ Full capability list: [FORMATS.md](../FORMATS.md).
- Luau has one number type: `1.0` reads back as `1`, and TOML / plist write integral floats as integers. Integers - Luau has one number type: `1.0` reads back as `1`, and TOML / plist write integral floats as integers. Integers
past 2^53 need `bigInts = "string"` to survive. past 2^53 need `bigInts = "string"` to survive.
- An empty plain table `{}` is written as an array; use `F.Types.object()` (or `emptyTable = "object"`) for `{}`. - An empty plain table `{}` is written as an array; use `F.Types.object()` (or `emptyTable = "object"`) for `{}`.
- Text formats sniff weakly: give `format` (or a file name) for YAML, TOML, INI, CSV, MessagePack and CBOR without - Text formats sniff weakly: give `format` (or a file name) for YAML, TOML, INI, VDF, CSV, MessagePack and CBOR without
its self-describe tag. its self-describe tag.
- XML whitespace-only text between elements is dropped by default (`whitespace = true` keeps it); text is never - XML whitespace-only text between elements is dropped by default (`whitespace = true` keeps it); text is never
trimmed otherwise. trimmed otherwise.
+12
View File
@@ -1718,6 +1718,18 @@ local list: { Entry } = {
return require("@rosetta/data/toml") return require("@rosetta/data/toml")
end, end,
}, },
{
name = "vdf",
category = "data",
path = "data/vdf",
extensions = { "vdf", "acf", "res", "kv" },
mime = { "text/x-vdf" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/KeyValues" },
caps = { decode = true, encode = true, ordered = true, binary = true },
load = function()
return require("@rosetta/data/vdf")
end,
},
{ {
name = "xml", name = "xml",
category = "data", category = "data",
@@ -0,0 +1,303 @@
--!strict
-- codecs/text/KeyValues/Binary: binary KeyValues (KeyValues::ReadAsBinary; Steam shortcuts.vdf / appinfo values).
-- Types: 0 block, 1 string, 2 int32, 3 float32, 4 pointer, 5 wide string (UTF-16LE), 6 color, 7 uint64, 8 end,
-- 10 int64, 11 end (alternative). 64-bit values are numbers below 2^53, decimal strings above.
local Err = require("@rosetta/core/Err")
local Text = require("@rosetta/codecs/text/Text")
local Binary = {}
export type Pair = {
key: string,
value: any, -- string | number | Block
cond: string?, -- text: the [$CONDITION] kept when not evaluated
type: string?, -- binary: "int32" | "float32" | "pointer" | "wstring" | "color" | "uint64" | "int64" (nil: string / block)
}
export type Block = { Pair }
local readu8, readu32, readi32, readf32 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32
local TYPES: { [number]: string } = { [2] = "int32", [3] = "float32", [4] = "pointer", [5] = "wstring", [6] = "color", [7] = "uint64", [10] = "int64" }
local CODES: { [string]: number } = { int32 = 2, float32 = 3, pointer = 4, wstring = 5, color = 6, uint64 = 7, int64 = 10 }
-- (hi, lo) u32 halves -> number below 2^53, else the decimal digits
local function u64text(hi: number, lo: number): number | string
if hi < 2 ^ 21 then
return hi * 4294967296 + lo
end
local digits: { string } = {}
-- base 10^6 long division over 16-bit limbs
local limbs = { hi // 65536, hi % 65536, lo // 65536, lo % 65536 }
while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do
local rem = 0
for i = 1, 4 do
local cur = rem * 65536 + limbs[i]
limbs[i] = cur // 1000000
rem = cur % 1000000
end
table.insert(digits, 1, string.format("%06d", rem))
end
local s = string.gsub(table.concat(digits), "^0+", "")
return if s == "" then 0 else s
end
-- number or decimal string -> (hi, lo), two's complement for negatives
local function u64parts(v: any): (number?, number?)
if type(v) == "number" then
if v ~= v or math.abs(v) >= 2 ^ 63 then
return nil, nil
end
v = math.floor(v)
local m = math.abs(v)
local hi = m // 4294967296
local lo = m - hi * 4294967296
if v < 0 then
return (4294967295 - hi + (if lo == 0 then 1 else 0)) % 4294967296, (4294967296 - lo) % 4294967296
end
return hi, lo
elseif type(v) == "string" then
local neg, digits = string.match(v, "^(%-?)(%d+)$")
if not digits or #digits > 20 then
return nil, nil
end
local limbs = { 0, 0, 0, 0 } -- 16-bit, most significant first
for i = 1, #digits do
local carry = tonumber(string.sub(digits, i, i)) :: number
for k = 4, 1, -1 do
local cur = limbs[k] * 10 + carry
limbs[k] = cur % 65536
carry = cur // 65536
end
if carry > 0 then
return nil, nil
end
end
if neg == "-" then
local carry = 1
for k = 4, 1, -1 do
local cur = (65535 - limbs[k]) + carry
limbs[k] = cur % 65536
carry = cur // 65536
end
end
return limbs[1] * 65536 + limbs[2], limbs[3] * 65536 + limbs[4]
end
return nil, nil
end
function Binary.read(buf: buffer | string, offset: number?, length: number?, opts: { maxDepth: number? }?): (Block?, Err.Err?)
local b: buffer = if type(buf) == "string" then buffer.fromstring(buf) else buf
if type(b) ~= "buffer" then
return nil, Err.new(Err.ARG, "KeyValues.readBinary: expected a buffer")
end
local o = offset or 0
local e = o + (length or (buffer.len(b) - o))
if o < 0 or e > buffer.len(b) or e < o then
return nil, Err.new(Err.ARG, "KeyValues.readBinary: range out of the buffer")
end
local maxDepth = opts and opts.maxDepth or 256
local p = o
local function cstr(): string?
local q = p
while q < e and readu8(b, q) ~= 0 do
q += 1
end
if q >= e then
return nil
end
local s = buffer.readstring(b, p, q - p)
p = q + 1
return s
end
local root: Block = {}
local stack: { Block } = { root }
while true do
if p >= e then
if #stack > 1 then
return nil, Err.new(Err.TRUNCATED, "unclosed block", p - o)
end
break
end
local t = readu8(b, p)
p += 1
if t == 8 or t == 11 then
if #stack == 1 then
break
end
table.remove(stack)
else
local cur = stack[#stack]
local key = cstr()
if not key then
return nil, Err.new(Err.TRUNCATED, "key", p - o)
end
if t == 0 then
if #stack >= maxDepth then
return nil, Err.new(Err.LIMIT, "nesting deeper than maxDepth", p - o)
end
local sub: Block = {}
table.insert(cur, { key = key, value = sub })
table.insert(stack, sub)
elseif t == 1 then
local v = cstr()
if not v then
return nil, Err.new(Err.TRUNCATED, "string value", p - o)
end
table.insert(cur, { key = key, value = v })
elseif t == 5 then
local q = p
while q + 1 < e and buffer.readu16(b, q) ~= 0 do
q += 2
end
if q + 1 >= e then
return nil, Err.new(Err.TRUNCATED, "wide string value", p - o)
end
table.insert(cur, { key = key, value = Text.utf16(b, p, q - p), type = "wstring" })
p = q + 2
elseif t == 2 or t == 3 or t == 4 or t == 6 then
if p + 4 > e then
return nil, Err.new(Err.TRUNCATED, "value", p - o)
end
local v = if t == 2 then readi32(b, p) elseif t == 3 then readf32(b, p) else readu32(b, p)
table.insert(cur, { key = key, value = v, type = TYPES[t] })
p += 4
elseif t == 7 or t == 10 then
if p + 8 > e then
return nil, Err.new(Err.TRUNCATED, "value", p - o)
end
local lo, hi = readu32(b, p), readu32(b, p + 4)
local v: number | string
if t == 10 and hi >= 2 ^ 31 then
-- negative: magnitude of the two's complement
local nlo = (4294967296 - lo) % 4294967296
local nhi = 4294967295 - hi + (if lo == 0 then 1 else 0)
local m = u64text(nhi, nlo)
v = if type(m) == "number" then -m else "-" .. m
else
v = u64text(hi, lo)
end
table.insert(cur, { key = key, value = v, type = TYPES[t] })
p += 8
else
return nil, Err.new(Err.CORRUPT, "unknown value type " .. t, p - o - 1)
end
end
end
return root, nil
end
local function utf16(s: string): string
local out: { string } = {}
for _, c in utf8.codes(s) do
if c >= 0x10000 then
local v = c - 0x10000
local hs = 0xD800 + v // 1024
table.insert(out, string.char(hs % 256, hs // 256))
local lo = 0xDC00 + v % 1024
table.insert(out, string.char(lo % 256, lo // 256))
else
table.insert(out, string.char(c % 256, c // 256))
end
end
return table.concat(out)
end
local function writeBlock(blk: Block, out: { string }, depth: number): string?
if depth > 256 then
return "nesting deeper than 256"
end
for _, pr in blk do
if type(pr) ~= "table" or type(pr.key) ~= "string" or string.find(pr.key, "%z") then
return "a pair needs a string key without NUL"
end
local v: any = pr.value
local k = pr.key .. "\0"
if type(v) == "table" then
table.insert(out, "\0" .. k)
local err = writeBlock(v, out, depth + 1)
if err then
return err
end
table.insert(out, "\8")
else
local code = if pr.type then CODES[pr.type] else (if type(v) == "number" then (if v % 1 == 0 and v >= -2 ^ 31 and v < 2 ^ 31 then 2 else 3) else 1)
if not code then
return "unknown value type " .. tostring(pr.type)
end
local w = buffer.create(8)
if code == 1 then
if type(v) ~= "string" or string.find(v, "%z") then
return "string value expected for key " .. pr.key
end
table.insert(out, "\1" .. k .. v .. "\0")
elseif code == 5 then
if type(v) ~= "string" or not utf8.len(v) then
return "UTF-8 string value expected for key " .. pr.key
end
table.insert(out, "\5" .. k .. utf16(v) .. "\0\0")
elseif code == 7 or code == 10 then
local hi, lo = u64parts(v)
if not hi then
return "64-bit value expected for key " .. pr.key
end
buffer.writeu32(w, 0, lo :: number)
buffer.writeu32(w, 4, hi :: number)
table.insert(out, string.char(code) .. k .. buffer.readstring(w, 0, 8))
else
if type(v) ~= "number" then
return "number value expected for key " .. pr.key
end
if code == 3 then
buffer.writef32(w, 0, v)
elseif code == 2 then
if v % 1 ~= 0 or v < -2 ^ 31 or v >= 2 ^ 31 then
return "int32 out of range for key " .. pr.key
end
buffer.writei32(w, 0, v)
else
if v % 1 ~= 0 or v < 0 or v >= 2 ^ 32 then
return "u32 out of range for key " .. pr.key
end
buffer.writeu32(w, 0, v)
end
table.insert(out, string.char(code) .. k .. buffer.readstring(w, 0, 4))
end
end
end
return nil
end
function Binary.write(blk: Block): (buffer?, Err.Err?)
if type(blk) ~= "table" then
return nil, Err.new(Err.ARG, "KeyValues.writeBinary: expected a pair list")
end
local out: { string } = {}
local err = writeBlock(blk, out, 0)
if err then
return nil, Err.new(Err.ARG, err)
end
table.insert(out, "\8")
return buffer.fromstring(table.concat(out)), nil
end
-- a type byte 0 / 1 / 2 then a printable NUL-terminated key
function Binary.sniff(b: buffer, o: number, n: number): boolean
if n < 3 then
return false
end
local t = readu8(b, o)
if t ~= 0 and t ~= 1 and t ~= 2 then
return false
end
for i = 1, math.min(n - 1, 64) do
local c = readu8(b, o + i)
if c == 0 then
return i > 1
elseif c < 32 then
return false
end
end
return false
end
return Binary
+555
View File
@@ -0,0 +1,555 @@
--!strict
-- codecs/text/KeyValues: Valve KeyValues text (tier1/KeyValues.cpp of the Source SDK 2013, srctools' reading of it)
-- and binary KeyValues (Steam appinfo / shortcuts.vdf). Pair lists keep order, duplicates and [$CONDITION]s;
-- #include / #base go through opts.resolve; the BSP entity lump ({ ... } blocks without keys) too.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Binary = require("@rosetta/codecs/text/KeyValues/Binary")
local KeyValues = {}
export type Pair = Binary.Pair
export type Block = Binary.Block
export type ParseOptions = {
escapes: boolean?, -- \n \t \\ \" ... in quoted strings, default true
-- [$X] conditions: the flags that are true (case-insensitive names, without $); default { WIN32 = true }, the
-- other SDK names (X360, PS3, GAMECONSOLE, OSX, LINUX, POSIX, WINDOWS, DECK) false; false keeps every pair with
-- its cond
defines: ({ [string]: boolean } | false)?,
resolve: ((name: string) -> (buffer | string)?)?, -- #include / #base files
maxDepth: number?, -- default 256
}
export type WriteOptions = {
escapes: boolean?, -- default true
indent: string?, -- default "\t"
}
export type ObjectOptions = {
duplicates: ("array" | "last" | "first")?, -- default "array": a repeated key's values become an array
}
local DEFAULT_DEFINES: { [string]: boolean } = { win32 = true }
local ESCAPE: { [string]: string } = { n = "\n", t = "\t", v = "\v", b = "\b", r = "\r", f = "\f", a = "\a", ["\\"] = "\\", ["?"] = "?", ["'"] = "'", ['"'] = '"' }
type Lexer = { s: string, i: number, n: number, escapes: boolean }
-- kind: "s" string, "{", "}", "[" condition (its text), nil at the end; err on an unterminated string
local function token(lx: Lexer): (string?, string?, number, string?)
local s, n = lx.s, lx.n
local i = lx.i
while true do
local a = string.find(s, "[^ \t\r\n\f\v]", i)
if not a then
lx.i = n + 1
return nil, nil, n, nil
end
i = a
if string.sub(s, i, i + 1) == "//" then
local e = string.find(s, "\n", i, true)
if not e then
lx.i = n + 1
return nil, nil, n, nil
end
i = e + 1
else
break
end
end
local c = string.sub(s, i, i)
if c == "{" or c == "}" then
lx.i = i + 1
return c, nil, i - 1, nil
elseif c == '"' then
local start = i
i += 1
if not lx.escapes then
local e = string.find(s, '"', i, true)
if not e then
lx.i = n + 1
return nil, nil, start - 1, "unterminated string"
end
lx.i = e + 1
return "s", string.sub(s, i, e - 1), start - 1, nil
end
local parts: { string } = {}
while true do
local e = string.find(s, '["\\]', i)
if not e then
lx.i = n + 1
return nil, nil, start - 1, "unterminated string"
end
table.insert(parts, string.sub(s, i, e - 1))
if string.sub(s, e, e) == '"' then
lx.i = e + 1
return "s", table.concat(parts), start - 1, nil
end
local x = string.sub(s, e + 1, e + 1)
local r = ESCAPE[x]
if r then
table.insert(parts, r)
i = e + 2
else
table.insert(parts, "\\")
i = e + 1
end
end
elseif c == "[" then
local e = string.find(s, "]", i, true)
local sp = string.find(s, "[\r\n]", i)
if e and (not sp or sp > e) then
lx.i = e + 1
return "[", string.sub(s, i + 1, e - 1), i - 1, nil
end
end
local e = string.find(s, '[ \t\r\n\f\v"{}]', i)
local stop = if e then e - 1 else n
lx.i = stop + 1
return "s", string.sub(s, i, stop), i - 1, nil
end
-- "$A || !$B && $C": || of && terms; a term is [!]$NAME (KeyValues::EvaluateConditional)
function KeyValues.condition(cond: string, defines: { [string]: boolean }?): boolean
local d = defines or DEFAULT_DEFINES
local function flag(name: string): boolean
local l = string.lower(name)
for k, v in d do
if string.lower(k) == l then
return v == true
end
end
return false
end
local any = false
for alt in string.gmatch(cond .. "||", "(.-)||") do
local all = true
for term in string.gmatch(alt .. "&&", "(.-)&&") do
local neg, name = string.match(term, "^%s*(!?)%s*%$?([%w_]*)%s*$")
if not name then
all = false
else
local v = flag(name :: string)
if neg == "!" then
v = not v
end
all = all and v
end
end
any = any or all
end
return any
end
local function keyEq(a: string, b: string): boolean
return a == b or string.lower(a) == string.lower(b)
end
local function parseText(text: string, opts: ParseOptions?, depth0: number): (Block?, Err.Err?)
local o: ParseOptions = opts or {}
local lx: Lexer = { s = text, i = 1, n = #text, escapes = o.escapes ~= false }
if string.sub(text, 1, 3) == "\239\187\191" then
lx.i = 4
end
local defines: { [string]: boolean }? = nil
local evaluate = o.defines ~= false
if type(o.defines) == "table" then
defines = o.defines
end
local maxDepth = o.maxDepth or 256
local root: Block = {}
local stack: { Block } = { root }
local skipping = 0 -- depth inside a block whose condition failed
local canReplace = false
local includes: { { kind: string, name: string } } = {}
while true do
local kind, v, at, terr = token(lx)
if terr then
return nil, Err.new(Err.TRUNCATED, terr, at)
end
if kind == nil then
if #stack > 1 or skipping > 0 then
return nil, Err.new(Err.TRUNCATED, "unclosed block", at)
end
break
end
local cur = stack[#stack]
if kind == "}" then
if skipping > 0 then
skipping -= 1
elseif #stack == 1 then
return nil, Err.new(Err.CORRUPT, "unbalanced '}'", at)
else
table.remove(stack)
end
canReplace = false
elseif kind ~= "s" then
return nil, Err.new(Err.CORRUPT, if kind == "{" then "block without a key" else "condition without a key", at)
else
local key = v :: string
local k2, v2, at2, terr2 = token(lx)
if terr2 then
return nil, Err.new(Err.TRUNCATED, terr2, at2)
end
local cond: string? = nil
if k2 == "[" then
cond = v2
k2, v2, at2, terr2 = token(lx)
if terr2 then
return nil, Err.new(Err.TRUNCATED, terr2, at2)
end
if k2 ~= "{" then
return nil, Err.new(Err.CORRUPT, "a condition after a key needs a block", at2)
end
end
if k2 == "{" then
if #stack + skipping > maxDepth then
return nil, Err.new(Err.LIMIT, "nesting deeper than maxDepth", at2)
end
local pass = skipping == 0 and (cond == nil or not evaluate or KeyValues.condition(cond :: string, defines))
if not pass then
skipping += 1
else
local pair: Pair = { key = key, value = {}, cond = if evaluate then nil else cond }
local last = cur[#cur]
if cond and evaluate and canReplace and last and type(last.value) == "table" and last.key == key then
cur[#cur] = pair
else
table.insert(cur, pair)
end
table.insert(stack, pair.value :: Block)
end
canReplace = false
elseif k2 == "s" then
local value = v2 :: string
-- a condition after a value: only on the same line
local save = lx.i
local k3, v3 = token(lx)
local c3: string? = nil
if k3 == "[" and not string.find(string.sub(text, save, lx.i - 1), "\n", 1, true) then
c3 = v3
else
lx.i = save
end
if skipping == 0 then
local pass = c3 == nil or not evaluate or KeyValues.condition(c3 :: string, defines)
if pass then
local pair: Pair = { key = key, value = value, cond = if evaluate then nil else c3 }
local last = cur[#cur]
if c3 and evaluate and canReplace and last and type(last.value) == "string" and last.key == key then
cur[#cur] = pair
canReplace = false
else
table.insert(cur, pair)
canReplace = c3 == nil
end
if #stack == 1 and (key == "#include" or key == "#base") and o.resolve then
table.remove(cur)
table.insert(includes, { kind = key, name = value })
end
end
end
elseif k2 == nil then
return nil, Err.new(Err.TRUNCATED, "key without a value", at)
else
return nil, Err.new(Err.CORRUPT, "unexpected '" .. tostring(k2) .. "' after a key", at2)
end
end
end
if #includes > 0 then
if depth0 >= 16 then
return nil, Err.new(Err.LIMIT, "#include / #base nested more than 16 deep")
end
local resolve = o.resolve :: (string) -> (buffer | string)?
for _, inc in includes do
local ok, data = pcall(resolve, inc.name)
if not ok or data == nil then
return nil, Err.new(Err.IO, inc.kind .. ' "' .. inc.name .. '" not found')
end
local s = if type(data) == "buffer" then buffer.tostring(data) else tostring(data)
local sub, err = parseText(s, o, depth0 + 1)
if not sub then
return nil, Err.new((err :: Err.Err).code, inc.name .. ": " .. (err :: Err.Err).message)
end
if inc.kind == "#include" then
for _, p in sub do
table.insert(root, p)
end
else
KeyValues.merge(root, sub)
end
end
end
return root, nil
end
function KeyValues.parse(text: string | buffer, opts: ParseOptions?): (Block?, Err.Err?)
local s = if type(text) == "buffer" then buffer.tostring(text) else text
if type(s) ~= "string" then
return nil, Err.new(Err.ARG, "KeyValues.parse: expected a string or a buffer")
end
return parseText(s, opts, 0)
end
-- #base: keys of base missing from into are added; blocks present in both merge recursively (RecursiveMergeKeyValues)
function KeyValues.merge(into: Block, base: Block)
for _, bp in base do
local found: Pair? = nil
for _, p in into do
if keyEq(p.key, bp.key) then
found = p
break
end
end
if not found then
table.insert(into, KeyValues.copy({ bp })[1])
elseif type(found.value) == "table" and type(bp.value) == "table" then
KeyValues.merge(found.value :: Block, bp.value :: Block)
end
end
end
function KeyValues.copy(b: Block): Block
local out: Block = table.create(#b) :: any
for i, p in b do
local v: any = p.value
out[i] = { key = p.key, value = if type(v) == "table" then KeyValues.copy(v) else v, cond = p.cond, type = p.type }
end
return out
end
-- the first pair with this key (case-insensitive, as KeyValues::FindKey); "a/b/c" walks blocks
function KeyValues.find(b: Block, path: string): Pair?
local cur: Block? = b
local found: Pair? = nil
for part in string.gmatch(path, "[^/]+") do
if not cur then
return nil
end
found = nil
for _, p in cur do
if keyEq(p.key, part) then
found = p
break
end
end
if not found then
return nil
end
cur = if type(found.value) == "table" then found.value :: Block else nil
end
return found
end
function KeyValues.get(b: Block, path: string): any
local p = KeyValues.find(b, path)
return p and p.value
end
function KeyValues.all(b: Block, key: string): { Pair }
local out: { Pair } = {}
for _, p in b do
if keyEq(p.key, key) then
table.insert(out, p)
end
end
return out
end
local function quote(s: string, escapes: boolean): string
if escapes then
s = string.gsub(s, '[\\"\n\t\r]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n", ["\t"] = "\\t", ["\r"] = "\\r" })
end
return '"' .. s .. '"'
end
local function writeBlock(b: Block, out: { string }, indent: string, level: number, escapes: boolean, depth: number): string?
if depth > 256 then
return "nesting deeper than 256"
end
local pad = string.rep(indent, level)
for _, p in b do
if type(p) ~= "table" or type(p.key) ~= "string" then
return "a pair needs a string key"
end
local v: any = p.value
local cond = if type(p.cond) == "string" then " [" .. p.cond .. "]" else ""
if type(v) == "table" then
table.insert(out, pad .. quote(p.key, escapes) .. cond .. "\n" .. pad .. "{\n")
local err = writeBlock(v, out, indent, level + 1, escapes, depth + 1)
if err then
return err
end
table.insert(out, pad .. "}\n")
elseif type(v) == "string" or type(v) == "number" or type(v) == "boolean" then
local s = if type(v) == "boolean" then (if v then "1" else "0") else tostring(v)
table.insert(out, pad .. quote(p.key, escapes) .. "\t" .. quote(s, escapes) .. cond .. "\n")
else
return "unwritable value for key " .. p.key
end
end
return nil
end
function KeyValues.write(b: Block, opts: WriteOptions?): (string?, Err.Err?)
if type(b) ~= "table" then
return nil, Err.new(Err.ARG, "KeyValues.write: expected a pair list")
end
local out: { string } = {}
local err = writeBlock(b, out, opts and opts.indent or "\t", 0, not (opts and opts.escapes == false), 0)
if err then
return nil, Err.new(Err.ARG, err)
end
return table.concat(out), nil
end
function KeyValues.toObject(b: Block, opts: ObjectOptions?): any
local mode = opts and opts.duplicates or "array"
local o = Types.object()
local multi: { [string]: boolean } = {}
for _, p in b do
local v: any = p.value
if type(v) == "table" then
v = KeyValues.toObject(v, opts)
end
local old = o[p.key]
if old == nil then
Types.set(o, p.key, v)
elseif mode == "last" then
o[p.key] = v
elseif mode == "array" then
if not multi[p.key] then
o[p.key] = { old }
multi[p.key] = true
end
table.insert(o[p.key], v)
end
end
return o
end
local function fromValue(key: string, v: any, out: Block, depth: number): string?
if depth > 256 then
return "nesting deeper than 256"
end
if type(v) == "table" and not Types.isObject(v) and Types.isArray(v, true) then
for _, x in v do
if type(x) == "table" and not Types.isObject(x) and Types.isArray(x, true) then
return "nested array under key " .. key
end
local err = fromValue(key, x, out, depth + 1)
if err then
return err
end
end
return nil
elseif type(v) == "table" then
local sub: Block = {}
local t: { [any]: any } = v :: any
for _, k in Types.keys(t) do
if type(k) ~= "string" and type(k) ~= "number" then
return "unwritable key"
end
local err = fromValue(tostring(k), t[k], sub, depth + 1)
if err then
return err
end
end
table.insert(out, { key = key, value = sub })
return nil
elseif type(v) == "string" or type(v) == "number" or type(v) == "boolean" then
table.insert(out, { key = key, value = if type(v) == "string" then v elseif type(v) == "boolean" then (if v then "1" else "0") else tostring(v) })
return nil
end
return "unwritable value for key " .. key
end
-- a Types.object / plain table -> pairs (arrays repeat their key; booleans become "1" / "0")
function KeyValues.fromObject(v: any): (Block?, Err.Err?)
if type(v) ~= "table" then
return nil, Err.new(Err.ARG, "KeyValues.fromObject: expected a table")
end
local out: Block = {}
for _, k in Types.keys(v) do
if type(k) ~= "string" and type(k) ~= "number" then
return nil, Err.new(Err.ARG, "unwritable key")
end
local err = fromValue(tostring(k), v[k], out, 0)
if err then
return nil, Err.new(Err.ARG, err)
end
end
return out, nil
end
-- pair list or object
function KeyValues.pairs(v: any): (Block?, Err.Err?)
if type(v) == "table" and not Types.isObject(v) and (#v > 0 or next(v) == nil) then
local first = v[1]
if first == nil or (type(first) == "table" and type(first.key) == "string") then
return v, nil
end
end
return KeyValues.fromObject(v)
end
-- BSP entity lump: { "k" "v" ... } blocks, no escapes (CMapEntities / ParseEntity)
function KeyValues.entities(text: string): ({ Block }?, Err.Err?)
text = string.match(text, "^[^%z]*") :: string
local lx: Lexer = { s = text, i = 1, n = #text, escapes = false }
local out: { Block } = {}
local cur: Block? = nil
while true do
local kind, v, at, terr = token(lx)
if terr then
return nil, Err.new(Err.TRUNCATED, terr, at)
end
if kind == nil then
if cur then
return nil, Err.new(Err.TRUNCATED, "unclosed entity", at)
end
return out, nil
elseif kind == "{" then
if cur then
return nil, Err.new(Err.CORRUPT, "'{' inside an entity", at)
end
cur = {}
elseif kind == "}" then
if not cur then
return nil, Err.new(Err.CORRUPT, "unbalanced '}'", at)
end
table.insert(out, cur :: Block)
cur = nil
elseif not cur then
return nil, Err.new(Err.CORRUPT, "key outside an entity", at)
else
local k2, v2, at2, terr2 = token(lx)
if terr2 then
return nil, Err.new(Err.TRUNCATED, terr2, at2)
end
if k2 ~= "s" then
return nil, Err.new(Err.CORRUPT, "entity key without a value", at)
end
table.insert(cur, { key = v :: string, value = v2 :: string })
end
end
end
function KeyValues.writeEntities(list: { Block }): (string?, Err.Err?)
local out: { string } = {}
for _, e in list do
table.insert(out, "{\n")
for _, p in e do
if type(p.value) ~= "string" then
return nil, Err.new(Err.ARG, "entity values are strings")
end
table.insert(out, '"' .. p.key .. '" "' .. (p.value :: string) .. '"\n')
end
table.insert(out, "}\n")
end
return table.concat(out), nil
end
KeyValues.readBinary = Binary.read
KeyValues.writeBinary = Binary.write
KeyValues.isBinary = Binary.sniff
return KeyValues
+99
View File
@@ -0,0 +1,99 @@
--!strict
-- data/vdf: Valve KeyValues files (.vdf, .acf, .res, ...) as data over codecs/text/KeyValues, read and written; binary
-- KeyValues (shortcuts.vdf) too. Values are ordered objects, a repeated key's values an array (opts.duplicates);
-- opts.pairs gives the pair list with conditions and binary types. Not supported: appinfo.vdf / packageinfo.vdf headers.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Sniff = require("@rosetta/core/Sniff")
local KeyValues = require("@rosetta/codecs/text/KeyValues")
-- ------------------------------------------------------------------------------------------------ contract
local Vdf = {
name = "vdf",
category = "data",
extensions = { "vdf", "acf", "res", "kv" },
mime = { "text/x-vdf" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/KeyValues" },
caps = { decode = true, encode = true, ordered = true, binary = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
pairs: boolean?, -- the KeyValues pair list instead of an object
duplicates: ("array" | "last" | "first")?, -- default "array"
escapes: boolean?, -- default true
defines: ({ [string]: boolean } | false)?, -- [$X] conditions (codecs/text/KeyValues), default PC
resolve: ((name: string) -> (buffer | string)?)?, -- #include / #base
binary: boolean?, -- force binary (default: sniffed)
}
export type EncodeOptions = {
binary: boolean?, -- default false
escapes: boolean?, -- default true
indent: string?, -- default "\t"
}
-- ------------------------------------------------------------------------------------------------ sniff
function Vdf.sniff(r: Bytes.Reader): number
local n = r:remaining()
if KeyValues.isBinary(r.buf, r.pos, n) then
return 0.3
end
local head = Sniff.text(r, 256, true)
if string.find(head, "%z") then
return 0
end
head = string.gsub(head, "^//[^\n]*\n%s*", "")
if string.match(head, '^"[^"\n]+"%s*{') or string.match(head, '^"[^"\n]+"%s*%[[^%]\n]*%]%s*{') then
return 0.6
end
if string.match(head, "^#base%s") or string.match(head, "^#include%s") then
return 0.5
end
if string.match(head, '^[%w_]+%s*\n%s*{%s*\n%s*"') then
return 0.3
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Vdf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local n = r.limit - r.base
local blk, err
if o.binary or (o.binary == nil and KeyValues.isBinary(r.buf, r.base, n)) then
blk, err = KeyValues.readBinary(r.buf, r.base, n)
else
blk, err = KeyValues.parse(buffer.readstring(r.buf, r.base, n), {
escapes = o.escapes,
defines = o.defines,
resolve = o.resolve,
})
end
if not blk then
return nil, err
end
if o.pairs then
return blk, nil
end
return KeyValues.toObject(blk, { duplicates = o.duplicates }), nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Vdf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local blk, err = KeyValues.pairs(value)
if not blk then
return nil, err
end
if opts and opts.binary then
return KeyValues.writeBinary(blk)
end
local s, werr = KeyValues.write(blk, { escapes = opts and opts.escapes, indent = opts and opts.indent })
if not s then
return nil, werr
end
return buffer.fromstring(s), nil
end
return Vdf
+166
View File
@@ -0,0 +1,166 @@
-- codecs/text/KeyValues tests: text against srctools' Keyvalues.parse, trees written by the python vdf module, binary
-- KeyValues by vdf.binary_dumps; write round trips, conditions, #include / #base, the entity lump, errors, fuzz.
-- Fixtures: tools/fixtures/keyvalues.py.
local T = require("@tests/T")
local KeyValues = require("@rosetta/codecs/text/KeyValues")
local Err = require("@rosetta/core/Err")
local Fx = require("@tests/gen/keyvalues")
local t = T.suite("keyvalues")
local function canon(b: KeyValues.Block, typed: boolean?): string
local out = { "{" }
for _, p in b do
table.insert(out, #p.key .. ":" .. p.key .. "=")
local v = p.value
if type(v) == "table" then
table.insert(out, canon(v, typed))
elseif typed and p.type then
local tag = ({ int32 = "i32", float32 = "f32", pointer = "ptr", color = "col", uint64 = "u64", int64 = "i64", wstring = "wstr" } :: any)[p.type]
if p.type == "float32" then
table.insert(out, tag .. "f" .. string.format("%.17g", v))
elseif type(v) == "string" and p.type ~= "wstring" then
table.insert(out, tag .. "i" .. v)
else
table.insert(out, tag .. "i" .. string.format("%d", v))
end
else
table.insert(out, "s" .. #v .. ":" .. v)
end
end
table.insert(out, "}")
return table.concat(out)
end
for i, c in Fx.text do
local b, err = KeyValues.parse(c.data)
t:check(b ~= nil, "text " .. i .. ": " .. tostring(err))
if b then
t:eq(canon(b), c.canon, "text " .. i .. ": same pairs as srctools")
local s = KeyValues.write(b) :: string
local b2 = KeyValues.parse(s)
t:eq(b2 and canon(b2), c.canon, "text " .. i .. ": write round trip")
end
end
for i, c in Fx.written do
local b, err = KeyValues.parse(c.data)
t:check(b ~= nil, "vdf.dumps " .. i .. ": " .. tostring(err))
t:eq(b and canon(b), c.canon, "vdf.dumps " .. i .. ": pairs")
if b then
local b2 = KeyValues.parse(KeyValues.write(b) :: string)
t:eq(b2 and canon(b2), c.canon, "vdf.dumps " .. i .. ": round trip")
end
end
for i, c in Fx.binary do
local b, err = KeyValues.readBinary(c.data)
t:check(b ~= nil, "binary " .. i .. ": " .. tostring(err))
if b then
t:eq(canon(b, true), c.canon, "binary " .. i .. ": values as vdf.binary_loads")
local w = KeyValues.writeBinary(b) :: buffer
t:eq(buffer.tostring(w), c.data, "binary " .. i .. ": identical bytes")
end
t:check(KeyValues.isBinary(buffer.fromstring(c.data), 0, #c.data), "binary " .. i .. ": sniffed")
end
do
-- conditions
t:check(KeyValues.condition("$WIN32"), "WIN32 by default")
t:check(not KeyValues.condition("$X360"), "X360 off")
t:check(KeyValues.condition("!$X360"), "negation")
t:check(KeyValues.condition("$X360 || $WIN32"), "or")
t:check(not KeyValues.condition("$WIN32 && $OSX"), "and")
t:check(KeyValues.condition("$OSX", { OSX = true }), "defines")
local b = KeyValues.parse('"r" { "a" "1" [$X360] "a" "2" [$X360||$WIN32] }') :: KeyValues.Block
t:eq(KeyValues.get(b, "r/a"), "2", "|| in a condition")
local keep = KeyValues.parse('"r" { "a" "1" [$X360] "a" "2" [$WIN32] }', { defines = false }) :: KeyValues.Block
local r = KeyValues.find(keep, "r") :: KeyValues.Pair
t:eq(#r.value, 2, "defines = false keeps both")
t:eq(r.value[1].cond, "$X360", "cond kept")
t:check(string.find(KeyValues.write(keep) :: string, '"a"\t"1" [$X360]', 1, true) ~= nil, "cond written")
-- #include / #base
local files = {
["base.res"] = '"r" { "a" "base" "b" "base" "sub" { "x" "1" "y" "1" } }',
["inc.res"] = '"extra" { "k" "v" }',
}
local main = '#base "base.res"\n#include "inc.res"\n"r" { "a" "main" "sub" { "x" "2" } }'
local m = KeyValues.parse(main, { resolve = function(n: string): string?
return files[n]
end }) :: KeyValues.Block
t:eq(KeyValues.get(m, "r/a"), "main", "#base: main wins")
t:eq(KeyValues.get(m, "r/b"), "base", "#base: missing key added")
t:eq(KeyValues.get(m, "r/sub/x"), "2", "#base: nested merge keeps main")
t:eq(KeyValues.get(m, "r/sub/y"), "1", "#base: nested merge adds")
t:eq(KeyValues.get(m, "extra/k"), "v", "#include appended")
t:eq(m[#m].key, "extra", "#include after the file's keys")
local raw = KeyValues.parse(main) :: KeyValues.Block
t:eq(raw[1].key, "#base", "no resolve: directive kept as a pair")
local _, e1 = KeyValues.parse(main, { resolve = function()
return nil
end })
t:eq(e1 and e1.code, Err.IO, "missing include")
local _, e2 = KeyValues.parse('#include "self"', { resolve = function()
return '#include "self"'
end })
t:eq(e2 and e2.code, Err.LIMIT, "include loop")
-- objects
local o = KeyValues.toObject(KeyValues.parse('"r" { "d" "1" "d" "2" "x" "y" }') :: KeyValues.Block)
t:eq(#o.r.d, 2, "duplicates -> array")
local last = KeyValues.toObject(KeyValues.parse('"r" { "d" "1" "d" "2" }') :: KeyValues.Block, { duplicates = "last" })
t:eq(last.r.d, "2", "duplicates last")
local back = KeyValues.fromObject(o) :: KeyValues.Block
t:eq(canon(back), "{1:r={1:d=s1:11:d=s1:21:x=s1:y}}", "fromObject repeats array keys in order")
-- escapes off
local ne = KeyValues.parse('"p" "C:\\maps\\x"', { escapes = false }) :: KeyValues.Block
t:eq(ne[1].value, "C:\\maps\\x", "escapes off")
-- entity lump
local ents = KeyValues.entities('{\n"classname" "worldspawn"\n"mapversion" "1"\n}\n{\n"classname" "logic_relay"\n"OnTrigger" "a,b,,0,-1"\n"OnTrigger" "c,d,,0,-1"\n}\n\0') :: { KeyValues.Block }
t:eq(#ents, 2, "entities")
t:eq(#KeyValues.all(ents[2], "ontrigger"), 2, "repeated outputs kept")
local again = KeyValues.entities(KeyValues.writeEntities(ents) :: string) :: { KeyValues.Block }
t:eq(canon(again[2]), canon(ents[2]), "entity round trip")
-- 64-bit binary values
local big = KeyValues.writeBinary({ { key = "id", value = "76561197960287930", type = "uint64" }, { key = "n", value = -5, type = "int64" }, { key = "w", value = "\u{e9}\u{1F600}", type = "wstring" } }) :: buffer
local rb = KeyValues.readBinary(big) :: KeyValues.Block
t:eq(rb[1].value, "76561197960287930", "uint64 above 2^53 as digits")
t:eq(rb[2].value, -5, "negative int64")
t:eq(rb[3].value, "\u{e9}\u{1F600}", "wide string")
-- errors
local function code(s: string): string?
local _, e = KeyValues.parse(s)
return e and e.code
end
t:eq(code('"r" { "a" "1"'), Err.TRUNCATED, "unclosed block")
t:eq(code('"r" "unterminated'), Err.TRUNCATED, "unterminated string")
t:eq(code('"r" { } }'), Err.CORRUPT, "extra brace")
t:eq(code("{ }"), Err.CORRUPT, "block without a key")
t:eq(code(string.rep('"a" {', 300) .. string.rep("}", 300)), Err.LIMIT, "depth limit")
local _, be = KeyValues.readBinary(buffer.fromstring("\1key\0no end"))
t:eq(be and be.code, Err.TRUNCATED, "binary truncated")
local _, we = KeyValues.write({ { key = "k", value = function() end } } :: any)
t:eq(we and we.code, Err.ARG, "unwritable value")
end
local samples = {}
for _, c in Fx.text do
table.insert(samples, c.data)
end
t:fuzz("parse", function(b: buffer)
return KeyValues.parse(b)
end, samples)
local bsamples = {}
for _, c in Fx.binary do
table.insert(bsamples, c.data)
end
t:fuzz("readBinary", function(b: buffer)
return KeyValues.readBinary(b)
end, bsamples)
t:fuzz("entities", function(b: buffer)
return KeyValues.entities(buffer.tostring(b))
end, { '{\n"classname" "worldspawn"\n}\n{ "a" "b" }' })
t:done()
+62
View File
@@ -0,0 +1,62 @@
-- data/vdf tests: KeyValues text written by the python vdf module decodes to what vdf.loads gives, encodes back;
-- binary KeyValues by sniffing; pair lists; sniff; fuzz. Fixtures: tools/fixtures/keyvalues.py.
local T = require("@tests/T")
local Vdf = require("@rosetta/data/vdf")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Canon = require("@tests/data/Canon")
local Fx = require("@tests/gen/keyvalues")
local t = T.suite("data/vdf")
t:eq(Vdf.name, "vdf", "name")
t:check(Vdf.caps.decode and Vdf.caps.encode, "caps")
local function dec(s: string, opts: any?): (any, any)
return Vdf.decode(Bytes.reader(buffer.fromstring(s)), opts)
end
for i, c in Fx.objects do
local v, err = dec(c.data)
t:check(v ~= nil, "vdf.dumps " .. i .. ": " .. tostring(err))
t:eq(Canon.of(v), c.canon, "vdf.dumps " .. i .. ": as vdf.loads")
local back = dec(buffer.tostring(Vdf.encode(v) :: buffer))
t:eq(Canon.of(back), c.canon, "vdf.dumps " .. i .. ": encode round trip")
t:check(Vdf.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, "vdf.dumps " .. i .. ": sniff")
end
for i, c in Fx.binary do
local v, err = dec(c.data)
t:check(type(v) == "table" and v.shortcuts ~= nil, "binary " .. i .. ": " .. tostring(err))
local p = dec(c.data, { pairs = true })
t:eq(buffer.tostring(Vdf.encode(p, { binary = true }) :: buffer), c.data, "binary " .. i .. ": pairs round trip")
end
do
local v = dec('"AppState"\n{\n\t"appid"\t"440"\n\t"InstalledDepots"\n\t{\n\t\t"441" { "manifest" "1" }\n\t}\n\t"x" "1"\n\t"x" "2"\n}\n')
t:eq(v.AppState.appid, "440", "acf value")
t:eq(v.AppState.InstalledDepots["441"].manifest, "1", "nested")
t:eq(#v.AppState.x, 2, "duplicates as array")
t:eq(table.concat(Types.keys(v.AppState), ","), "appid,InstalledDepots,x", "key order")
local s = buffer.tostring(Vdf.encode(v) :: buffer)
t:check(string.find(s, '\t"x"\t"1"\n\t"x"\t"2"\n', 1, true) ~= nil, "array written as repeated keys")
local o = Types.object()
Types.set(o, "b", true)
Types.set(o, "n", 3)
t:eq(buffer.tostring(Vdf.encode({ r = o }) :: buffer), '"r"\n{\n\t"b"\t"1"\n\t"n"\t"3"\n}\n', "encode typed values")
local _, e = dec('"r" {')
t:eq(e and e.code, Err.TRUNCATED, "truncated")
local _, ee = Vdf.encode({ r = { function() end } })
t:eq(ee and ee.code, Err.ARG, "unwritable")
t:eq(Vdf.sniff(Bytes.reader(buffer.fromstring("{}"))), 0, "json is not vdf")
end
local samples = {}
for i = 1, 10 do
table.insert(samples, Fx.objects[i].data)
table.insert(samples, Fx.binary[i].data)
end
t:fuzz("decode", function(b: buffer)
return Vdf.decode(Bytes.reader(b))
end, samples)
t:done()
+139
View File
@@ -0,0 +1,139 @@
# codecs/text/KeyValues + data/vdf fixtures: KeyValues text parsed by srctools (Keyvalues.parse, flags $WIN32 on),
# random trees written by the python vdf module (vdf.dumps) and binary KeyValues written / read by vdf.binary_dumps.
# tests/gen/keyvalues.luau { text = { { data, canon } }, objects = { { data, canon } }, written = { { data, canon } }, binary = { { data, canon } } }
# canon: a pair list as "{" .. <len>:<key>=<value> ... "}", a value s<len>:<bytes> | i<int> | f<%.17g> | a block;
# binary types prefix their letter (i32 / f32 / ptr / wstr / col / u64 / i64). objects: vdf.loads of the written
# trees, in tests/data/Canon form.
import importlib.util, json, os
_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)
TEXT = [
'"root"\n{\n\t"a"\t"1"\n\t"b"\t"two words"\n}\n',
'// comment\n"root" { "k" "v" "sub" { "x" "y" } }\n',
'root\n{\n\tkey value\n\tother\t"quoted value"\n\tnested\n\t{\n\t\tdeep 1\n\t}\n}\n',
'"r"\n{\n\t"dup"\t"1"\n\t"dup"\t"2"\n\t"blk" { "a" "1" }\n\t"blk" { "a" "2" }\n}\n',
'"r"\n{\n\t"x"\t"1"\n\t"x"\t"2"\t[$X360]\n\t"y"\t"pc"\t[$WIN32]\n\t"z"\t"not console"\t[!$X360]\n}\n',
'"r"\n{\n\t"esc"\t"a\\tb\\nc\\\\d\\"e"\n}\n',
'"r"\n{\n\t"first" "0"\n\t"blk" [$X360]\n\t{\n\t\t"a" "1"\n\t}\n\t"blk2" [$WIN32]\n\t{\n\t\t"b" "2"\n\t}\n}\n',
'"r" { "empty" "" "emptyblock" { } }\n',
'"a" { "k" "1" }\n"b" { "k" "2" }\n',
'"r"\r\n{\r\n\t"crlf"\t"yes"\r\n}\r\n',
'"r"\n{\n\t"unicode"\t"é中"\n\t"slash"\t"models/props/x.mdl"\n}\n',
'"r"\n{\n\t"c" "1" // trailing comment\n\t// "hidden" "1"\n}\n',
'"r"{"tight""1""t2"{"a""b"}}',
]
CODE = r'''
import json, sys, random
from srctools.keyvalues import Keyvalues
import vdf
FLAGS = {"$win32": True, "win32": True, "$x360": False}
inp = json.loads(sys.stdin.read())
def esc(b):
return b"%d:" % len(b) + b
def canon(kvs):
out = bytearray(b"{")
for q in kvs:
out += esc(q.real_name.encode())
out += b"="
if q.has_children() or isinstance(q.value, list):
out += canon(q)
else:
out += b"s" + esc(q.value.encode())
return bytes(out + b"}")
def vcanon(d):
out = bytearray(b"{")
for k, v in d.items():
out += esc(k.encode()) + b"="
if isinstance(v, dict):
out += vcanon(v)
elif isinstance(v, vdf.UINT_64):
out += b"u64i%d" % int(v)
elif isinstance(v, vdf.INT_64):
out += b"i64i%d" % int(v)
elif isinstance(v, vdf.POINTER):
out += b"ptri%d" % int(v)
elif isinstance(v, vdf.COLOR):
out += b"coli%d" % int(v)
elif isinstance(v, int):
out += b"i32i%d" % int(v)
elif isinstance(v, float):
out += b"f32f" + ("%.17g" % v).encode()
else:
out += b"s" + esc(v.encode())
return bytes(out + b"}")
res = {"text": [], "written": [], "binary": []}
for t in inp["text"]:
kv = Keyvalues.parse(t, flags=FLAGS, single_line=True)
res["text"].append({"data": t, "canon": canon(kv).decode("latin1")})
rng = random.Random(5)
ALPH = "abcXYZ019_ .-/\\\"\té"
def word(n=8):
return "".join(rng.choice(ALPH) for _ in range(rng.randrange(1, n)))
def tree(d):
out = vdf.VDFDict() if False else {}
for i in range(rng.randrange(0, 5)):
k = word() + str(i)
if d < 3 and rng.random() < 0.3:
out[k] = tree(d + 1)
else:
out[k] = word(14)
return out
for i in range(40):
t = {"root%d" % i: tree(0)}
s = vdf.dumps(t, pretty=bool(i % 2))
kv = Keyvalues.parse(s, single_line=True)
res["written"].append({"data": s, "canon": canon(kv).decode("latin1"), "obj": vdf.loads(s)})
import struct
def btree(d):
out = {}
for i in range(rng.randrange(0, 6)):
k = "k%d_%s" % (i, rng.choice(["", "x", "é"]))
r = rng.random()
if d < 3 and r < 0.2:
out[k] = btree(d + 1)
elif r < 0.35:
out[k] = rng.randrange(-2**31, 2**31)
elif r < 0.45:
out[k] = struct.unpack("<f", struct.pack("<f", rng.uniform(-1e6, 1e6)))[0]
elif r < 0.55:
out[k] = vdf.UINT_64(rng.choice([rng.randrange(0, 2**64), 76561197960265728 + rng.randrange(1000), 5]))
elif r < 0.6:
out[k] = vdf.INT_64(rng.randrange(-2**63, 2**63))
elif r < 0.65:
out[k] = vdf.POINTER(rng.randrange(0, 2**31))
elif r < 0.7:
out[k] = vdf.COLOR(rng.randrange(0, 2**31))
else:
out[k] = word(10)
return out
for i in range(30):
t = {"shortcuts": btree(0)}
b = vdf.binary_dumps(t)
back = vdf.binary_loads(b)
res["binary"].append({"data": b.decode("latin1"), "canon": vcanon(back).decode("latin1")})
print(json.dumps(res))
'''
def generate(ctx):
out = ctx.python(["srctools", "vdf"], CODE, input=json.dumps({"text": TEXT}).encode())
res = json.loads(out)
def enc(lst):
return [{"data": c["data"].encode("utf-8") if not isinstance(c["data"], bytes) else c["data"], "canon": c["canon"].encode("latin1")} for c in lst]
objs = [{"data": c["data"].encode("utf-8"), "canon": C.canon(c["obj"])} for c in res["written"]]
ctx.emit("keyvalues", {
"objects": objs,
"text": enc(res["text"]),
"written": enc(res["written"]),
"binary": [{"data": c["data"].encode("latin1"), "canon": c["canon"].encode("latin1")} for c in res["binary"]],
})