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

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

No files matched your search

+12
View File
@@ -86,3 +86,15 @@ do
Xml.encode(doc)
end)
end
do
local Yaml = require("@formats/data/yaml")
local YB = require("@tests/gen/yaml_bench")
local yb = buffer.fromstring(YB.text)
local v = assert(Yaml.decode(Bytes.reader(yb)))
bench("yaml decode (block)", 3, #YB.text, function()
Yaml.decode(Bytes.reader(yb))
end)
bench("yaml encode", 3, #YB.text, function()
Yaml.encode(v)
end)
end
+1 -1
View File
@@ -3,7 +3,7 @@
cd "$(dirname "$0")/.." || exit 1
LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')}
LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')}
python3 -I tools/fixtures.py deflate png json xml > /dev/null || exit 1
python3 -I tools/fixtures.py deflate png json xml yaml > /dev/null || exit 1
python3 -I tools/build.py luajit > /dev/null || exit 1
"$LUAU" --codegen -O2 tools/bench.luau
"$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua
+111
View File
@@ -0,0 +1,111 @@
# data/yaml fixtures: the yaml-test-suite (data release 2022-01-17, pinned tarball through nix: every case's
# in.yaml, its in.json when there is one, and whether it is an error case), and a random corpus dumped by PyYAML
# (through nix) in several styles: block, flow, indent 4, explicit documents, allow_unicode, multi-document. The
# corpus avoids the strings where YAML 1.1 (PyYAML) and 1.2 resolve plain scalars differently.
# tests/gen/yaml_suite.luau { { name, yaml, json?, error } }
# tests/gen/yaml_corpus.luau { { canon, texts = { [style] = yaml } } }
# tests/gen/yaml_bench.luau { text } (~500 KB, block style)
import importlib.util, json, os, random
_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py"))
C = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(C)
SUITE_URL = "https://github.com/yaml/yaml-test-suite/archive/refs/tags/data-2022-01-17.tar.gz"
SUITE_SHA = "00xcny67bp56xkvz4iq6d2prvj9p48z7r705xrw49invvgyp4wnd"
WORDS = ["a", "key", "value", "x y", "café", "中文", "\U0001f600", "multi\nline", "trail\n", "two\n\n",
" lead", "tail ", "a: b", "# c", "- x", "[x]", "{y}", "'q'", "\"dq\"", "true", "null", "~", "12", "1.5",
"0x1F", "yes", "no", "on", "-", "?", ":", "a#b", "tab\there", "back\\slash", "", "éé é",
"line1\n indented\nline3", "ends with colon:", "---", "...", "%x", "@x", "`x", "*x", "&x", "!x", "|", ">"]
def rand_value(rng, depth=0):
r = rng.random()
if depth > 3 or r < 0.5:
k = rng.randrange(8)
if k == 0:
return None
if k == 1:
return rng.random() < 0.5
if k == 2:
return rng.randrange(-10 ** 12, 10 ** 12)
if k == 3:
v = round(rng.uniform(-1e5, 1e5), rng.randrange(1, 6))
return int(v) if v.is_integer() else v
return rng.choice(WORDS) + (rng.choice(WORDS) if rng.random() < 0.3 else "")
if r < 0.75:
return [rand_value(rng, depth + 1) for _ in range(rng.randrange(0, 5))]
d = {}
for _ in range(rng.randrange(0, 5)):
k = rng.choice(WORDS[:30])
if rng.random() < 0.15:
k = rng.randrange(100)
d[k] = rand_value(rng, depth + 1)
return d
DUMP = r'''
import json, sys, yaml
values = json.loads(sys.stdin.read())
def fix(v): # JSON object keys are strings: restore the int keys marked "#int:"
if isinstance(v, dict):
return {(int(k[5:]) if k.startswith("#int:") else k): fix(x) for k, x in v.items()}
if isinstance(v, list):
return [fix(x) for x in v]
return v
out = []
for v in values:
v = fix(v)
t = {
"block": yaml.safe_dump(v, default_flow_style=False, sort_keys=False, allow_unicode=True),
"flow": yaml.safe_dump(v, default_flow_style=True, sort_keys=False),
"indent4": yaml.safe_dump(v, default_flow_style=False, indent=4, explicit_start=True, explicit_end=True),
"auto": yaml.safe_dump(v, sort_keys=True, width=20),
"multi": yaml.safe_dump_all([v, {"second": v}], default_flow_style=False, allow_unicode=True),
}
back = yaml.safe_load(t["block"])
out.append({"texts": t, "same": back == v})
print(json.dumps(out))
'''
def keyed(v):
if isinstance(v, dict):
return {("#int:%d" % k if isinstance(k, int) else k): keyed(x) for k, x in v.items()}
if isinstance(v, list):
return [keyed(x) for x in v]
return v
def generate(ctx):
root = C.fetch(SUITE_URL, SUITE_SHA)
cases = []
for name in sorted(os.listdir(root)):
d = os.path.join(root, name)
if not os.path.isdir(d) or name.startswith("."):
continue
dirs = [d] if os.path.exists(os.path.join(d, "in.yaml")) else [os.path.join(d, x) for x in sorted(os.listdir(d))]
for dd in dirs:
if not os.path.exists(os.path.join(dd, "in.yaml")):
continue
c = {"name": os.path.relpath(dd, root), "yaml": open(os.path.join(dd, "in.yaml"), "rb").read(),
"error": os.path.exists(os.path.join(dd, "error"))}
if os.path.exists(os.path.join(dd, "in.json")):
c["json"] = open(os.path.join(dd, "in.json"), "rb").read()
cases.append(c)
ctx.emit("yaml_suite", cases)
rng = ctx.rng(5)
values = [rand_value(rng) for _ in range(250)]
dumped = json.loads(ctx.python(["pyyaml"], DUMP, input=json.dumps([keyed(v) for v in values]).encode()))
corpus = []
for v, d in zip(values, dumped):
if d["same"]:
corpus.append({"canon": C.canon(v), "multi": C.canon([v, {"second": v}]), "texts": d["texts"]})
ctx.emit("yaml_corpus", corpus)
big = [rand_value(rng) for _ in range(1500)]
text = json.loads(ctx.python(["pyyaml"], "import json, sys, yaml\nprint(json.dumps(yaml.safe_dump(json.loads(sys.stdin.read()), default_flow_style=False, allow_unicode=True)))",
input=json.dumps([x for x in big if not isinstance(x, dict) or all(isinstance(k, str) for k in x)]).encode()))
ctx.emit("yaml_bench", {"text": text})