mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 14:28:40 +00:00
180 lines
7.3 KiB
Python
180 lines
7.3 KiB
Python
"""Regenerate (or check) the translator input fixtures in tests/semantic/fixtures/disasm/ from the hand-written assembly
|
|
sources in runtime/test/shaders/.
|
|
|
|
python tests/semantic/regen_fixtures.py # rewrite every generated fixture
|
|
python tests/semantic/regen_fixtures.py --check # exit 1 if a fixture differs from what would be generated
|
|
python tests/semantic/regen_fixtures.py NAME [...] # mark runtime/test/shaders/NAME.asm and write its fixture
|
|
|
|
The translator (tools/rdna2spirv.py) reads one instruction per tab-indented line and skips the first line. For
|
|
straight-line code it does not need the `; encoding:` comments, so a fixture is the .asm instruction text,
|
|
unchanged, under a one-line header. No assembler is involved, which keeps the tests free of any LLVM version.
|
|
(The .asm syntax itself was written for `llvm-mc -mcpu=gfx1013`; see the comment at the top of each file.)
|
|
|
|
There is no list to edit. A source opts in with the comment line `ASM_MARK` in its own .asm (comments never reach
|
|
the fixture), so adding a fixture touches only that .asm and the new .s, and two PRs that add different fixtures no
|
|
longer edit the same lines. `--check` compares every marked source with its fixture (a missing fixture is reported)
|
|
and also reports a generated fixture whose source is no longer marked. Hand-written fixtures in the same folder
|
|
(another first line) are left alone.
|
|
"""
|
|
import os
|
|
import sys
|
|
import tempfile
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
ROOT = os.path.dirname(os.path.dirname(HERE))
|
|
TOOLS_DIR = os.path.join(ROOT, "tools")
|
|
if TOOLS_DIR not in sys.path:
|
|
sys.path.insert(0, TOOLS_DIR)
|
|
|
|
from file_mode import published_mode # noqa: E402
|
|
import replace_retry # noqa: E402
|
|
|
|
ASM_DIR = os.path.join(ROOT, "runtime", "test", "shaders")
|
|
FIXTURE_DIR = os.path.join(HERE, "fixtures", "disasm")
|
|
ASM_MARK = "; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm"
|
|
HEADER_MARK = "test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/"
|
|
|
|
|
|
def _validate_name(name):
|
|
"""True when `name` is a single plain shader stem (no path separators or traversal segments)."""
|
|
return bool(name) and name not in (".", "..") and os.path.basename(name) == name and "/" not in name and "\\" not in name
|
|
|
|
|
|
def _write_atomic_bytes(path, data):
|
|
"""Stage `data` next to `path` and atomically publish it with destination permissions."""
|
|
abs_path = os.path.abspath(path)
|
|
if os.path.isdir(abs_path):
|
|
raise IsADirectoryError(f"{path} is a directory")
|
|
tmp_path = None
|
|
try:
|
|
with tempfile.NamedTemporaryFile(
|
|
"wb",
|
|
dir=os.path.dirname(abs_path),
|
|
prefix="." + os.path.basename(abs_path) + ".",
|
|
suffix=".tmp",
|
|
delete=False,
|
|
) as f:
|
|
tmp_path = f.name
|
|
f.write(data)
|
|
f.flush()
|
|
os.chmod(tmp_path, published_mode(abs_path))
|
|
replace_retry.replace(tmp_path, abs_path)
|
|
tmp_path = None
|
|
finally:
|
|
if tmp_path is not None:
|
|
try:
|
|
os.unlink(tmp_path)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def marked_names(directory=None):
|
|
"""Names of the .asm sources that carry `ASM_MARK`, in name order: the fixtures this script owns."""
|
|
directory = directory or ASM_DIR
|
|
names = []
|
|
for fname in sorted(os.listdir(directory)) if os.path.isdir(directory) else []:
|
|
if fname.endswith(".asm"):
|
|
with open(os.path.join(directory, fname), encoding="utf-8-sig") as f:
|
|
if any(line.strip() == ASM_MARK for line in f):
|
|
names.append(fname[:-4])
|
|
return names
|
|
|
|
|
|
def generated_names(directory=None):
|
|
"""Names of the fixtures this script wrote, in name order: their first line carries `HEADER_MARK`."""
|
|
directory = directory or FIXTURE_DIR
|
|
names = []
|
|
for fname in sorted(os.listdir(directory)) if os.path.isdir(directory) else []:
|
|
if fname.endswith(".s"):
|
|
with open(os.path.join(directory, fname), encoding="utf-8-sig") as f:
|
|
if HEADER_MARK in f.readline():
|
|
names.append(fname[:-2])
|
|
return names
|
|
|
|
|
|
SHADERS = tuple(marked_names())
|
|
|
|
|
|
def render(name):
|
|
"""Fixture text for one shader: header line, then each instruction line indented with a tab."""
|
|
with open(os.path.join(ASM_DIR, name + ".asm"), encoding="utf-8-sig") as f:
|
|
insns = [ln.strip() for ln in f.read().splitlines() if ln.strip() and not ln.lstrip().startswith(";")]
|
|
head = f"; {name} {HEADER_MARK}{name}.asm\n"
|
|
return head + "".join("\t" + ln + "\n" for ln in insns)
|
|
|
|
|
|
def mark(name):
|
|
"""Put `ASM_MARK` at the top of NAME.asm unless it is already there."""
|
|
path = os.path.join(ASM_DIR, name + ".asm")
|
|
with open(path, encoding="utf-8-sig", newline="") as f:
|
|
text = f.read()
|
|
if not any(line.strip() == ASM_MARK for line in text.splitlines()):
|
|
newline = "\r\n" if "\r\n" in text else "\n"
|
|
_write_atomic_bytes(path, (ASM_MARK + newline + text).encode("utf-8"))
|
|
|
|
|
|
def shown(path):
|
|
try:
|
|
return os.path.relpath(path, ROOT)
|
|
except ValueError: # another drive than the repository (a TEMP on C: for a checkout on E:)
|
|
return path
|
|
|
|
|
|
def main(argv):
|
|
check = False
|
|
named = []
|
|
stop_flags = False
|
|
for arg in argv:
|
|
if not stop_flags and arg == "--":
|
|
stop_flags = True
|
|
continue
|
|
if not stop_flags and arg in ("-h", "--help"):
|
|
print(__doc__.splitlines()[0])
|
|
return 0
|
|
if not stop_flags and arg == "--check":
|
|
check = True
|
|
continue
|
|
if not stop_flags and arg.startswith("-"):
|
|
print(f"unknown option: {arg}", file=sys.stderr)
|
|
return 2
|
|
if not _validate_name(arg):
|
|
print(f"invalid shader name: {arg}", file=sys.stderr)
|
|
return 2
|
|
named.append(arg)
|
|
missing = [n for n in named if not os.path.isfile(os.path.join(ASM_DIR, n + ".asm"))]
|
|
if missing:
|
|
print(f"no runtime/test/shaders/{missing[0]}.asm", file=sys.stderr)
|
|
return 2
|
|
try:
|
|
if named and not check:
|
|
for name in named:
|
|
mark(name)
|
|
bad = 0
|
|
for name in named or marked_names():
|
|
path = os.path.join(FIXTURE_DIR, name + ".s")
|
|
want = render(name)
|
|
if check:
|
|
have = ""
|
|
if os.path.isfile(path):
|
|
with open(path, encoding="utf-8-sig", newline="") as f:
|
|
have = f.read().replace("\r\n", "\n")
|
|
if have != want:
|
|
print(f"{name}: fixture is stale or missing")
|
|
bad += 1
|
|
else:
|
|
os.makedirs(FIXTURE_DIR, exist_ok=True)
|
|
_write_atomic_bytes(path, want.encode("utf-8"))
|
|
print(f"wrote {shown(path)}")
|
|
if check and not named:
|
|
for name in sorted(set(generated_names()) - set(marked_names())):
|
|
print(f"{name}: generated fixture whose runtime/test/shaders/{name}.asm is not marked (or is gone)")
|
|
bad += 1
|
|
except (OSError, UnicodeDecodeError) as exc:
|
|
print(f"error processing fixtures: {exc}", file=sys.stderr)
|
|
return 2
|
|
return 1 if bad else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main(sys.argv[1:]))
|