merge ws/data: codecs Json/Xml, data json xml csv ini toml yaml msgpack cbor plist

This commit is contained in:
4DBug committed 2026-10-31 08:59:44 -05:00
commit e8d2ba81c2
49 files changed
+10395 -3

No files matched your search

+41
View File
@@ -130,4 +130,45 @@ do
end)
end
end
do
local Json = require("@formats/codecs/Json")
local JB = require("@tests/gen/json_bench")
local v = assert(Json.decode(JB.text))
assert(Json.encode(v) == JB.compact, "json bench mismatch")
bench("json decode (indented)", 5, #JB.text, function()
Json.decode(JB.text)
end)
bench("json decode (compact)", 5, #JB.compact, function()
Json.decode(JB.compact)
end)
bench("json encode (compact, sorted)", 5, #JB.compact, function()
Json.encode(v)
end)
end
do
local Xml = require("@formats/codecs/Xml")
local XB = require("@tests/gen/xml_bench")
local doc = assert(Xml.decode(XB.text))
bench("xml decode (DOM)", 5, #XB.text, function()
Xml.decode(XB.text)
end)
bench("xml events", 5, #XB.text, function()
for _ in Xml.events(XB.text) do
end
end)
bench("xml encode", 5, #XB.text, function()
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 zstd brotli bzip2 lzma fonts > /dev/null || exit 1
python3 -I tools/fixtures.py > /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
+110
View File
@@ -0,0 +1,110 @@
# Shared helpers for the data-format fixture generators (json, xml, csv, toml, yaml, msgpack, cbor, plist, ...):
# fetch(url, sha256) -> a nix store path of an unpacked tarball (official test suites, pinned by hash)
# canon(value) -> the canonical text a Luau test computes too (tests/data/_canon.luau): typed, sorted keys,
# numbers as %.17g, so Python's parse and ours compare exactly.
import os, subprocess, datetime
def fetch(url, sha256):
expr = 'builtins.fetchTarball { url = "%s"; sha256 = "%s"; }' % (url, sha256)
out = subprocess.run(["nix", "eval", "--raw", "--impure", "--expr", expr], capture_output=True, check=True)
return out.stdout.decode()
def _b(s):
if isinstance(s, str):
return s.encode("utf-8", "surrogatepass")
return bytes(s)
def canon(v):
"""null n; true t; false f; number #%d (integral, under 2^53) or #%.17g; string s<len>:<bytes>;
bytes b<len>:<bytes>; list [..]; dict {k v ...} with keys sorted by their canon bytes; dates d<rfc3339>"""
out = bytearray()
_canon(v, out)
return bytes(out)
def num(x):
x = float(x)
if x != x:
return b"#nan"
if x in (float("inf"), float("-inf")):
return b"#inf" if x > 0 else b"#-inf"
if x == int(x) and abs(x) < 2 ** 53:
return b"#%d" % int(x)
return b"#" + ("%.17g" % x).encode()
def _canon(v, out):
if v is None:
out += b"n"
elif v is True:
out += b"t"
elif v is False:
out += b"f"
elif isinstance(v, (int, float)):
out += num(v)
elif isinstance(v, str):
b = _b(v)
out += b"s%d:" % len(b) + b
elif isinstance(v, (bytes, bytearray)):
out += b"b%d:" % len(v) + bytes(v)
elif isinstance(v, (list, tuple)):
out += b"["
for x in v:
_canon(x, out)
out += b","
out += b"]"
elif isinstance(v, dict):
items = []
for k, x in v.items():
kb = bytearray()
_canon(k, kb)
items.append((bytes(kb), x))
items.sort(key=lambda p: p[0])
out += b"{"
for kb, x in items:
out += kb + b"="
_canon(x, out)
out += b","
out += b"}"
elif isinstance(v, (datetime.datetime, datetime.date, datetime.time)):
out += b"d" + date_text(v).encode()
else:
raise TypeError("canon: %r" % type(v))
def date_text(v):
"""RFC 3339 the way Types.Date prints: fraction without trailing zeros, Z for +00:00"""
def frac(us):
return ("." + ("%06d" % us).rstrip("0")) if us else ""
def tz(t):
off = t.utcoffset()
if off is None:
return ""
m = int(off.total_seconds()) // 60
if m == 0:
return "Z"
sign = "-" if m < 0 else "+"
m = abs(m)
return "%s%02d:%02d" % (sign, m // 60, m % 60)
if isinstance(v, datetime.datetime):
return "%04d-%02d-%02dT%02d:%02d:%02d%s%s" % (v.year, v.month, v.day, v.hour, v.minute, v.second,
frac(v.microsecond), tz(v))
if isinstance(v, datetime.date):
return "%04d-%02d-%02d" % (v.year, v.month, v.day)
return "%02d:%02d:%02d%s" % (v.hour, v.minute, v.second, frac(v.microsecond))
def python(ctx, packages, body):
"""run body (with these helpers prepended, so canon() / date_text() exist) under a nix python with packages;
returns stdout bytes, raising with the script's stderr on failure"""
import subprocess as sp
src = open(os.path.abspath(__file__)).read()
try:
return ctx.python(packages, src + "\n" + body)
except sp.CalledProcessError as e:
raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:])
+108
View File
@@ -0,0 +1,108 @@
# data/cbor fixtures: RFC 8949 Appendix A examples and random values encoded by Python's cbor2 (through nix): every
# integer width (and bignums), floats, text / byte strings, nested arrays / maps, dates (tags 0 / 1), other tags,
# simple values, undefined, indefinite-length items (written by hand), with the canonical form of cbor2's decode.
# tests/gen/cbor.luau { appendix = { { hex, data, canon } }, safe = { { data, canon } }, wide = { { data, canon,
# canonStr } } } safe: our decode + encode gives the same bytes; wide: big integers (doubles / exact text)
import importlib.util, os, pickle
_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)
APPENDIX = """00 01 0a 17 1818 1819 1864 1903e8 1a000f4240 1b000000e8d4a51000 1bffffffffffffffff c249010000000000000000
3bffffffffffffffff c349010000000000000000 20 29 3863 3903e7 f90000 f98000 f93c00 fb3ff199999999999a f93e00 f97bff
fa47c35000 fa7f7fffff fb7e37e43c8800759c f90001 f90400 f9c400 fbc010666666666666 f97c00 f97e00 f9fc00 fa7f800000
fa7fc00000 faff800000 fb7ff0000000000000 fb7ff8000000000000 fbfff0000000000000 f4 f5 f6 f7 f0 f818 f8ff
c074323031332d30332d32315432303a30343a30305a c11a514b67b0 c1fb41d452d9ec200000 d74401020304
d818456449455446 d82076687474703a2f2f7777772e6578616d706c652e636f6d 40 4401020304 60 6161 6449455446 62225c
62c3bc 63e6b0b4 64f0908591 80 83010203 8301820203820405 98190102030405060708090a0b0c0d0e0f101112131415161718181819
a0 a201020304 a26161016162820203 826161a161626163 a56161614161626142616361436164614461656145 5f42010243030405ff
7f657374726561646d696e67ff 9fff 9f018202039f0405ffff 9f01820203820405ff 83018202039f0405ff 83019f0203ff820405
9f0102030405060708090a0b0c0d0e0f101112131415161718181819ff bf61610161629f0203ffff 826161bf61626163ff
bf6346756ef563416d7421ff"""
BODY = r'''
import cbor2, pickle, random, sys, datetime
from collections.abc import Mapping
HEXES = sys.argv[1:] if False else HEXLIST
def conv(v):
if v is cbor2.undefined:
return ["undefined"]
if isinstance(v, cbor2.CBORSimpleValue):
return ["simple", v.value]
if isinstance(v, cbor2.CBORTag):
return ["tag", v.tag, conv(v.value)]
if isinstance(v, (list, tuple)):
return [conv(x) for x in v]
if isinstance(v, Mapping) or hasattr(v, "items"):
return {(tuple(conv(k)) if isinstance(k, list) else k): conv(x) for k, x in v.items()}
return v
def cstr(v):
if isinstance(v, cbor2.CBORTag):
return cbor2.CBORTag(v.tag, cstr(v.value))
if isinstance(v, int) and not isinstance(v, bool) and abs(v) >= 2**53:
return str(v)
if isinstance(v, (list, tuple)):
return [cstr(x) for x in v]
if isinstance(v, Mapping) or hasattr(v, "items"):
return {k: cstr(x) for k, x in v.items()}
return v
out = {"appendix": [], "safe": [], "wide": []}
for h in HEXES:
data = bytes.fromhex(h)
try:
v = cbor2.loads(data)
except Exception:
out["appendix"].append({"hex": h, "data": data, "error": True}) # e.g. f818: invalid since RFC 8949
continue
if type(v).__name__ in ("Decimal", "Fraction", "UUID") or (isinstance(v, str) and h.startswith("d820")):
continue # semantic tags cbor2 interprets and we keep tagged
out["appendix"].append({"hex": h, "data": data, "canon": canon(conv(v)), "canonStr": canon(conv(cstr(v)))})
rng = random.Random(9)
def rint(wide):
lim = rng.choice([23, 24, 255, 256, 65535, 65536, 2**32 - 1, 2**32, 2**53 - 1])
if wide and rng.random() < 0.4:
lim = rng.choice([2**64 - 1, 2**70])
v = rng.randrange(0, lim + 1)
return -v - 1 if rng.random() < 0.5 else v
def rstr():
return "".join(rng.choice("abé中\U0001f600 \n\x00") for _ in range(rng.choice([0, 1, 23, 24, 255, 300])))
def rval(d, wide):
r = rng.random()
if d > 3 or r < 0.5:
k = rng.randrange(10)
if k == 0: return None
if k == 1: return rng.random() < 0.5
if k in (2, 3): return rint(wide)
if k == 4:
f = rng.uniform(-1e6, 1e6) * 10 ** rng.randrange(-5, 5)
return f if not f.is_integer() else f + 0.5
if k == 5: return rstr()
if k == 6: return rng.randbytes(rng.choice([0, 3, 24, 256]))
if k == 7:
return datetime.datetime.fromtimestamp(rng.randrange(0, 2**33), datetime.timezone.utc)
if k == 8:
return cbor2.CBORTag(rng.choice([6, 1000, 100000]), rval(d + 1, wide))
return rng.choice([cbor2.undefined, cbor2.CBORSimpleValue(rng.choice([0, 19, 32, 255]))])
if r < 0.75:
return [rval(d + 1, wide) for _ in range(rng.choice([0, 1, 3, 23, 24] if d < 2 else [0, 1, 3]))]
m = {}
for _ in range(rng.choice([0, 1, 3, 23, 24] if d < 2 else [0, 1, 3])):
key = rint(False) if rng.random() < 0.3 else "".join(rng.choice("abcé") for _ in range(rng.randrange(6)))
m[key] = rval(d + 1, wide)
return m
for i in range(250):
data = cbor2.dumps(rval(0, False))
out["safe"].append({"data": data, "canon": canon(conv(cbor2.loads(data)))})
for i in range(120):
data = cbor2.dumps(rval(0, True))
v = cbor2.loads(data)
out["wide"].append({"data": data, "canon": canon(conv(v)), "canonStr": canon(conv(cstr(v)))})
sys.stdout.buffer.write(pickle.dumps(out, protocol=4))
'''
def generate(ctx):
hexes = APPENDIX.split()
out = pickle.loads(C.python(ctx, ["cbor2"], "HEXLIST = %r\n" % hexes + BODY))
ctx.emit("cbor", out)
+43
View File
@@ -0,0 +1,43 @@
# data/csv fixtures: random tables (quotes, delimiters, CR / LF / CRLF inside fields, empty fields, unicode) written
# by Python's csv.writer / DictWriter in several dialects, with the rows csv.reader reads back (blank rows dropped:
# we skip blank lines).
# tests/gen/csv.luau { { data, delimiter, rows = { { field } }, keyed? } }
# keyed: the file has a header row (DictWriter)
import csv, io
def rand_field(rng):
alph = 'ab ,;\t|"\n\ré中1.'
k = rng.random()
if k < 0.15:
return ""
if k < 0.3:
return str(rng.randrange(-1000, 1000))
return "".join(rng.choice(alph) for _ in range(rng.randrange(1, 8)))
def generate(ctx):
rng = ctx.rng(13)
cases = []
for i in range(200):
delim = rng.choice([",", ",", ";", "\t", "|"])
ncol = rng.randrange(1, 6)
rows = [[rand_field(rng) for _ in range(ncol)] for _ in range(rng.randrange(1, 12))]
buf = io.StringIO(newline="")
lt = "\r\n" if delim == "," else rng.choice(["\r\n", "\n"])
w = csv.writer(buf, delimiter=delim, lineterminator=lt)
w.writerows(rows)
data = buf.getvalue()
back = [r for r in csv.reader(io.StringIO(data, newline=""), delimiter=delim) if r]
cases.append({"data": data.encode(), "delimiter": delim, "newline": lt, "rows": back})
for i in range(30):
cols = ["id", "name", "note é", "x,y"][: rng.randrange(1, 5)]
rows = [{c: rand_field(rng) for c in cols} for _ in range(rng.randrange(1, 8))]
buf = io.StringIO(newline="")
w = csv.DictWriter(buf, fieldnames=cols)
w.writeheader()
w.writerows(rows)
data = buf.getvalue()
back = [r for r in csv.reader(io.StringIO(data, newline="")) if r]
cases.append({"data": data.encode(), "delimiter": ",", "newline": "\r\n", "rows": back, "keyed": True})
ctx.emit("csv", cases)
+62
View File
@@ -0,0 +1,62 @@
# data/ini fixtures: random configs written by Python's configparser (interpolation off, key case kept), and
# hand-written messy files (comments, ':' delimiters, continuation lines, odd spacing, duplicates) with what
# configparser(strict=False) reads from them.
# tests/gen/ini.luau { written = { { data, canon } }, read = { { data, canon } } }
import configparser, importlib.util, io, 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)
def parser():
p = configparser.ConfigParser(interpolation=None, strict=False)
p.optionxform = str
return p
def as_dict(p):
return {s: dict(p.items(s, raw=True)) for s in p.sections()}
MESSY = [
"[a]\nx=1\ny : two words \n; comment\n # indented comment\nz =\n",
"[s]\nkey = line one\n line two\n\tline three\nk2: v\n",
"# top comment\n[one]\na = 1\n[two]\nb = 2\n[one]\nc = 3\n",
"[dup]\na = 1\na = 2\n",
"[weird name with spaces]\n key with spaces = value with = sign \n",
"[s]\nurl = http://x:8080/p?a=b\npath: C:\\dir\n",
"[x]\r\nwin = yes\r\nmore = no\r\n",
"[\u00e9]\n\u4e2d = \u00fc\n",
"[a]\nk = v ; not a comment by default\n",
"[e]\nempty =\nalso:\n",
]
def generate(ctx):
rng = ctx.rng(17)
written = []
alph = "ab xyz09_-.\u00e9/=:;#"
for i in range(80):
p = parser()
for s in range(rng.randrange(1, 5)):
name = "sec%d %s" % (s, rng.choice(["", "x", "\u00e9"]))
p.add_section(name)
for k in range(rng.randrange(0, 6)):
key = "k%d%s" % (k, rng.choice(["", "_a", ".b"]))
val = "".join(rng.choice(alph) for _ in range(rng.randrange(0, 12))).strip()
if rng.random() < 0.15:
val = val + "\nsecond line" + rng.choice(["", "\nthird"])
p.set(name, key, val)
buf = io.StringIO()
p.write(buf)
data = buf.getvalue()
back = parser()
back.read_string(data)
written.append({"data": data.encode(), "canon": C.canon(as_dict(back))})
read = []
for m in MESSY:
p = parser()
p.read_string(m)
read.append({"data": m.encode(), "canon": C.canon(as_dict(p))})
ctx.emit("ini", {"written": written, "read": read})
+91
View File
@@ -0,0 +1,91 @@
# codecs/Json + data/json fixtures: the JSONTestSuite parsing corpus (nst/JSONTestSuite, pinned tarball through nix)
# with Python's json verdicts and canonical values, plus a random corpus written by Python's json.dumps in several
# styles (compact sorted, insertion order, indent 2, ensure_ascii) that the tests must parse and reproduce exactly.
# tests/gen/json_suite.luau { { name, expect = "y" | "n" | "i", data, canon? } }
# tests/gen/json_corpus.luau { { canon, compact, ordered, pretty, ascii } }
# tests/gen/json_bench.luau { text, compact } (~1 MB, indent 1; compact = sorted keys)
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)
SUITE_URL = "https://github.com/nst/JSONTestSuite/archive/1ef36fa01286573e846ac449e8683f8833c5b26a.tar.gz"
SUITE_SHA = "0zp4gbpfxac9hfzlgjmqg70w8dhql6rbrkh8dhi3rn5aan0qqv5k"
def rand_value(rng, depth=0):
v = _rand_value(rng, depth)
if isinstance(v, float) and v.is_integer():
return int(v) # Python writes 1.0, we write 1: keep integral numbers ints
return v
def _rand_value(rng, depth=0):
r = rng.random()
if depth > 4 or r < 0.45:
k = rng.randrange(9)
if k == 0:
return None
if k == 1:
return rng.random() < 0.5
if k == 2:
return rng.randrange(-10 ** 15, 10 ** 15)
if k == 3:
return rng.randrange(-1000, 1000)
if k == 4:
return round(rng.uniform(-1e6, 1e6), rng.randrange(1, 8))
if k == 5:
return rng.uniform(-1, 1) * 10 ** rng.randrange(-4, 14)
return rand_str(rng)
if r < 0.72:
return [rand_value(rng, depth + 1) for _ in range(rng.randrange(0, 7))]
d = {}
for _ in range(rng.randrange(0, 7)):
d[rand_str(rng)] = rand_value(rng, depth + 1)
return d
ALPH = "abcxyz ABC_019\"\\/\n\t\r\b\f\x01\x1f\x7féü中文\U0001f600
"
def rand_str(rng):
return "".join(rng.choice(ALPH) for _ in range(rng.randrange(0, 12)))
def generate(ctx):
root = C.fetch(SUITE_URL, SUITE_SHA)
d = os.path.join(root, "test_parsing")
cases = []
for name in sorted(os.listdir(d)):
if not name.endswith(".json"):
continue
data = open(os.path.join(d, name), "rb").read()
c = {"name": name, "expect": name[0], "data": data}
try:
v = json.loads(data.decode("utf-8", "surrogatepass"))
c["canon"] = C.canon(v)
except Exception:
pass
cases.append(c)
ctx.emit("json_suite", cases)
rng = ctx.rng(7)
corpus = []
for _ in range(300):
v = rand_value(rng)
corpus.append({
"canon": C.canon(v),
"compact": json.dumps(v, separators=(",", ":"), sort_keys=True, ensure_ascii=False),
"ordered": json.dumps(v, separators=(",", ":"), ensure_ascii=False),
"pretty": json.dumps(v, indent=2, sort_keys=True, ensure_ascii=False),
"ascii": json.dumps(v, separators=(",", ":"), sort_keys=True),
})
ctx.emit("json_corpus", corpus)
big = [rand_value(rng) for _ in range(3000)]
text = json.dumps(big, ensure_ascii=False, indent=1)
while len(text) < 1_000_000:
big = big + big
text = json.dumps(big, ensure_ascii=False, indent=1)
ctx.emit("json_bench", {"text": text, "compact": json.dumps(big, separators=(",", ":"), sort_keys=True, ensure_ascii=False)})
+94
View File
@@ -0,0 +1,94 @@
# data/msgpack fixtures: random values packed by Python's msgpack (through nix): every integer width, floats,
# str / bin of every length class, nested arrays / maps (int and str keys), nil / bools, timestamps (all three
# widths) and other ext types; with the canonical form of msgpack's own unpacking.
# tests/gen/msgpack.luau { safe = { { data, canon } }, wide = { { data, canon, canonStr } } }
# safe: no integers past 2^53, no integral floats: our decode + encode must give the same bytes
# wide: 64-bit integers too (canon = as doubles, canonStr = exact text via bigInts = "string")
import importlib.util, os, pickle
_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)
BODY = r'''
import msgpack, pickle, random, sys, datetime
rng = random.Random(5)
def rint(wide):
k = rng.randrange(8)
lim = [2**5, 2**7, 2**8, 2**15, 2**16, 2**31, 2**32, 2**53 - 1][k]
if wide and rng.random() < 0.4:
lim = rng.choice([2**63 - 1, 2**64 - 1])
v = rng.randrange(0, lim + 1)
if lim == 2**63 - 1 and rng.random() < 0.5:
v = -v - 1
return v
v = rng.randrange(-lim, lim + 1)
return v
def rstr():
n = rng.choice([0, 1, 5, 31, 32, 200, 255, 256, 300])
alph = "abé中\U0001f600 \n\x00"
return "".join(rng.choice(alph) for _ in range(n))[:n]
def rval(d, wide):
r = rng.random()
if d > 3 or r < 0.5:
k = rng.randrange(9)
if k == 0: return None
if k == 1: return rng.random() < 0.5
if k in (2, 3): return rint(wide)
if k == 4:
f = rng.uniform(-1e6, 1e6) * 10 ** rng.randrange(-5, 5)
return f if not f.is_integer() else f + 0.5
if k == 5: return rstr()
if k == 6: return rng.randbytes(rng.choice([0, 3, 255, 256]))
if k == 7:
sec = rng.choice([rng.randrange(0, 2**32), rng.randrange(0, 2**34), rng.randrange(-2**35, 2**37)])
us = rng.choice([0, rng.randrange(1000000)])
return msgpack.Timestamp(sec, us * 1000)
return msgpack.ExtType(rng.randrange(0, 128), rng.randbytes(rng.choice([1, 2, 4, 8, 16, 3, 300])))
if r < 0.75:
return [rval(d + 1, wide) for _ in range(rng.choice([0, 1, 3, 15, 16, 20] if d < 2 else [0, 1, 3]))]
m = {}
for _ in range(rng.choice([0, 1, 3, 15, 16, 17] if d < 2 else [0, 1, 3])):
key = rint(False) if rng.random() < 0.3 else "".join(rng.choice("abc\u00e9") for _ in range(rng.randrange(6)))
m[key] = rval(d + 1, wide)
return m
def conv(v):
if isinstance(v, msgpack.Timestamp):
return v.to_datetime()
if isinstance(v, msgpack.ExtType):
return ["ext", v.code, v.data]
if isinstance(v, list):
return [conv(x) for x in v]
if isinstance(v, dict):
return {k: conv(x) for k, x in v.items()}
return v
def cstr(v):
if isinstance(v, int) and not isinstance(v, bool) and abs(v) >= 2**53:
return str(v)
if isinstance(v, list):
return [cstr(x) for x in v]
if isinstance(v, dict):
return {k: cstr(x) for k, x in v.items()}
return v
out = {"safe": [], "wide": []}
# the 32-bit length forms, once each
for v in ["x" * 70000, b"y" * 70000, list(range(70000)), {i: i for i in range(70000)}]:
data = msgpack.packb(v, use_bin_type=True)
out["safe"].append({"data": data, "canon": canon(msgpack.unpackb(data, strict_map_key=False))})
for i in range(250):
v = rval(0, False)
data = msgpack.packb(v, use_bin_type=True)
back = msgpack.unpackb(data, raw=False, strict_map_key=False)
out["safe"].append({"data": data, "canon": canon(conv(back))})
for i in range(150):
v = rval(0, True)
data = msgpack.packb(v, use_bin_type=True)
back = conv(msgpack.unpackb(data, raw=False, strict_map_key=False))
out["wide"].append({"data": data, "canon": canon(back), "canonStr": canon(cstr(back))})
sys.stdout.buffer.write(pickle.dumps(out, protocol=4))
'''
def generate(ctx):
out = pickle.loads(C.python(ctx, ["msgpack"], BODY))
ctx.emit("msgpack", out)
+83
View File
@@ -0,0 +1,83 @@
# data/plist fixtures: random values written by Python's plistlib as XML (insertion order) and as binary, with the
# canonical form of plistlib's own reading (aware UTC datetimes; UIDs as ["uid", n]).
# tests/gen/plist.luau { { xml, binary, canon } } (our XML writer must reproduce xml byte for byte)
# + wide = { { binary, canon } } (UIDs, 64-bit integers: binary only)
import datetime, importlib.util, os, plistlib
_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)
def rval(rng, d, wide):
r = rng.random()
if d > 3 or r < 0.5:
k = rng.randrange(8)
if k == 0:
return rng.random() < 0.5
if k == 1:
return rng.randrange(-2 ** 31, 2 ** 31)
if k == 2:
return rng.choice([rng.randrange(-2 ** 63, 2 ** 63), rng.randrange(0, 2 ** 64)]) if wide else rng.randrange(-2 ** 53, 2 ** 53)
if k == 3:
f = rng.uniform(-1e6, 1e6) * 10 ** rng.randrange(-5, 5)
return f if not f.is_integer() else f + 0.5
if k == 4:
return "".join(rng.choice("ab <>&\"'é中\U0001f600\n\t") for _ in range(rng.randrange(0, 12)))
if k == 5:
return rng.randbytes(rng.choice([0, 1, 2, 3, 40, 57, 58, 200]))
if k == 6:
return datetime.datetime.fromtimestamp(rng.randrange(-2 ** 31, 2 ** 33), datetime.timezone.utc)
return plistlib.UID(rng.randrange(0, 2 ** 32)) if wide else "x"
if r < 0.75:
return [rval(rng, d + 1, wide) for _ in range(rng.randrange(0, 6))]
return {"".join(rng.choice("abcé <&") for _ in range(rng.randrange(0, 6))): rval(rng, d + 1, wide) for _ in range(rng.randrange(0, 6))}
def conv(v):
if isinstance(v, plistlib.UID):
return ["uid", v.data]
if isinstance(v, list):
return [conv(x) for x in v]
if isinstance(v, dict):
return {k: conv(x) for k, x in v.items()}
return v
def generate(ctx):
rng = ctx.rng(21)
cases = []
for i in range(200):
v = rval(rng, 0, False)
if not isinstance(v, (list, dict)) and rng.random() < 0.5:
v = {"root": v}
xml = plistlib.dumps(v, fmt=plistlib.FMT_XML, sort_keys=False, aware_datetime=True)
binary = plistlib.dumps(v, fmt=plistlib.FMT_BINARY, sort_keys=False, aware_datetime=True)
back = plistlib.loads(xml, aware_datetime=True)
assert C.canon(conv(plistlib.loads(binary, aware_datetime=True))) == C.canon(conv(back))
cases.append({"xml": xml, "binary": binary, "canon": C.canon(conv(back))})
wide = []
for i in range(80):
v = [rval(rng, 1, True) for _ in range(4)]
binary = plistlib.dumps(v, fmt=plistlib.FMT_BINARY, aware_datetime=True)
wide.append({"binary": binary, "canon": C.canon(conv(plistlib.loads(binary, aware_datetime=True)))})
# a hand-written XML plist with whitespace, comments, hex integers, odd reals, a bare value root
extra = b"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<!-- comment -->
<dict>
<key>hex</key> <integer>0x1F</integer>
<key>neg</key> <integer>-5</integer>
<key>real</key> <real> 2.5e3 </real>
<key>data</key> <data>
AAEC
AwQ=
</data>
<key>empty</key> <string/>
<key>date</key> <date>2001-01-01T00:00:00Z</date>
</dict>
</plist>
"""
ctx.emit("plist", {"cases": cases, "wide": wide, "extra": extra,
"extraCanon": C.canon(plistlib.loads(extra, aware_datetime=True))})
+120
View File
@@ -0,0 +1,120 @@
# data/toml fixtures: the toml-test suite (toml-lang/toml-test v2.2.0, pinned tarball through nix; the files listed
# in tests/files-toml-1.0.0) with each valid case's expected value as the canonical text tests/data/Canon.luau
# computes, plus a random corpus written by tomli-w and read back by Python's tomllib.
# tests/gen/toml_suite.luau { { name, valid, data, canon? } }
# tests/gen/toml_corpus.luau { { data, canon } }
import datetime, importlib.util, json, os, re, tomllib
_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/toml-lang/toml-test/archive/refs/tags/v2.2.0.tar.gz"
SUITE_SHA = "1nkgbfcdjaccqgf5pkjs49jh0z1pz4lval94qfxq4j6ikvmlg80s"
DATES = ("datetime", "datetime-local", "date-local", "time-local")
def norm_date(v):
"""a toml-test datetime string the way Types.Date prints it"""
m = re.match(r"^(\d{4}-\d{2}-\d{2})?(?:[Tt ]?(\d{2}:\d{2}:\d{2})(?:\.(\d+))?)?([Zz]|[+-]\d{2}:\d{2})?$", v)
date, time, frac, off = m.groups()
out = date or ""
if time:
out += ("T" if date else "") + time
f = (frac or "")[:9].rstrip("0")
if f:
out += "." + f
if off:
out += "Z" if off in ("Z", "z", "+00:00", "-00:00") else off
return out
def tagged(v, out):
if isinstance(v, dict) and set(v) == {"type", "value"} and isinstance(v["type"], str) and isinstance(v["value"], str):
t, x = v["type"], v["value"]
if t == "string":
b = x.encode("utf-8", "surrogatepass")
out += b"s%d:" % len(b) + b
elif t == "integer":
out += C.num(int(x))
elif t == "float":
out += C.num(float(x))
elif t == "bool":
out += b"t" if x == "true" else b"f"
elif t in DATES:
out += b"d" + norm_date(x).encode()
else:
raise ValueError(t)
elif isinstance(v, list):
out += b"["
for x in v:
tagged(x, out)
out += b","
out += b"]"
else:
items = []
for k, x in v.items():
kb = k.encode("utf-8", "surrogatepass")
items.append((b"s%d:" % len(kb) + kb, x))
items.sort(key=lambda p: p[0])
out += b"{"
for kb, x in items:
out += kb + b"="
tagged(x, out)
out += b","
out += b"}"
GEN = r'''
import datetime, json, random, sys, tomli_w
rng = random.Random(5)
KEYS = ["a", "b-c", "d_e", "1", "with space", "dot.ted", "é", "quote\"", "", "tab\t"]
def scalar():
k = rng.randrange(8)
if k == 0: return rng.randrange(-2**63, 2**63)
if k == 1: return rng.randrange(-1000, 1000)
if k == 2: return rng.choice([0.5, -1.25e-7, 3.14159, 1e300, float("inf"), -float("inf"), 6.02e23])
if k == 3: return rng.random() < 0.5
if k == 4: return "".join(rng.choice("ab \"\\\n\té中\U0001f600\x01\x7f'#=[]") for _ in range(rng.randrange(12)))
if k == 5:
tz = rng.choice([None, datetime.timezone.utc, datetime.timezone(datetime.timedelta(hours=-7, minutes=-30))])
return datetime.datetime(rng.randrange(1, 9999), rng.randrange(1, 13), rng.randrange(1, 29), rng.randrange(24), rng.randrange(60), rng.randrange(60), rng.choice([0, 999999, 500000]), tzinfo=tz)
if k == 6: return datetime.date(rng.randrange(1, 9999), rng.randrange(1, 13), rng.randrange(1, 29))
return datetime.time(rng.randrange(24), rng.randrange(60), rng.randrange(60), rng.choice([0, 123000]))
def table(depth):
d = {}
for _ in range(rng.randrange(1, 6)):
r = rng.random()
k = rng.choice(KEYS)
if depth < 3 and r < 0.2: d[k] = table(depth + 1)
elif depth < 3 and r < 0.3: d[k] = [table(depth + 1) for _ in range(rng.randrange(1, 3))]
elif r < 0.45: d[k] = [scalar() for _ in range(rng.randrange(0, 4))]
elif r < 0.5: d[k] = [[scalar()], [scalar(), scalar()], {"x": scalar()}]
else: d[k] = scalar()
return d
out = []
for _ in range(200):
out.append(tomli_w.dumps(table(0), multiline_strings=rng.random() < 0.3))
json.dump(out, sys.stdout)
'''
def generate(ctx):
root = os.path.join(C.fetch(SUITE_URL, SUITE_SHA), "tests")
names = [l.strip() for l in open(os.path.join(root, "files-toml-1.0.0")) if l.strip().endswith(".toml")]
cases = []
for name in names:
data = open(os.path.join(root, name), "rb").read()
c = {"name": name, "valid": name.startswith("valid/"), "data": data}
if c["valid"]:
out = bytearray()
tagged(json.load(open(os.path.join(root, name[:-5] + ".json"), encoding="utf-8")), out)
c["canon"] = bytes(out)
cases.append(c)
ctx.emit("toml_suite", cases)
texts = json.loads(ctx.python(["tomli-w"], GEN))
corpus = []
for t in texts:
corpus.append({"data": t.encode("utf-8"), "canon": C.canon(tomllib.loads(t))})
ctx.emit("toml_corpus", corpus)
+174
View File
@@ -0,0 +1,174 @@
# codecs/Xml + data/xml fixtures: random documents (namespaces, attributes with every escape, CDATA, comments, PIs,
# entities from an internal DOCTYPE, mixed content) written by hand, then parsed by Python's xml.etree (expat) for the
# reference tree; the same documents re-encoded as UTF-16 and Latin-1; and well-formedness cases (hand-written plus
# random mutations) with expat's verdict.
# tests/gen/xml_docs.luau { { data, canon } } canon: see canon() below (the test computes the same)
# tests/gen/xml_wf.luau { { data, ok } } ok: expat accepts it
# tests/gen/xml_bench.luau { text } (~1 MB)
import xml.etree.ElementTree as ET
from xml.parsers import expat
NS = [("", None), ("a", "urn:a"), ("b", "http://example.com/b")]
TAGS = ["item", "x", "Data", "set-1", "q.r", "_u", "élément", "名"]
TXT = "ab <>&\"' é中\U0001f600\t\n ]]"
def s(x):
x = x or ""
b = x.encode("utf-8", "surrogatepass")
return b"%d:" % len(b) + b
def canon(e):
out = b"(" + s(e.tag)
for k in sorted(e.attrib):
out += b"|" + s(k) + b"=" + s(e.attrib[k])
out += b"|t" + s(e.text)
for c in e:
out += canon(c)
return out + b")t" + s(e.tail)
def esc_text(t):
return t.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def esc_attr(t, q):
t = t.replace("&", "&amp;").replace("<", "&lt;")
return t.replace(q, "&quot;" if q == '"' else "&apos;")
def rand_text(rng):
return "".join(rng.choice(TXT) for _ in range(rng.randrange(0, 10)))
def gen_elem(rng, depth, declared):
prefix = rng.choice([p for p in declared])
local = rng.choice(TAGS)
name = (prefix + ":" + local) if prefix else local
attrs = []
newdecl = set(declared)
if depth > 0 and rng.random() < 0.15:
p, uri = rng.choice(NS[1:])
attrs.append(("xmlns:" + p, uri))
newdecl.add(p)
if rng.random() < 0.1:
attrs.append(("xmlns", "urn:default%d" % rng.randrange(3)))
used = set(a for a, _ in attrs)
for _ in range(rng.randrange(0, 4)):
an = rng.choice(["id", "k", "v-1", "é", "x.y"])
if rng.random() < 0.2 and len(newdecl) > 1:
an = rng.choice([p for p in newdecl if p]) + ":" + an
if an in used:
continue
used.add(an)
attrs.append((an, rand_text(rng)))
parts = ["<" + name]
for k, v in attrs:
q = rng.choice("\"'")
parts.append(" %s=%s%s%s" % (k, q, esc_attr(v, q), q))
if depth > 4 or rng.random() < 0.15:
parts.append(rng.choice(["/>", " />"]))
return "".join(parts)
parts.append(">")
for _ in range(rng.randrange(0, 5)):
r = rng.random()
if r < 0.35:
parts.append(esc_text(rand_text(rng)))
elif r < 0.45:
parts.append("<![CDATA[" + rand_text(rng).replace("]", "] ") + "<&>]]>")
elif r < 0.5:
parts.append("<!-- c " + rand_text(rng).replace("-", "=") + " -->")
elif r < 0.53:
parts.append("<?pi data " + rand_text(rng).replace("?", "") + "?>")
elif r < 0.58:
parts.append(rng.choice(["&ent;", "&#233;", "&#x1F600;", "&amp;", "&lt;", "&#10;"]))
else:
parts.append(gen_elem(rng, depth + 1, newdecl))
parts.append("</%s>" % name)
return "".join(parts)
def gen_doc(rng):
head = ""
if rng.random() < 0.5:
head += '<?xml version="1.0" encoding="UTF-8"?>\n'
head += '<!DOCTYPE root [\n <!ENTITY ent "entity &#38;#38; text &lt;">\n <!-- a comment -->\n]>\n'
if rng.random() < 0.3:
head += "<!-- prolog comment -->\n"
declared = {""}
body = gen_elem(rng, 0, declared)
# the root must declare every prefix it may use: declare all at the root
root_decl = " ".join('xmlns:%s="%s"' % (p, u) for p, u in NS[1:])
i = body.index(">") if not body.startswith("<") else 0
name_end = 1
while body[name_end] not in " />":
name_end += 1
body = body[:name_end] + " " + root_decl + body[name_end:]
return head + body + ("\n" if rng.random() < 0.5 else "")
def expat_ok(data):
p = expat.ParserCreate()
try:
p.Parse(data, True)
return True
except Exception: # ExpatError, or LookupError for an unknown encoding name
return False
WF = [
"<a/>", "<a></a>", "<a><b/></a>", "<a>x</b>", "<a>", "</a>", "<a/><b/>", "text<a/>", "<a/>text", "<a b='1' b='2'/>",
"<a b=1/>", "<a b='<'/>", "<a>&undefined;</a>", "<a>&#0;</a>", "<a>&#x110000;</a>", "<a>&#xD800;</a>", "<a>& </a>",
"<a><!-- x -- y --></a>", "<a><!-- x ---></a>", "<a>]]></a>", "<1a/>", "<a 1b='x'/>", "<a b='x'c='y'/>",
"<?xml version='1.0'?><a/>", " <?xml version='1.0'?><a/>", "<a/><?xml version='1.0'?>", "<a><![CDATA[x]]></a>",
"<![CDATA[x]]><a/>", "<a><![CDATA[x</a>", "<a>\x01</a>", "<a b='\x01'/>", "<a><?pi x?></a>", "<a><?pi?></a>",
"<!DOCTYPE a><a/>", "<a/><!DOCTYPE a>", "<!DOCTYPE a [<!ENTITY e 'v'>]><a>&e;</a>", "<a b='&lt;&#65;'/>",
"<a:b xmlns:a='u'/>", "<a\n b\n =\n 'c'\n/>", "<a></a >", "<a></ a>", "< a/>", "<a/ >", "<a b='x' / >",
"<a>é\U0001f600</a>", "<a>&amp;&lt;&gt;&quot;&apos;</a>", "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><a/>",
"<!-- c --><a/><!-- d -->", "<a><!----></a>", "", " ", "<a>x</a>trailing", "<a>x</a><!-- ok --> ",
]
def generate(ctx):
rng = ctx.rng(11)
docs = []
for k in range(250):
text = gen_doc(rng)
root = ET.fromstring(text.encode("utf-8"))
docs.append({"data": text.encode("utf-8"), "canon": canon(root)})
# other encodings: UTF-16 (BOM, both byte orders) and Latin-1
for k in range(10):
text = gen_doc(rng)
body = text.split("?>", 1)[1] if text.startswith("<?xml") else text
c = canon(ET.fromstring(text.encode("utf-8")))
docs.append({"data": ('<?xml version="1.0" encoding="UTF-16"?>' + body).encode("utf-16"), "canon": c})
docs.append({"data": b"\xfe\xff" + ('<?xml version="1.0" encoding="UTF-16"?>' + body).encode("utf-16-be"), "canon": c})
for k in range(10):
text = "<?xml version='1.0' encoding='ISO-8859-1'?><r a='éÿ'>café ½ &#x4e2d;</r>"
data = text.encode("latin-1")
docs.append({"data": data, "canon": canon(ET.fromstring(data))})
ctx.emit("xml_docs", docs)
wf = [{"data": d.encode("utf-8"), "ok": expat_ok(d.encode("utf-8"))} for d in WF]
# mutations of valid documents: delete / duplicate / replace one markup character
for k in range(400):
text = gen_doc(rng).encode("utf-8")
b = bytearray(text)
for _ in range(rng.randrange(1, 3)):
pos = rng.randrange(len(b))
op = rng.randrange(3)
ch = rng.choice(b"<>/&;='\"![]-? ")
if op == 0:
del b[pos]
elif op == 1:
b.insert(pos, ch)
else:
b[pos] = ch
wf.append({"data": bytes(b), "ok": expat_ok(bytes(b))})
ctx.emit("xml_wf", wf)
parts = []
while sum(map(len, parts)) < 1_000_000:
parts.append(gen_elem(rng, 1, {""}))
ctx.emit("xml_bench", {"text": "<root>" + "\n".join(p for p in parts if "&ent;" not in p) + "</root>"})
+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})