rust_modtree.py: a cfg(feature = "preview-path") attribute was taken for a #[path] attribute (two modules were invisible to the tools). path_to_modules.py keeps a file that two parents declare (native_down_pair_io.rs, one copy of the state each). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
151 lines
6.3 KiB
Python
151 lines
6.3 KiB
Python
"""Remove `#[allow(unused_imports)]` and what it hid (STRA-338 stage 10, ratchet `allow-unused-imports`).
|
|
|
|
Usage: python scripts/dev/drop_allow_unused.py WORKTREE CRATE_DIR PACKAGE [--keep-test-only]
|
|
|
|
The attribute sat on re-exports (`pub use child::name;`) that the splits kept so the old paths still resolve. Without it the compiler
|
|
says which of them nobody uses:
|
|
|
|
* a name unused in the unit-test build is unused everywhere (that build compiles all code and the tests): it is deleted from its
|
|
`use` statement, the statement goes when nothing is left;
|
|
* a name used by the test build only is kept as `#[cfg(test)] use ..;` (the statement is split when it names others too).
|
|
|
|
One round is `cargo check --lib --bins` and `--tests`; the loop repeats because deleting a re-export can make another one unused.
|
|
Offline refactoring aid, not part of the product.
|
|
"""
|
|
import collections
|
|
import json
|
|
import pathlib
|
|
import re
|
|
import sys
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).parent))
|
|
import explicit_imports as ei # noqa: E402
|
|
from unglob_by_errors import PLATFORM_FILES # noqa: E402
|
|
|
|
ALLOW = re.compile(r"^[ \t]*#\[allow\(unused_imports\)\][ \t]*\n", re.M)
|
|
USE_STATEMENT = re.compile(r"(?ms)^(?P<attrs>(?:[ \t]*(?:#\[[^\n]*\]|///[^\n]*)\n)*)(?P<head>[ \t]*(?:pub(?:\([^)]*\))?[ \t]+)?use[ \t]+)"
|
|
r"(?P<body>[^;]*?);[ \t]*\n")
|
|
NL = chr(10)
|
|
NAME = re.compile(rf"(?:\bas\s+)?({ei.IDENT})\s*$")
|
|
|
|
|
|
def bound(item):
|
|
"""The name an import item binds (`a::B` -> B, `a::b as c` -> c); None for globs and `as _`."""
|
|
m = NAME.search(item)
|
|
return m.group(1) if m and not item.rstrip().endswith("as _") else None
|
|
|
|
|
|
def statement_names(body):
|
|
"""[(name as it is bound, source text of the item)] of `a::b::{c, d as e}` or `a::b::c` (one level of braces)."""
|
|
body = body.strip()
|
|
brace = body.find("{")
|
|
if brace < 0:
|
|
return [(bound(body), body)], body, None
|
|
prefix, inner = body[:brace], body[brace + 1 : body.rindex("}")]
|
|
items = [i.strip() for i in inner.split(",") if i.strip()]
|
|
return [(bound(i), i) for i in items], prefix, items
|
|
|
|
|
|
def build(attrs, head, prefix, items):
|
|
"""One `use` statement for `items` below `prefix`, wrapped at 120 columns like rustfmt does."""
|
|
indent = head[: len(head) - len(head.lstrip())]
|
|
if len(items) == 1 and not items[0].startswith("self"):
|
|
return f"{attrs}{head}{prefix}{items[0]};{NL}"
|
|
one = f"{head}{prefix}{{{', '.join(items)}}};"
|
|
if len(one) <= 120:
|
|
return f"{attrs}{one}{NL}"
|
|
lines, cur = [], indent + " "
|
|
for item in items:
|
|
if len(cur) + len(item) + 1 > 120:
|
|
lines.append(cur.rstrip())
|
|
cur = indent + " "
|
|
cur += item + ", "
|
|
lines.append(cur.rstrip())
|
|
return f"{attrs}{head}{prefix}{{{NL}{NL.join(lines)}{NL}{indent}}};{NL}"
|
|
|
|
|
|
def rewrite(text, drop, test_only):
|
|
"""The text with `drop` names deleted and `test_only` names moved under `#[cfg(test)]`."""
|
|
def fix(m):
|
|
if "{" in m.group("body").split("{", 1)[-1]: # nested braces: left for a person
|
|
return m.group(0)
|
|
names, prefix, items = statement_names(m.group("body"))
|
|
gone = [i for n, i in names if n in drop]
|
|
moved = [i for n, i in names if n in test_only]
|
|
if not gone and not moved:
|
|
return m.group(0)
|
|
attrs, head = m.group("attrs"), m.group("head")
|
|
if items is None: # a single path
|
|
return f"{attrs}#[cfg(test)]{NL}{head}{m.group('body').strip()};{NL}" if moved else ""
|
|
left = [i for n, i in names if n not in drop and n not in test_only]
|
|
out = build(attrs, head, prefix, left) if left else ""
|
|
if moved:
|
|
out += build("" if left else attrs, head, prefix, moved).replace(head, "#[cfg(test)]" + NL + head, 1)
|
|
return out
|
|
|
|
return USE_STATEMENT.sub(fix, text)
|
|
|
|
|
|
def write(path, text):
|
|
with open(path, "w", encoding="utf-8", newline=chr(10)) as handle:
|
|
handle.write(text)
|
|
|
|
|
|
def flagged_counts(msgs):
|
|
"""Counter {(file, name): messages} of the unused-import warnings (a name flagged by two units counts twice)."""
|
|
counts = collections.Counter()
|
|
for m in msgs:
|
|
for r, names in ei.flagged([m], "unused").items():
|
|
counts.update((r, n) for n in names)
|
|
return counts
|
|
|
|
|
|
def classify(counts_a, counts_b):
|
|
"""({file: names unused everywhere}, {file: names used by the test build only}) from the two builds.
|
|
`--tests` builds the library once more as a dependency of the integration tests, so it repeats the first build's
|
|
warnings; what it says on top of that comes from the unit-test build."""
|
|
drop, test_only = collections.defaultdict(set), collections.defaultdict(set)
|
|
for (r, name), n_a in counts_a.items():
|
|
if counts_b.get((r, name), 0) > n_a:
|
|
drop[r].add(name)
|
|
else:
|
|
test_only[r].add(name)
|
|
for (r, name), n_b in counts_b.items():
|
|
if (r, name) not in counts_a: # a file only the test build compiles
|
|
drop[r].add(name)
|
|
return drop, test_only
|
|
|
|
|
|
def main():
|
|
wt, crate_dir, package = sys.argv[1:4]
|
|
wtp = pathlib.Path(wt).resolve()
|
|
rel = lambda f: f.resolve().relative_to(wtp).as_posix() # noqa: E731
|
|
crate = pathlib.Path(crate_dir).resolve()
|
|
files = {f: f.read_text(encoding="utf-8") for f in (crate / "src").rglob("*.rs")}
|
|
for f, text in files.items():
|
|
if ALLOW.search(text) and "--keep-allow" not in sys.argv:
|
|
files[f] = ALLOW.sub("", text)
|
|
write(f, files[f])
|
|
for round_no in range(1, 8):
|
|
a = ei.run_cargo(wt, f"-p {package} --lib --bins", "da-a.json")
|
|
b = ei.run_cargo(wt, f"-p {package} --tests", "da-b.json")
|
|
drop_by_file, test_by_file = classify(flagged_counts(a), flagged_counts(b))
|
|
touched = 0
|
|
by_rel = {rel(f): f for f in files}
|
|
for r in set(drop_by_file) | set(test_by_file):
|
|
f = by_rel.get(r)
|
|
if f is None or r.split("/src/", 1)[-1] in PLATFORM_FILES: # their other-platform code is not built here
|
|
continue
|
|
new = rewrite(files[f], drop_by_file.get(r, set()), test_by_file.get(r, set()))
|
|
if new != files[f]:
|
|
files[f] = new
|
|
write(f, new)
|
|
touched += 1
|
|
print(f"round {round_no}: {touched} files edited", flush=True)
|
|
if not touched:
|
|
break
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|