Types (backward compatible additions in the Data section): Types.object / isObject / set / keys (ordered objects and empty-object marking, shared by every data format), Types.Date (RFC 3339 typed dates for TOML / plist / CBOR / msgpack: new / is / valid / parse / toUnix / fromUnix), XmlNode gains optional text / target / ns fields. tools/bench.sh: also generates the json fixtures.
100 lines
3.2 KiB
Python
100 lines
3.2 KiB
Python
# 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))
|