Files
doslang-mirror/tests/run.py
T
coolguy 730bcac282 audit: SPEC-파서 괴리 일곱을 정리한다
구현 셋, SPEC 다섯. 어느 쪽이 틀렸는지는 항목마다 따로 판정했다.

구현:
- ~ 를 넣었다. ^ 는 xor 과 .^ 가 가져가서 비트 NOT 이 자기 철자를 못 갖고
  있었다. 렉서·파서·검사·lowering(전부 1 과의 xor).
- 전역 static/var 는 타입을 적는다. 다른 유닛이 읽는 링커 심볼이라 초기값의
  생김새에 타입을 맡기면 그쪽이 보는 것이 달라진다. const 는 그대로 추론한다.
- error code 는 정수 리터럴 하나다. 식이면 중복도 예약된 0 도 검사할 수 없다.

SPEC:
- 최상위 comptime if 를 뺐다. comptime 조건은 타입 술어뿐인데(§7.5) 유닛
  바깥에는 바인딩된 타입 파라미터가 없어 물어볼 것이 없다. §11 v0.2.
- 타입 이름은 [binding.]Name 이다. import 가 마지막 segment 를 바인딩하므로
  점 둘 이상은 만들어질 수 없는데 문법이 unit_path 를 쓰고 있었다.
- catch 의 EBNF 가 §4.6 보다 넓었다. 값을 주는 짧은 형태와 에러를 받는 블록
  형태 둘로 나눠 적었다.
- | 와 ^ 를 한 단계로 둔 것을 쪼갰다. 합치면 a | b ^ c 가 좌결합으로
  (a|b)^c 가 되어 C 에서 온 사람을 속인다. 구현이 C 순서로 옳았다.
- 마지막 필드 쉼표 생략을 명세에 적었다. enum 은 이미 허용하고 있었다.

그리고 tests/run.py 가 마커를 진단 스트림에만 맞춘다. --dump-ast 모드에서는
AST 덤프가 stdout 으로 먼저 나와서 parse/ fixture 는 마커를 쓸 수 없었다.

249/249, 39/39.
2026-08-17 16:52:12 +09:00

177 lines
6.9 KiB
Python

