#!/usr/bin/env python3 """Write the prelude's impls for `()` and tuples (ADR 0018 Rev. 1). Eq, Ord, Show, Debug, Hash and Default, for `()` and tuples of 2 to MAX_ARITY elements, each element constrained by the same trait. They are generated because they differ only in arity; edit this script, not the block in std/prelude.lse. scripts/gen-tuple-impls.py rewrite the block scripts/gen-tuple-impls.py --check fail if the block is out of date """ import pathlib import subprocess import sys import tempfile MAX_ARITY = 12 ROOT = pathlib.Path(__file__).resolve().parent.parent PRELUDE = ROOT / "std" / "prelude.lse" BEGIN = "// --- `()` and tuples: generated by scripts/gen-tuple-impls.py, do not edit ---" END = "// --- end of the generated tuple impls ---" def format_louise(text): """The canonical form: the file through `louise fmt`.""" louise = ROOT / "target" / "debug" / "louise" with tempfile.TemporaryDirectory() as tmp: f = pathlib.Path(tmp) / "prelude.lse" f.write_text(text) if louise.exists(): subprocess.run([louise, "fmt", str(f)], check=True) else: subprocess.run( ["cargo", "run", "-q", "-p", "louise", "--", "fmt", str(f)], cwd=ROOT, check=True, ) return f.read_text() def impls(arity): vars_ = [chr(ord("a") + i) for i in range(arity)] ty = "(" + ", ".join(vars_) + ")" fields = range(arity) def head(trait): where = ", ".join(f"{trait}<{v}>" for v in vars_) return f"impl {trait}<{ty}> where {where} {{" def joined(method): parts = ' <> ", " <> '.join(f"{method} x.{i}" for i in fields) return f'"(" <> {parts} <> ")"' hash_ = "hash_combine 0 (hash x.0)" for i in range(1, arity): hash_ = f"hash_combine ({hash_}) (hash x.{i})" eq = " && ".join(f"x.{i} == y.{i}" for i in fields) compare = " <> ".join(f"compare x.{i} y.{i}" for i in fields) default = "(" + ", ".join("default ()" for _ in fields) + ")" # `louise fmt` canonical form: function bodies always break. def method(name, body): return f" fn {name} {{\n {body}\n }}" return [ f"{head('Eq')}\n{method('eq :: x y', eq)}\n}}", f"{head('Ord')}\n{method('compare :: x y', compare)}\n}}", f"{head('Show')}\n{method('show :: x', joined('show'))}\n}}", f"{head('Debug')}\n{method('debug :: x', joined('debug'))}\n}}", f"{head('Hash')}\n{method('hash :: x', hash_)}\n}}", f"{head('Default')}\n{method('default ::', default)}\n}}", ] def block(): unit = [ "impl Eq<()> {\n fn eq :: _ _ {\n True\n }\n}", "impl Ord<()> {\n fn compare :: _ _ {\n Eq\n }\n}", 'impl Show<()> {\n fn show :: _ {\n "()"\n }\n}', 'impl Debug<()> {\n fn debug :: _ {\n "()"\n }\n}', "impl Hash<()> {\n fn hash :: _ {\n 0\n }\n}", "impl Default<()> {\n fn default :: {\n ()\n }\n}", ] doc = ( "// Tuples compare element by element, in order; they show as `(1, a)`\n" "// and debug as `(1, \"a\")`. A tuple's hash folds its elements' with\n" "// `hash_combine`, as a derived impl does.\n" ) items = unit + [i for n in range(2, MAX_ARITY + 1) for i in impls(n)] return BEGIN + "\n" + doc + "\n" + "\n\n".join(items) + "\n" + END def main(): text = PRELUDE.read_text() new = block() if BEGIN in text: start = text.index(BEGIN) end = text.index(END) + len(END) updated = text[:start] + new + text[end:] else: updated = text.rstrip("\n") + "\n\n" + new + "\n" updated = format_louise(updated) if "--check" in sys.argv[1:]: if updated != text: sys.exit("std/prelude.lse: the tuple impls are out of date; run scripts/gen-tuple-impls.py") return PRELUDE.write_text(updated) if __name__ == "__main__": main()