# 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)