"""Run every fixture through the front end and check what it reports.
A fixture is checked by running `fec` on it and looking at two things: whether
it was accepted, and, when it was rejected, whether the diagnostic is the one
the fixture asked for.
A fixture states its expectation in its first line:
// ERROR:8:self rejected at line 8, with "self" in the message
// ERROR:expected ';' rejected, message only -- the parse fixtures, where
the line is not the interesting part
A fixture with no marker whose name starts with `bad` must be rejected but does
not pin the message yet. Anything else must be accepted.
Fixtures under `parse/` are checked with --dump-ast rather than --check: they
exercise the grammar, and several are deliberately not well-typed.
This runs on the host in about a second. It checks what the compiler says; what
the compiled programs actually do is `exec.py`.
"""
from __future__ import annotations
import argparse
import os
import re
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
FIXTURES = ROOT / "fec" / "tests"
WATCOM = ROOT / ".dosboxx" / "watcom"
SOURCES = ("arena", "diag", "lexer", "ast", "parser", "types", "m7", "own",
"check", "checkexp", "checkstm", "checkgen", "checkcal", "checkpro",
"resolve", "ir", "lower", "lowerprn", "lowerexp", "lowerstm", "x86", "report", "driver")
MARKER = re.compile(r"^//\s*ERROR:(?:(\d+):)?(.*)$")
@dataclass
class Expectation:
rejected: bool
line: int | None = None
text: str | None = None
def expectation(path: Path) -> Expectation:
first = path.read_text(encoding="utf-8", errors="replace").split("\n", 1)[0]
m = MARKER.match(first.strip())
if m:
line = int(m.group(1)) if m.group(1) else None
return Expectation(True, line, m.group(2).strip())
name = path.stem
return Expectation(name.startswith("bad") or "-bad-" in name or name.startswith("own-bad"))
def build(out: Path) -> Path:
"""Build the front end with the pinned toolchain, hosted."""
wcl = WATCOM / "binnt" / "wcl386.exe"
if not wcl.is_file():
sys.exit(f"pinned Open Watcom not found at {WATCOM}")
out.mkdir(parents=True, exist_ok=True)
env = dict(os.environ)
env.update(WATCOM=str(WATCOM), INCLUDE=f"{WATCOM / 'h'};{WATCOM / 'h' / 'nt'}",
PATH=f"{WATCOM / 'binnt'}{os.pathsep}{env.get('PATH', '')}")
src = ROOT / "fec" / "src"
cmd = [str(wcl), "-q", "-za", "-wx", "-bt=nt", "-fe=fec.exe", f"-i={src}"]
cmd += [str(src / f"{n}.c") for n in SOURCES]
done = subprocess.run(cmd, cwd=out, capture_output=True, text=True, env=env)
if done.returncode != 0 or (done.stdout + done.stderr).strip():
sys.exit("front end does not build clean:\n" + done.stdout + done.stderr)
return out / "fec.exe"
def run_case(fec: Path, path: Path) -> tuple[bool, str]:
want = expectation(path)
# The grammar fixtures are not all well-typed; stop after parsing.
mode = "--dump-ast" if path.parent.name == "parse" else "--check"
done = subprocess.run([str(fec), mode, str(path),
f"--std={ROOT / 'fec'}"],
capture_output=True, text=True, timeout=30)
output = (done.stdout + done.stderr).strip()
# Diagnostics go to the diag stream. `--dump-ast` also writes the tree to
# stdout, so a marker matched against the two together would read the tree
# and never reach the error.
diags = done.stderr.strip() or output
rejected = done.returncode != 0
if want.rejected != rejected:
verb = "accepted" if rejected else "rejected"
return False, f"expected to be {'rejected' if want.rejected else verb}"
if not want.rejected:
return True, ""
if want.line is None:
if want.text and want.text.lower() not in output.lower():
got = output.splitlines()[0] if output else "(silent)"
return False, f"marker wants {want.text!r}\n {got}"
return True, ""
# The marker pins where and roughly what, so a rule can be moved or reworded
# only deliberately.
first = diags.split("\n", 1)[0] if diags else ""
at = re.search(r":(\d+):\d+: error:", first)
if not at:
return False, f"no diagnostic to match marker\n got: {first or '(silent)'}"
if int(at.group(1)) != want.line:
return False, f"marker says line {want.line}, diagnostic is line {at.group(1)}\n {first}"
if want.text and want.text.lower() not in diags.lower():
return False, f"marker wants {want.text!r}\n {first}"
return True, ""
def main() -> int:
ap = argparse.ArgumentParser(description="run the front-end fixtures")
ap.add_argument("-k", dest="select", help="only fixtures whose path contains this")
ap.add_argument("-v", dest="verbose", action="store_true")
args = ap.parse_args()
fec = build(ROOT / ".build")
cases = sorted(FIXTURES.rglob("*.fe"))
if args.select:
cases = [p for p in cases if args.select in p.as_posix()]
failed = []
for path in cases:
ok, why = run_case(fec, path)
rel = path.relative_to(FIXTURES).as_posix()
if ok:
if args.verbose:
print(f" ok {rel}")
else:
failed.append((rel, why))
for rel, why in failed:
print(f"FAIL {rel}: {why}")
marked = sum(1 for p in cases if expectation(p).line is not None)
print(f"\n{len(cases) - len(failed)}/{len(cases)} passed "
f"({marked} pin a line and message)")
if not args.select:
leak = unsafe_budget(fec)
if leak:
print(leak)
return 1
return 1 if failed else 0
# The programs the budget is measured on: the Ferro front end, and the ones
# that lean hardest on the standard library.
BUDGETED = ("exec/lexer/tree.fe", "exec/interns.fe", "exec/arenat.fe",
"exec/maps.fe", "exec/wordfreq.fe")
def unsafe_budget(fec: Path) -> str:
"""`unsafe` and `*T` belong to std.mem and std.sys. Anywhere else they are
a hole in what the checker promises, so the count outside std has to stay
at zero and a regression has to fail the build rather than be noticed."""
for rel in BUDGETED:
path = FIXTURES / rel
if not path.is_file():
return f"budget: {rel} is gone"
done = subprocess.run([str(fec), "--report-unsafe", str(path),
f"--std={ROOT / 'fec'}"],
capture_output=True, text=True)
line = [l for l in done.stdout.splitlines()
if l.startswith("outside std")]
if not line:
return f"budget: no report for {rel}\n{done.stdout}{done.stderr}"
counts = line[0].split()[2:]
if any(c != "0" for c in counts):
return (f"budget: {rel} has unsafe/raw pointers outside std: "
f"{line[0]}")
return ""
if __name__ == "__main__":
raise SystemExit(main())