Files
mandy/tools/d3d12_switches.py
MoonEyes 6a321e5db4 tools: d3d12_switches and d3d12_run_fps set errors=replace on stdout
tests/test_tool_stdout_encoding.py asks it of every tool. d3d12_run_fps.py came
in with #2594 without it, which left that test red on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:23:47 +01:00

328 lines
15 KiB
Python

"""List the LEONIDA_* variables the D3D12 runtime (`d3d12/`) names, with what the code says of each.
python -I tools/d3d12_switches.py --out d3d12/docs/switches.md
python -I tools/d3d12_switches.py --check d3d12/docs/switches.md # names missing from the page, or no longer read
The page is made from the sources alone: where a name is read, whether the code treats it as a switch, whether
`LEONIDA_AB` can turn it while the title runs, and the sentence of the comment that names it. The sentences are the
code's own words, cut to one line, not a measurement: what a switch costs or gains is in `d3d12/docs/findings.md`.
Values the launcher sets are not copied (some are long lists), only that it sets the name.
"""
import argparse
import os
import re
import subprocess
import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
NAME = re.compile(r"LEONIDA_[A-Z0-9_]*[A-Z0-9](?![A-Z0-9_])")
LITERAL = re.compile(r'"(LEONIDA_[A-Z0-9_]*[A-Z0-9])"')
COMMENT = re.compile(r"^\s*//[/!]?\s?(.*)$")
# The launcher's own assignments: `LEONIDA_X = '1'` in a table of settings (several may stand on a line),
# `$env:LEONIDA_X = ...` or `$settings.LEONIDA_X = ...`.
ASSIGNED = re.compile(r"(?:^\s*|[;{]\s*|\$env:|\$settings\.)(LEONIDA_[A-Z0-9_]*[A-Z0-9])\s*=(?!=)")
TEST_CFG = re.compile(r"#\[cfg\((?:test|all\(test,.*\))\)\]$")
# What turns a name into a switch of `LEONIDA_AB`.
AB_CALL = r"(?:toggled!|asked!|asked_for!|\bab::pick|\bab::bit|\bswitched)"
# What comments write for "any name".
PLACEHOLDERS = {"LEONIDA_X"}
LAUNCHER = "d3d12/scripts/play-nvidia.ps1"
FINDINGS = "d3d12/docs/findings.md"
LONGEST = 220
def tracked(root, top):
out = subprocess.run(["git", "ls-files", top], cwd=root, capture_output=True, text=True, check=True).stdout
return [p for p in out.splitlines() if p]
def read(root, rel):
with open(os.path.join(root, rel), encoding="utf-8", errors="replace") as f:
return f.read()
def is_test_file(rel):
base = os.path.basename(rel)
return "/tests/" in rel or "/benches/" in rel or base in ("tests.rs",) or base.endswith("_tests.rs")
def without_raw_strings(text):
"""`text` with what stands in raw strings blanked, its lines kept: a `}` in a shader's source ends no module."""
return re.sub(r'\br(#*)"(.*?)"\1', lambda m: re.sub(r"[^\n]", " ", m.group(0)), text, flags=re.S)
def test_files(files):
"""The files of outline modules that only tests have (`#[cfg(test)] mod name;`), and the folders below them."""
tops = set()
for rel, text in files.items():
if not rel.endswith(".rs"):
continue
folder, _, base = rel.rpartition("/")
here = folder if base in ("lib.rs", "main.rs", "mod.rs") else rel[:-len(".rs")]
for m in re.finditer(r"^\s*#\[cfg\((?:test|all\(test,.*\))\)\]\s*\n(?:\s*#\[.*\]\s*\n)*"
r"\s*(?:pub(?:\(\w+\))? )?mod (\w+);", text, re.M):
tops.add(f"{here}/{m.group(1)}")
return {rel for rel in files for top in tops if rel == top + ".rs" or rel.startswith(top + "/")}
def ab_names(text):
"""The names `text` (one file) hands to what `LEONIDA_AB` turns."""
names = set(re.findall(rf'{AB_CALL}\(\s*"(LEONIDA_[A-Z0-9_]+)"', text))
# `const SWITCH: &str = "..."` and `ab::pick(SWITCH)`; another constant further on may have the same name.
consts = list(re.finditer(r"const (\w+): &(?:'static )?str = \"(LEONIDA_[A-Z0-9_]+)\"", text))
for i, m in enumerate(consts):
end = next((c.start() for c in consts[i + 1:] if c.group(1) == m.group(1)), len(text))
if re.search(rf"{AB_CALL}\(\s*{m.group(1)}\b", text[m.end():end]):
names.add(m.group(2))
# A function or closure of the file that hands its argument on, and a list of names that is gone through.
for m in re.finditer(r"(?:fn (\w+)\(|let (\w+) = \|)(\w+): &(?:'static )?str", text):
if re.search(rf"\bab::(?:pick|bit)\({m.group(3)}\)", text[m.end():m.end() + 200]):
names.update(re.findall(rf'(?<![\w.]){m.group(1) or m.group(2)}\(\s*"(LEONIDA_[A-Z0-9_]+)"', text))
for m in re.finditer(r"const \w+: \[&str; \d+\] = \[([^\]]*)\];", text):
if re.search(r"\bab::(?:pick|bit)\(name\)", text[m.end():m.end() + 600]):
names.update(LITERAL.findall(m.group(1)))
return names
def test_lines(text):
"""The line numbers inside the file's own `#[cfg(test)] mod name {` modules (`mod name;` is another file)."""
lines = without_raw_strings(text).splitlines()
inside, i = set(), 0
while i < len(lines):
if TEST_CFG.match(lines[i].strip()):
# Other attributes may stand between it and the module.
j = i + 1
while j < len(lines) and lines[j].strip().startswith("#["):
j += 1
m = re.match(r"(\s*)(?:pub(?:\([a-z]+\))? )?mod \w+ \{", lines[j]) if j < len(lines) else None
if m:
end = next((k for k in range(j + 1, len(lines)) if lines[k] == m.group(1) + "}"), len(lines) - 1)
inside.update(range(i, end + 1))
i = end
i += 1
return inside
def blocks(lines):
"""Runs of comment lines, each as one text."""
out, run = [], []
for line in lines + [""]:
m = COMMENT.match(line)
if m:
run.append(m.group(1).strip())
elif run:
out.append(" ".join(run))
run = []
return out
def sentence(text, name):
"""The sentence of `text` that names `name`, on one line, or ""."""
text = re.sub(r"\s+", " ", text)
m = re.search(rf"(?<![A-Z0-9_]){name}(?![A-Z0-9_])", text)
if not m:
return ""
starts = [0] + [cut.end() for cut in re.finditer(r"[.!?:;]\)? (?=[A-Z`(])", text[:m.start()])]
end = re.search(r"[.!?]\)?(?= [A-Z`(]|$)", text[m.end():])
stop = m.end() + end.end() if end else len(text)
def words(piece):
return len(re.findall(r"[a-z]{2,}", piece.replace(name, "")))
# The shortest piece that says something and does not begin or end inside a parenthesis.
for start in reversed(starts):
said = text[start:stop].strip()
if said.count("(") == said.count(")") and words(said) >= 3:
break
else:
start = starts[-1]
said = text[start:stop].strip()
if words(said) < 3:
return ""
if len(said) > LONGEST:
# Keep the name in what is left: cut the front when it lies too far in.
at = m.start() - start
front = max(0, at - 60) if at > LONGEST - 80 else 0
said = ("..." if front else "") + said[front:front + LONGEST].rstrip() + "..."
return said
def kind(uses, name):
quoted = f'"{name}"'
text = "\n".join(uses)
if re.search(rf"toggled!\(\s*{quoted}", text):
return "on, `0` turns it off"
if re.search(rf"(asked!|switch::on)\(\s*{quoted}", text):
return "off unless set and not `0`"
return "see the code"
def collect(files, launcher="", findings=""):
"""{name: {"files", "uses", "said", "ab", "tests", "launcher", "findings"}} over `files` ({path: text})."""
found = {}
def entry(name):
return found.setdefault(name, {"files": set(), "uses": [], "said": "", "ab": False, "tests": False, "read": False,
"launcher": False, "findings": False})
outline = test_files(files)
for rel in sorted(files):
lines = files[rel].splitlines()
rust = rel.endswith(".rs")
whole = rust and (is_test_file(rel) or rel in outline)
tests = test_lines(files[rel]) if rust else set()
for i, line in enumerate(lines):
comment = COMMENT.match(line) if rust else re.match(r"\s*(?:#|rem\b|::)", line, re.I)
for name in LITERAL.findall(line) if rust and not comment else NAME.findall(line):
e = entry(name)
e["files"].add(rel)
if comment:
continue
if whole or i in tests:
e["tests"] = True
continue
e["read"] = True
if rust:
# A call that breaks the line before its argument still says what it is.
e["uses"].append((lines[i - 1].strip() if i else "") + " " + line.strip())
if rust and not whole:
for name in ab_names(files[rel]):
entry(name)["ab"] = True
for name in PLACEHOLDERS:
found.pop(name, None)
for rel in sorted(files):
if not rel.endswith(".rs"):
continue
for text in blocks(files[rel].splitlines()):
for name in set(NAME.findall(text)):
said = sentence(text, name)
# A comment where the name is read says more than one that mentions it elsewhere.
here = f'"{name}"' in files[rel]
e = found.get(name)
if e is not None and said and (not e["said"] or (here and not e.get("here"))):
e["said"], e["here"] = said, here
for name in {n for line in launcher.splitlines()
if not line.lstrip().startswith("#") for n in ASSIGNED.findall(line)}:
if name in found:
found[name]["launcher"] = True
for name in set(NAME.findall(findings)):
if name in found:
found[name]["findings"] = True
return found
def cell(text):
return text.replace("|", "\\|").replace("<", "&lt;").replace(">", "&gt;")
def where(files):
"""The first file that reads the name, short, and how many others name it."""
first = min(files, key=lambda f: (not f.endswith(".rs"), f))
short = re.sub(r"^d3d12/(?:crates|apps)/", "", first).replace("/src/", "/")
short = re.sub(r"^d3d12/", "", short)
more = len(files) - 1
return f"`{short}`" + (f" +{more}" if more else "")
def page(found):
real = {n: e for n, e in found.items() if e["read"]}
tests = sorted(n for n, e in found.items() if e["tests"] and not e["read"])
named = sorted(n for n, e in found.items() if not e["tests"] and not e["read"])
said = sum(1 for e in real.values() if e["said"])
out = [
"# The D3D12 runtime's `LEONIDA_*` variables", "",
"Made by `python -I tools/d3d12_switches.py --out d3d12/docs/switches.md` from the sources of `d3d12/`; do not",
"edit it by hand. No CI job keeps it up to date: run the command again, or `--check`, when you need it current.",
"It says which names exist and what the code's own comments say of them. It is **not** a list of recommended",
"settings and says nothing of what a switch gains: for that read [findings.md](findings.md) first,",
"and [how to measure frame rates](../../docs/measuring_fps.md) before trying one.", "",
f"{len(real)} names; {said} have a sentence of a comment below, the others no comment or only a bare list.", "",
"- **Kind**: how the code reads it, where that can be told. \"see the code\" is a number, a path, a list or a",
" switch read some other way; its default is not given here.",
"- **A/B**: `LEONIDA_AB` can turn it while the title runs (builds with `diagnostics`), where the code reads it by",
" name that way. Blank means it was not found so, not that it cannot.",
"- **L**: the NVIDIA launcher (`d3d12/scripts/play-nvidia.ps1`) has an assignment for it, perhaps only with some option.",
"- **F**: named in [findings.md](findings.md), which is where a measurement would be.",
"- **In the code's words**: the sentence of the comment that names it, cut to one line. Comments go out of date;",
" the code is what counts.", "",
]
by_top = {}
for n, e in real.items():
first = min(e["files"], key=lambda f: (not f.endswith(".rs"), f))
m = re.match(r"d3d12/(?:crates|apps)/([^/]+)/", first)
by_top.setdefault(m.group(1) if m else "scripts and others", []).append(n)
for top in sorted(by_top):
out += [f"## {top}", "", "| Name | Kind | A/B | L | F | Named in | In the code's words |", "|---|---|---|---|---|---|---|"]
for n in sorted(by_top[top]):
e = real[n]
mark = lambda b: "yes" if b else ""
out.append(f"| `{n}` | {kind(e['uses'], n)} | {mark(e['ab'])} | {mark(e['launcher'])} | {mark(e['findings'])} "
f"| {where(e['files'])} | {cell(e['said'])} |")
out.append("")
if tests:
out += ["## Only in tests", "", "Read by test code alone, or made up by it: " + ", ".join(f"`{n}`" for n in tests) + ".", ""]
if named:
out += ["## Only in comments", "", "Named in a comment of `d3d12/` and read nowhere by that name: "
+ ", ".join(f"`{n}`" for n in named) + ".", ""]
return "\n".join(out)
def difference(found, text):
"""(names the sources have and the page lacks, names the page lists that no source has)."""
listed = set(re.findall(r"^\| `(LEONIDA_[A-Z0-9_]+)` \|", text, re.M))
tests = re.search(r"^Read by test code alone.*$", text, re.M)
if tests:
listed |= set(NAME.findall(tests.group(0)))
now = {n for n, e in found.items() if e["read"] or e["tests"]}
return sorted(now - listed), sorted(listed - now)
def gather(root):
files = {p: read(root, p) for p in tracked(root, "d3d12")
if p.endswith((".rs", ".ps1", ".cmd")) and "/third_party/" not in p}
launcher = files.get(LAUNCHER, "")
findings = read(root, FINDINGS) if os.path.exists(os.path.join(root, FINDINGS)) else ""
return collect(files, launcher, findings)
def main(argv=None):
ap = argparse.ArgumentParser(description="List the LEONIDA_* variables the D3D12 runtime names.")
ap.add_argument("--root", default=ROOT, help="the repository (default: the one this script is in)")
what = ap.add_mutually_exclusive_group(required=True)
what.add_argument("--out", help="write the page here")
what.add_argument("--check", help="compare the names of this page with the sources; exit 1 when they differ")
args = ap.parse_args(argv)
try:
found = gather(args.root)
except (OSError, subprocess.CalledProcessError) as error:
print(f"d3d12_switches.py: cannot list the sources: {error}", file=sys.stderr)
return 2
if args.check:
try:
with open(args.check, encoding="utf-8") as f:
missing, gone = difference(found, f.read())
except OSError as error:
print(f"d3d12_switches.py: {error}", file=sys.stderr)
return 2
for name in missing:
print(f"missing from the page: {name}")
for name in gone:
print(f"no longer in the sources: {name}")
return 1 if missing or gone else 0
try:
with open(args.out, "w", encoding="utf-8", newline="\n") as f:
f.write(page(found))
except OSError as error:
print(f"d3d12_switches.py: {error}", file=sys.stderr)
return 2
print(f"{len(found)} names written to {args.out}")
return 0
if __name__ == "__main__":
try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
sys.stdout.reconfigure(errors="replace")
except (AttributeError, ValueError, OSError):
pass
sys.exit(main())