cli: add deterministic source formatter
This commit is contained in:
1 parent
d901d5227b
commit
462ddd2c5c
14 files changed
+787
-13
No files matched your search
@@ -0,0 +1,11 @@
|
||||
// Header stays before the module.
|
||||
module fmt.layout
|
||||
import std.option; // explicit import
|
||||
// Generic declaration.
|
||||
struct Pair<T:Copy>{first:T,second:T,}
|
||||
enum Choice<T:Copy>{some(T),none}
|
||||
fn identity(x:u64)->u64 effects[]{x}
|
||||
fn apply<T:Copy,F:fn(T)->T effects []>(x:T)->T effects[]{return F(x);}
|
||||
fn main()->u64 effects[]{let pair=Pair::<u64>{first:40u64,second:2u64}; // keep trailing
|
||||
let bytes=b"//not a comment\x00";let x=(pair.first+pair.second)*1u64;
|
||||
if x<43u64{match Choice::<u64>::some(x){Choice::<u64>::some(v)=>{return apply::<u64,fn identity>(v);}Choice::<u64>::none=>{return 0u64;}}}else{return x>>1u64;}} // final
|
||||
@@ -0,0 +1,40 @@
|
||||
// Header stays before the module.
|
||||
module fmt.layout
|
||||
import std.option; // explicit import
|
||||
|
||||
// Generic declaration.
|
||||
struct Pair<T: Copy> {
|
||||
first: T,
|
||||
second: T,
|
||||
}
|
||||
|
||||
enum Choice<T: Copy> {
|
||||
some(T),
|
||||
none
|
||||
}
|
||||
|
||||
fn identity(x: u64) -> u64 effects [] {
|
||||
x
|
||||
}
|
||||
|
||||
fn apply<T: Copy, F: fn(T) -> T effects []>(x: T) -> T effects [] {
|
||||
return F(x);
|
||||
}
|
||||
|
||||
fn main() -> u64 effects [] {
|
||||
let pair = Pair::<u64> { first: 40u64, second: 2u64 }; // keep trailing
|
||||
let bytes = b"//not a comment\x00";
|
||||
let x = (pair.first + pair.second) * 1u64;
|
||||
if x < 43u64 {
|
||||
match Choice::<u64>::some(x) {
|
||||
Choice::<u64>::some(v) => {
|
||||
return apply::<u64, fn identity>(v);
|
||||
}
|
||||
Choice::<u64>::none => {
|
||||
return 0u64;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return x >> 1u64;
|
||||
}
|
||||
} // final
|
||||
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env python3
|
||||
"""P6-8 formatter: public corpus, token/AST fidelity, canonical AIR and CLI I/O.
|
||||
|
||||
Read only the source conformance corpus, std and examples. Never format originals
|
||||
in place; --write tests use temporary files. Runs use fuel, without timeouts.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
AJI = REPO / "zig-out/bin/aji"
|
||||
checks = 0
|
||||
|
||||
|
||||
def cli(*args, code=0):
|
||||
global checks
|
||||
result = subprocess.run([str(AJI), *map(str, args)], capture_output=True)
|
||||
assert result.returncode == code, (args, result.returncode, result.stdout, result.stderr)
|
||||
checks += 1
|
||||
return result.stdout
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="aji-format-") as directory:
|
||||
root = Path(directory)
|
||||
fixture = REPO / "tests/format/layout.aji"
|
||||
before = fixture.read_bytes()
|
||||
golden = (REPO / "tests/format/layout.expected").read_bytes()
|
||||
assert cli("fmt", fixture) == golden
|
||||
assert fixture.read_bytes() == before
|
||||
record = json.loads(cli("fmt", "--check", fixture, code=1))
|
||||
assert record == {"file": str(fixture), "status": "needs_format", "changed": True}
|
||||
formatted = root / "formatted.aji"
|
||||
formatted.write_bytes(golden)
|
||||
assert cli("fmt", formatted) == golden
|
||||
assert json.loads(cli("fmt", "--check", formatted)) == {
|
||||
"file": str(formatted), "status": "formatted", "changed": False}
|
||||
assert cli("lower", fixture) == cli("lower", formatted)
|
||||
original_run = json.loads(cli("run", "--fuel", "100000", fixture))
|
||||
assert original_run["value"] == 42
|
||||
assert json.loads(cli("run", "--fuel", "100000", formatted)) == original_run
|
||||
|
||||
# Explicit writes are atomic, preserve mode despite umask, and do not touch
|
||||
# an unchanged file (including its inode and modification time).
|
||||
target = root / 'quoted "name.aji'
|
||||
target.write_bytes(before)
|
||||
target.chmod(0o664)
|
||||
initial = target.stat()
|
||||
assert json.loads(cli("fmt", "--write", target)) == {
|
||||
"file": str(target), "status": "formatted", "changed": True}
|
||||
assert target.read_bytes() == golden and target.stat().st_mode == initial.st_mode
|
||||
os.utime(target, ns=(1234567890000000000, 1234567890000000000))
|
||||
unchanged = target.stat()
|
||||
assert json.loads(cli("fmt", "--write", target))["changed"] is False
|
||||
assert (target.stat().st_ino, target.stat().st_mtime_ns) == (unchanged.st_ino, unchanged.st_mtime_ns)
|
||||
link = root / "link.aji"
|
||||
link.symlink_to(target)
|
||||
cli("fmt", "--write", link, code=2)
|
||||
assert link.is_symlink() and target.read_bytes() == golden
|
||||
assert cli("fmt", link) == golden
|
||||
hard = root / "hard.aji"
|
||||
twin = root / "twin.aji"
|
||||
hard.write_bytes(before)
|
||||
os.link(hard, twin)
|
||||
cli("fmt", "--write", hard)
|
||||
assert hard.read_bytes() == golden and twin.read_bytes() == before
|
||||
pipe = root / "pipe.aji"
|
||||
os.mkfifo(pipe)
|
||||
# Reject before reading: no writer or wall-clock timeout is needed.
|
||||
cli("fmt", "--write", pipe, code=2)
|
||||
|
||||
broken = root / "broken.aji"
|
||||
broken.write_bytes(b"module broken\nfn f()->u64 effects [] {return 1}\n")
|
||||
for flags in ((), ("--check",), ("--write",)):
|
||||
error = json.loads(cli("fmt", *flags, broken, code=1))
|
||||
assert error["code"] == "E7001" and error["file"] == str(broken)
|
||||
assert error == json.loads(cli("lower", broken, code=1))
|
||||
assert broken.read_bytes().endswith(b"{return 1}\n")
|
||||
for args in ((), ("--check",), ("--unknown", fixture),
|
||||
("--check", "--write", fixture), ("--manifest", fixture),
|
||||
(root / "missing.aji",), (fixture, fixture), ("not.air",), (root,)):
|
||||
assert cli("fmt", *args, code=2) == b""
|
||||
|
||||
library = root / "lib.aji"
|
||||
library.write_bytes(b"module lib import absent; fn f(p: Unknown)->Unknown effects [] {p}")
|
||||
text = cli("fmt", library)
|
||||
assert b"import absent;" in text and b"p: Unknown" in text
|
||||
|
||||
# Scope delimiters, inline/standalone comments, UTF-8 comments, CRLF and
|
||||
# missing final newline must be stable, even in semantically invalid code.
|
||||
cases = [
|
||||
b"module empty",
|
||||
b"// heading\r\r\nmodule m // ending\r\r",
|
||||
b"// header\r\nmodule m // module\r\nfn f()->void effects [] { // body\r\n// end\r\n} // final",
|
||||
"module m fn f()->u64 effects [] {let x=\n// отдельный комментарий\n42u64;return x;}".encode(),
|
||||
b"module m struct S {x:u64} fn f()->S effects [] {S {// inner\nx:42u64 // trailing\n}}",
|
||||
b"module m fn f()->void effects [] {let n=1u64; if true{} // after empty\nelse{} // after else\n}",
|
||||
b"module m fn f(p:own<own<u64> >)->u64 effects [] {let n=(1u64+2u64)*3u64;return n>>1u64;}",
|
||||
b"module m fn f()->void effects [] {select { recv(rx){ok(x)=>{},closed=>{},cancelled=>{},} cancelled=>{},}}",
|
||||
b"module m fn f()->void effects [] {let p=P{a:1u64, // lit \t\nb:2u64};\n\n\nlet n=not (true and false);}",
|
||||
]
|
||||
for i, source in enumerate(cases):
|
||||
sample = root / f"case{i}.aji"
|
||||
sample.write_bytes(source)
|
||||
text = cli("fmt", sample)
|
||||
sample.write_bytes(text)
|
||||
assert cli("fmt", sample) == text, (i, text)
|
||||
cli("fmt", "--check", sample)
|
||||
if b"// lit" in source:
|
||||
assert b"// lit \t\n b: 2u64" in text
|
||||
assert b"not (true and false)" in text
|
||||
|
||||
parsed = syntax_errors = lowered = 0
|
||||
files = sorted({p for directory in (REPO / "tests/conformance/source", REPO / "std", REPO / "examples")
|
||||
for p in directory.rglob("*.aji")})
|
||||
for i, path in enumerate(files, 1):
|
||||
original = path.read_bytes()
|
||||
result = subprocess.run([str(AJI), "fmt", str(path)], capture_output=True)
|
||||
checks += 1
|
||||
if result.returncode == 1:
|
||||
assert json.loads(result.stdout)["code"] == "E7001", (path, result.stdout, result.stderr)
|
||||
syntax_errors += 1
|
||||
else:
|
||||
assert result.returncode == 0, (path, result.returncode, result.stdout, result.stderr)
|
||||
formatted.write_bytes(result.stdout)
|
||||
assert cli("fmt", formatted) == result.stdout, path
|
||||
parsed += 1
|
||||
# CLI packages require explicit mappings; for ordinary files,
|
||||
# accepted lowering must remain byte-identical after formatting.
|
||||
lower = subprocess.run([str(AJI), "lower", str(path)], capture_output=True)
|
||||
checks += 1
|
||||
if lower.returncode == 0:
|
||||
assert cli("lower", formatted) == lower.stdout, path
|
||||
lowered += 1
|
||||
else:
|
||||
assert lower.returncode in (1, 3), (path, lower.returncode, lower.stderr)
|
||||
assert path.read_bytes() == original, path
|
||||
if i % 100 == 0:
|
||||
print(f"formatter corpus: {i}/{len(files)} files", flush=True)
|
||||
print(f"source formatter passed ({checks} checks; {parsed} parsed, "
|
||||
f"{syntax_errors} syntax errors, {lowered} identical AIR outputs)")
|
||||
Reference in new issue
Block a user