Files
aji/tests/hosted/source_format.py
T

240 lines
12 KiB
Python

#!/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 re
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
def annotation_ranges(path, canonical):
annotated = cli("lower", "--annotate", path)
ordinary = []
for line in annotated.splitlines(keepends=True):
match = re.fullmatch(rb'\s*; (?:(.+):)?(\d+):(\d+)-(\d+):(\d+)\n', line)
if match:
start = tuple(map(int, match.group(2, 3)))
end = tuple(map(int, match.group(4, 5)))
assert min(*start, *end) >= 1 and start < end, (path, line)
else:
ordinary.append(line)
assert b''.join(ordinary) == canonical, path
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);}",
b"module m fn f(p:mut<u64>)->void effects [] {apply(ref // shared\n*p,mut *p);}",
]
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)
# The grammar permits inline dereferenced places without parentheses.
# Both spellings must lower identically; formatting preserves the new
# prefix boundary and comments without introducing grouping tokens.
bare = root / "deref.aji"
grouped = root / "deref-grouped.aji"
source = (REPO / "tests/conformance/source/deref_arguments/mutable.aji").read_bytes()
for gap in (b" ", b"\r\n", " // λ\n".encode()):
bare.write_bytes(source.replace(b"mut *p", b"mut" + gap + b"*p")
.replace(b"ref *p", b"ref" + gap + b"*p"))
grouped.write_bytes(source.replace(b"mut *p", b"mut (*p)").replace(b"ref *p", b"ref (*p)"))
air = cli("lower", bare)
assert cli("lower", grouped) == air
cli("check", bare)
result = json.loads(cli("run", "--fuel", "100000", bare))
assert result["value"] == 42
text = cli("fmt", bare)
bare.write_bytes(text)
assert cli("fmt", bare) == text
assert cli("lower", bare) == air
cli("fmt", "--check", bare)
text = cli("fmt", grouped)
assert b"ref (*p)" in text and b"mut (*p)" in text, text
grouped.write_bytes(text)
assert cli("fmt", grouped) == text
assert cli("lower", grouped) == air
cli("fmt", "--check", grouped)
if b"// lit" in source:
assert b"// lit \t\n b: 2u64" in text
assert b"not (true and false)" in text
# Grouped range bounds and unpack bindings have keyword spacing,
# while calls and the range operator stay compact. AIR stays identical.
sample = root / "keyword-spaces.aji"
sample.write_bytes(b"module spaces fn main()->u64 effects [] {let p=[1u64,2u64];"
b"let(a,b)=array.unpack(p);var n:u64=0;"
b"for i in(0usize)..(2usize){n=n+a+b;}n}")
original_air = cli("lower", sample)
text = cli("fmt", sample)
assert b"let (a, b) = array.unpack(p);" in text
assert b"for i in (0usize)..(2usize)" in text
sample.write_bytes(text)
assert cli("fmt", sample) == text
assert cli("lower", sample) == original_air
assert json.loads(cli("run", "--fuel", "10000", sample))["value"] == 6
# Q-040: statement boundaries are lexical, not dependent on the original
# line breaks. Formatting exposes them without inserting separators.
for construct in ("{*p=2u64;}", "if true {*p=2u64;} else {}",
"match 0u64 {0=>{*p=2u64;} _=>{}}"):
for gap in (" ", "\n", " // boundary\n"):
source = ("module boundary fn main()->u64 effects [] {"
"var x:u64=1u64; mut p=x;" + construct + gap +
"*p=*p+3u64;return *p;}").encode()
sample = root / "boundary.aji"
sample.write_bytes(source)
original_air = cli("lower", sample)
assert json.loads(cli("run", "--fuel", "10000", sample))["value"] == 5
text = cli("fmt", sample)
assert b"}\n *p = *p + 3u64;" in text or b"// boundary\n *p = *p + 3u64;" in text
sample.write_bytes(text)
assert cli("fmt", sample) == text
assert cli("lower", sample) == original_air
# Former value-producing continuations must reject, rather than silently
# discard their left operand. A formatter can still format rejected code.
for body in ("{2u64} *3u64", "{2i64} -3i64",
"if true {2u64} else {3u64} return 0u64;",
"match 0u64 {0=>{2u64} _=>{3u64}} return 0u64;"):
sample = root / "value-boundary.aji"
source = ("module boundary fn main()->u64 effects [] {" + body + "}").encode()
sample.write_bytes(source)
error = json.loads(cli("lower", sample, code=1))
assert error["code"] == "E7006" and "parentheses" in error["message"]
assert error["line"] == 1 and error["col"] == source.index(body.encode()) + 1
text = cli("fmt", sample)
sample.write_bytes(text)
assert cli("fmt", sample) == text
assert json.loads(cli("lower", sample, code=1))["code"] == "E7006"
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:
diagnostics = [json.loads(line) for line in result.stdout.splitlines()]
assert diagnostics and len(diagnostics) <= 32, (path, result.stdout, result.stderr)
assert all(d["code"] == "E7001" for d in diagnostics), (path, diagnostics)
assert [json.loads(line) for line in cli("lower", path, code=1).splitlines()] == diagnostics, path
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
annotation_ranges(path, lower.stdout)
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)")