Files
leleka/scripts/dev/explicit_imports.py

598 lines
26 KiB
Python

"""Expand `#[allow(unused_imports)] use super::*;` into explicit imports in the files that a mechanical split left behind,
and replace the 'Moved out of the parent module' header by a doc comment generated from the file's content.
Usage: python scripts/dev/explicit_imports.py WORKTREE CRATE_DIR PACKAGE [--features-all] [--dry-run]
Each file with the `#[allow(unused_imports)] use super::*;` pair (what `rustsplit` leaves behind) gets `use super::{names}`
with exactly the names it uses (compiled and pruned against `cargo check --lib --bins` and `--tests`); a file that cannot be
expanded safely stays as it was (reported). The 'Moved out of the parent module by STRA-338' header becomes a two-line doc
comment generated from what the file defines. Compiles through `cargo` (on Windows through `scripts/dev/wsl-cargo.sh`), so a
crate takes minutes per round. Offline refactoring aid (STRA-338 debt (c)); not part of the product.
"""
import collections
import json
import os
import pathlib
import posixpath
import re
import shutil
import subprocess
import sys
import tempfile
sys.path.insert(0, str(pathlib.Path(__file__).parent))
from rust_modtree import IDENT, MIXED_CFG, OPAQUE, Crate, normalize_cfg, statements, strip_code # noqa: E402
GLOB_RE = re.compile(r"^(?:#\[allow\(unused_imports\)\]\s*\n)?use super::\*;[ \t]*\n", re.M)
USE_SUPER_RE = re.compile(r"(?m)^(?:// used only with some cargo features of this crate\n#\[allow\(unused_imports\)\]\n)?(?:#\[cfg\([^\n]*\)\]\n)*use super::(?:\{[^}]*\}|[A-Za-z_]\w*);\n")
HEADER_RE = re.compile(r"\A((?://![^\n]*\n)+)")
PLATFORM_CFG = re.compile(
r"cfg\([^\n]*(windows|macos|miri|target_feature|not\((?:target_|windows|unix|miri)"
r"|target_os\s*=\s*\"(?!linux)|target_arch\s*=\s*\"(?!x86_64))"
)
WIDTH = 120
RUSTFMT = shutil.which("rustfmt") or "rustfmt"
WORK = pathlib.Path(tempfile.gettempdir()) / "explicit-imports"
def run_cargo(wt, args, out_name):
"""Messages of `cargo check --message-format=json ARGS` run in `wt`; the log is kept in WORK."""
WORK.mkdir(parents=True, exist_ok=True)
out = WORK / (pathlib.Path(wt).resolve().name + "-" + out_name)
check = ["check", "--message-format=json"] + args.split()
if sys.platform == "win32":
helper = pathlib.Path(__file__).parent / "wsl-cargo.sh"
rel_log = pathlib.Path("target") / ("explicit-imports-" + out_name)
subprocess.run(["bash", str(helper), rel_log.as_posix()] + check, cwd=wt, check=False, capture_output=True)
out = pathlib.Path(wt) / rel_log
else:
with open(out, "w", encoding="utf-8") as handle:
subprocess.run(["cargo"] + check, cwd=wt, check=False, stdout=handle, stderr=subprocess.DEVNULL)
messages = []
for line in out.read_text(encoding="utf-8", errors="replace").splitlines():
if not line.startswith("{"):
continue
try:
record = json.loads(line)
except ValueError:
continue
if record.get("reason") == "compiler-message":
messages.append(record["message"])
return messages
def span_name(span):
"""The imported name a span of an unused-import warning highlights."""
try:
text = span["text"][0]["text"][span["text"][0]["highlight_start"] - 1 : span["text"][0]["highlight_end"] - 1]
except (KeyError, IndexError):
return None
m = re.search(rf"({IDENT})\s*[,;}}]?\s*$", text)
return m.group(1) if m else None
def flagged(messages, kind):
"""{file: {name}} of the unused imports; errors as {file: count} when kind == 'errors'."""
out = collections.defaultdict(set)
for m in messages:
if kind == "errors":
if m["level"] == "error":
for s in m["spans"]:
if s["is_primary"]:
out[posixpath.normpath(s["file_name"])].add(m["message"][:80])
continue
code = (m.get("code") or {}).get("code")
if m["level"] == "warning" and code == "unused_imports":
for s in m["spans"]:
if s["is_primary"]:
name = span_name(s)
if name == "_":
text = "".join(t["text"][t["highlight_start"] - 1 : t["highlight_end"] - 1] for t in s["text"])
out[posixpath.normpath(s["file_name"])].add("@anon:" + re.sub(r"\s+", "", text).removesuffix("as_"))
elif name:
out[posixpath.normpath(s["file_name"])].add(name)
return out
def pack_use(names, cfg_test=False):
"""The `use super::{..};` statement for `names`, formatted by rustfmt (width 120, like the repository)."""
names = sorted(names, key=lambda n: (n.lower(), n))
prefix = "#[cfg(test)]" + chr(10) if cfg_test else ""
text = (f"use super::{names[0]};" if len(names) == 1 else f"use super::{{{', '.join(names)}}};") + chr(10)
try:
done = subprocess.run(
[RUSTFMT, "--edition", "2024", "--config", "max_width=120,use_small_heuristics=Max"],
input=text, capture_output=True, text=True, check=True,
)
text = done.stdout
except (OSError, subprocess.CalledProcessError):
pass
return prefix + text
pack_use_fixed = pack_use
def depth1_fns(block):
names, depth, i = [], 0, 0
while i < len(block):
c = block[i]
if c == "{":
depth += 1
elif c == "}":
depth -= 1
elif depth == 1 and block.startswith("fn ", i) and (i == 0 or not (block[i - 1].isalnum() or block[i - 1] == "_")):
m = re.compile(IDENT).match(block, i + 3)
if m:
names.append(m.group(0))
i += 1
return names
def head_type(rest):
"""The first type name of an `impl ... for T` / `impl T` header text."""
rest = re.split(r"\bwhere\b|\{", rest)[0].strip()
if " for " in rest:
trait, ty = rest.split(" for ", 1)
else:
trait, ty = None, rest
m = re.match(rf"[&\s]*(?:dyn\s+)?(?:\w+::)*({IDENT})", ty)
t = re.match(rf"(?:\w+::)*({IDENT})", trait.strip()) if trait else None
return (m.group(1) if m else ty.strip()), (t.group(1) if t else None)
def describe(stripped):
"""What a file defines, read from its top-level statements: (inherent impls, trait impls, free fns, types)."""
inherent, traits, fns, types = collections.OrderedDict(), [], [], []
for _, head, _, _ in statements(stripped):
m = re.match(r"(?:unsafe\s+)?impl\b", head)
if m:
body = head[m.end() :].lstrip()
if body.startswith("<"):
body = body.replace("->", "--")
depth, i = 0, 0
while i < len(body):
depth += body[i] == "<"
depth -= body[i] == ">"
i += 1
if depth == 0:
break
body = body[i:]
ty, trait = head_type(body)
methods = depth1_fns(head[head.find("{") :]) if "{" in head else []
if trait:
traits.append((trait, ty))
else:
inherent.setdefault(ty, []).extend(methods)
continue
m = re.match(
rf"(?:pub(?:\s*\([^)]*\))?\s+)?(?:(?:unsafe|async|const|extern(?:\s*\"\")?)\s+)*(fn|struct|enum|trait|type)\s+({IDENT})",
head,
)
if m:
(fns if m.group(1) == "fn" else types).append(m.group(2))
return inherent, traits, fns, types
def listing(names, limit=4):
shown = ", ".join(f"`{n}`" for n in names[:limit])
return shown + (f" and {len(names) - limit} more" if len(names) > limit else "")
def submodules(stripped):
return re.findall(rf"(?m)^\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+({IDENT})\s*;", stripped)
def doc_parts(stripped):
inherent, traits, fns, types = describe(stripped)
parts = []
for ty, methods in list(inherent.items())[:2]:
parts.append(f"Methods of `{ty}`: {listing(methods)}." if methods else f"`impl {ty}`.")
if traits:
shown = ", ".join(f"`{t} for {ty}`" for t, ty in traits[:2])
parts.append(f"Implements {shown}" + (f" and {len(traits) - 2} more." if len(traits) > 2 else "."))
if fns:
parts.append(f"Functions: {listing(fns)}.")
if types:
parts.append(f"Defines {listing(types, 3)}.")
subs = submodules(stripped)
if subs and not parts:
parts.append(f"Groups the submodules {listing(subs, 3)}.")
return parts or ["Items of the parent module."]
def doc_lines(stripped, parent_name, prose):
"""At most two `//!` lines of at most 120 columns: what the file holds, then why it is a file of its own."""
limit = WIDTH - 4
lines, cur = [], ""
for part in doc_parts(stripped):
if cur and len(cur) + 1 + len(part) > limit:
lines.append(cur)
cur = ""
cur = (cur + " " + part).strip() if len(part) <= limit else (cur or part[: limit - 3] + "...")
if len(lines) == 2:
break
if cur and len(lines) < 2:
lines.append(cur)
lines = lines[:2]
if len(lines) == 1:
second = prose or f"Split out of `{parent_name}` to keep its files under the line limit."
lines.append(second if len(second) <= limit else second[: limit - 3] + "...")
return ["//! " + ln for ln in lines]
ITEM_START = re.compile(r"\s*(impl|fn|struct|enum|trait|type|const|static|mod)\s+(\S+?)(\s+\(\d+\))?\s*([,.])")
def header_prose(block):
"""The human sentence after the generated item list of a 'Moved out of the parent module' header, or None."""
m = re.match(r"Moved out of the parent (?:module|file) by STRA-338(?:\s*:\s*)?", block)
rest = block[m.end() :] if m else block
while True:
item = ITEM_START.match(rest)
if not item:
break
rest = rest[item.end() :]
if item.group(4) == ".":
break
rest = re.sub(r"^\s*(?:\.\.\.\.?)", "", rest).strip()
rest = re.sub(r"^\(same module path as before\)\.?", "", rest).strip()
return rest if len(rest) > 12 and not re.match(r"^(impl|fn)\s", rest) else None
def new_header(text, stripped, parent_name, is_tests):
m = HEADER_RE.match(text)
if not m or "Moved out of the parent" not in m.group(1):
return text
block = " ".join(l[3:].strip() for l in m.group(1).splitlines())
prose = header_prose(block)
if is_tests:
lines = [f"//! Unit tests of `{parent_name}`."] + ([f"//! {prose}"] if prose else [])
else:
lines = doc_lines(stripped, parent_name, prose)
return chr(10).join(lines) + chr(10) + text[m.end() :]
INLINE_ARG = re.compile(r"\{(" + IDENT + r")(?::[^}]*)?\}")
def tokens_of(stripped, raw=""):
"""Identifiers in the stripped code, plus the `{name}` inline arguments of format strings (blanked in `stripped`)."""
return set(re.findall(IDENT, stripped)) | set(INLINE_ARG.findall(raw))
class Plan:
def __init__(self, wt, crate_dir):
self.wt = pathlib.Path(wt)
self.crate = Crate(crate_dir)
self.texts = {f: m.text for f, m in self.crate.by_file.items()}
self.skipped = {}
self._macro_cache = {}
self.imports = {} # file -> {name: 'normal' | 'test'}
self.cfgs = {} # file -> {name: cfg attribute text the name is declared under in the parent}
def candidates(self):
return [f for f, t in self.texts.items() if GLOB_RE.search(t) and self.crate.by_file[f].parent is not None]
def skip_reason(self, f):
mod = self.crate.by_file[f]
decl = mod.parent.decl_attrs.get(mod.name, "")
forced = f.name in os.environ.get("FORCE_FILES", "").split(",") # the platform-only code is checked by hand afterwards
if not forced and (PLATFORM_CFG.search(normalize_cfg(decl)) or PLATFORM_CFG.search(normalize_cfg(self.texts[f]))):
return "platform cfg"
if f.name == "tests.rs" or f.name.endswith("_tests.rs"):
return "test module"
if self.crate.names(mod.parent, True) is OPAQUE:
return "opaque glob in the parent chain"
return None
def is_test_only(self, f):
"""A file that only the test build compiles: `tests.rs`, `*_tests.rs`, or declared under `#[cfg(test)]`."""
if "tests" in f.parts:
return True
mod = self.crate.by_file[f]
while mod is not None:
decl = mod.parent.decl_attrs.get(mod.name, "") if mod.parent else ""
if mod.file.name == "tests.rs" or mod.file.name.endswith("_tests.rs") or "cfg(test)" in decl:
return True
mod = mod.parent
return False
def blocked_reason(self, f):
return "names under mixed or platform cfg in the parent chain" if f in self.blocked else None
def extra_requirements(self):
"""{module file: names other files import from it by path (`super::X`, `crate::a::X`, `a::X`)}."""
extra = collections.defaultdict(set)
for mod in self.crate.by_file.values():
for name, _, path in mod.parsed()[1]:
if len(path) >= 2 and path[0] in ("super", "self", "crate", *mod.children):
target = self.crate.resolve_module(mod, path[:-1])
if target is not None:
extra[target.file].add(path[-1])
return extra
def inherited_macro_idents(self, mod):
"""Identifiers inside the `macro_rules!` bodies of the ancestors: an expansion below them names these in the
expanding module, whose text never mentions them."""
found, ancestor = set(), mod.parent
while ancestor is not None:
found |= self.macro_idents(ancestor.file)
ancestor = ancestor.parent
return found
def macro_idents(self, f):
if f not in self._macro_cache:
text, idents = strip_code(self.texts[f]), set()
for m in re.finditer(r"macro_rules!\s*" + IDENT + r"\s*[{(\[]", text):
close = {"{": "}", "(": ")", "[": "]"}[text[m.end() - 1]]
end = text.find(close, m.end())
depth, i = 1, m.end()
while i < len(text) and depth:
depth += text[i] == text[m.end() - 1]
depth -= text[i] == close
i += 1
idents |= set(re.findall(IDENT, text[m.end() : i]))
self._macro_cache[f] = idents
return self._macro_cache[f]
def compute_needs(self, files):
"""imports[f]: the names f (and the glob children below it) take from f's parent, over the original namespaces.
A file whose needs include a conditionally declared name is blocked (kept as a glob)."""
orig = self.crate
tokens = {f: tokens_of(strip_code(self.texts[f]), self.texts[f]) for f in orig.by_file}
extra = self.extra_requirements()
req, needs, self.blocked = {}, {}, set()
for f in sorted(orig.by_file, key=lambda f: -len(f.parts)):
mod = orig.by_file[f]
wanted = set(tokens[f]) | extra.get(f, set()) | self.inherited_macro_idents(mod)
for child in mod.children.values():
if self._globs_super(child.file):
wanted |= req.get(child.file, set()) - self._own_names(child)
req[f] = wanted
if mod.parent is None:
continue
parent_names = orig.names(mod.parent, True)
if parent_names is OPAQUE:
continue
wanted |= {n for n, (may_be_trait, _) in parent_names.items() if may_be_trait}
needs[f] = {n for n in wanted if n in parent_names and n not in self._own_names(mod)}
conditional = {n: parent_names[n][1] for n in needs[f] if parent_names[n][1]}
if f.name not in os.environ.get("FORCE_FILES", "").split(",") and any(
c == MIXED_CFG or PLATFORM_CFG.search(c) for c in conditional.values()
):
self.blocked.add(f)
elif conditional:
self.cfgs[f] = conditional
needs[f] |= {"@anon:" + p for p in orig.anon_paths(mod.parent, True) if p not in self._own_anon(mod)}
return needs
def _globs_super(self, f):
return bool(re.search(r"^\s*use super::\*;", self.texts[f], re.M))
def _own_anon(self, mod):
mod.parsed()
return {p for p, _ in mod.anon}
def _own_names(self, mod):
items, uses, _ = mod.parsed()
return set(items) | {n for n, _, _ in uses} | set(mod.children)
def apply(self, files, needs):
done = []
for f in files:
names = needs.get(f, set())
self.imports[f] = {n: "normal" for n in sorted(names)}
done.append(f)
return done
@staticmethod
def grouped_use(names, cfgs, cfg_test):
"""`use super::{..};` statements for `names`, one per cfg attribute the names are declared under."""
groups = {}
for name in names:
groups.setdefault(cfgs.get(name, ""), []).append(name)
out = ""
for cfg in sorted(groups):
statement = pack_use_fixed(groups[cfg], cfg_test)
if cfg:
# the cfg attributes of the declaration go first; `#[cfg(test)]` (added by pack_use) stays beside them
out += cfg + chr(10) + statement
else:
out += statement
return out
def render(self, f):
text = self.texts[f]
imports = self.imports.get(f)
if imports is not None:
normal = [n for n, k in imports.items() if k == "normal"]
test = [n for n, k in imports.items() if k == "test"]
residual = [n for n, k in imports.items() if k == "residual"]
anon_normal = [n for n in normal if n.startswith("@anon:")]
anon_test = [n for n in test if n.startswith("@anon:")]
normal = [n for n in normal if not n.startswith("@anon:")]
test = [n for n in test if not n.startswith("@anon:")]
cfgs = self.cfgs.get(f, {})
block = "".join(f"use {n[6:]} as _;" + chr(10) for n in anon_normal)
block += "".join("#[cfg(test)]" + chr(10) + f"use {n[6:]} as _;" + chr(10) for n in anon_test)
block += self.grouped_use(normal, cfgs, False) + self.grouped_use(test, cfgs, True)
if residual:
note = "// used only with some cargo features of this crate" + chr(10)
block += note + "#[allow(unused_imports)]" + chr(10) + self.grouped_use(residual, cfgs, False)
if getattr(self, "prune", False):
matches = list(USE_SUPER_RE.finditer(text))
for index in reversed(range(len(matches))):
m = matches[index]
text = text[: m.start()] + (block if index == 0 else "") + text[m.end() :]
else:
text = GLOB_RE.sub(lambda _: block, text, count=1)
mod = self.crate.by_file[f]
parent = mod.parent.name if mod.parent else "crate"
stripped = strip_code(text)
return new_header(text, stripped, parent, f.name == "tests.rs")
def write(self):
for f in self.texts:
text = self.render(f)
# compare with what is on disk: a file given back its glob must overwrite the explicit list written before
if text != open(f, encoding="utf-8", newline="").read():
with open(f, "w", encoding="utf-8", newline=chr(10)) as handle:
handle.write(text)
def package_args(package, features_all):
return f"-p {package}" + (" --all-features" if features_all else "")
def check_round(wt, package, configs):
"""(errors {file: set}, flagged_a {file: set}, flagged_b {file: set}) over all feature configs."""
errors = collections.defaultdict(set)
a_flags, b_flags = [], []
for i, feat in enumerate(configs):
base = f"-p {package}" + (" --all-features" if feat else "")
a = run_cargo(wt, f"{base} --lib --bins", f"a{i}.json")
b = run_cargo(wt, f"{base} --tests", f"b{i}.json")
for ms in (a, b):
for k, v in flagged(ms, "errors").items():
errors[k] |= v
a_flags.append(flagged(a, "unused"))
b_flags.append(flagged(b, "unused"))
return errors, a_flags, b_flags
def main():
wt, crate_dir, package = sys.argv[1:4]
features = "--features-all" in sys.argv
dry = "--dry-run" in sys.argv
plan = Plan(wt, crate_dir)
if "--headers-only" in sys.argv:
plan.write()
print(f"{package}: headers rewritten, imports untouched", flush=True)
return
todo, skipped = [], {}
if "--prune" in sys.argv:
plan.prune = True
for f, text in plan.texts.items():
names = {}
for m in USE_SUPER_RE.finditer(text):
text0 = m.group(0)
cfg_lines = [ln for ln in text0.splitlines() if ln.startswith("#[cfg(")]
kind = "residual" if text0.startswith("// used only") else "normal"
cfg = "\n".join(cfg_lines)
if cfg == "#[cfg(test)]":
kind, cfg = ("test" if kind == "normal" else kind), ""
for name in re.findall(IDENT, m.group(0).split("use super::", 1)[1]):
names[name] = kind
if cfg:
plan.cfgs.setdefault(f, {})[name] = cfg
if names:
plan.imports[f] = names
todo.append(f)
cands = todo
else:
cands = plan.candidates()
excluded = {n for n in os.environ.get("EXCLUDE", "").split(",") if n}
src = pathlib.Path(crate_dir).resolve() / "src"
for f in cands:
reason = plan.skip_reason(f)
if not reason and f.relative_to(src).parts[0].removesuffix(".rs") in excluded:
reason = "excluded by hand (a glob source the tool cannot trace)"
(skipped.__setitem__(f, reason) if reason else todo.append(f))
needs = plan.compute_needs(todo)
for f in list(todo):
reason = plan.blocked_reason(f)
if reason:
todo.remove(f)
skipped[f] = reason
plan.apply(todo, needs)
print(f"{package}: {len(cands)} glob files, {len(todo)} to expand, {len(skipped)} skipped", flush=True)
for reason, n in collections.Counter(skipped.values()).items():
print(f" skipped {n}: {reason}")
if dry:
return
original = dict(plan.texts)
plan.write()
configs = [True] if features else [False]
wtp = pathlib.Path(wt)
rel = lambda f: f.resolve().relative_to(wtp.resolve()).as_posix()
for round_no in range(1, 11):
errors, a_flags, b_flags = check_round(wt, package, configs)
print(f"round {round_no}: {sum(len(v) for v in errors.values())} errors in {len(errors)} files", flush=True)
if errors:
by_rel = {rel(f): f for f in plan.crate.by_file}
revert = set()
for r in errors:
f = by_rel.get(r)
if f is None:
continue
if f in todo:
revert.add(f)
ancestor = plan.crate.by_file[f].parent
while ancestor is not None:
if ancestor.file in todo:
revert.add(ancestor.file)
ancestor = ancestor.parent
if not revert:
# the cause is not in the erroring file or above it: give the whole top-level module back its globs
src = pathlib.Path(crate_dir).resolve() / "src"
def top_level(path):
parts = path.resolve().relative_to(src).parts
return parts[0].removesuffix(".rs") if parts else ""
tops = {top_level(by_rel[r]) for r in errors if r in by_rel}
revert = {f for f in todo if top_level(f) in tops}
if not revert:
print("FAILED: errors outside the expanded files, crate restored:", dict(list(errors.items())[:5]))
for f, text in original.items():
with open(f, "w", encoding="utf-8", newline=chr(10)) as handle:
handle.write(text)
return
for f in sorted(revert):
print(" revert to glob:", rel(f), sorted(errors.get(rel(f), ["(parent of an erroring file)"]))[:2])
plan.imports.pop(f, None)
todo.remove(f)
skipped[f] = "needs manual imports"
plan.write()
continue
changed = False
for f in todo:
imp = plan.imports.get(f, {})
r = rel(f)
for name in list(imp):
test_only = plan.is_test_only(f)
a_unused = test_only or all(name in fl.get(r, ()) for fl in a_flags)
b_unused = all(name in fl.get(r, ()) for fl in b_flags)
test_cfg = re.search(r"\btest\b", plan.cfgs.get(f, {}).get(name, "")) is not None
if (a_unused or imp[name] == "test" or test_cfg) and b_unused: # compiled by the test build only
del imp[name]
changed = True
elif a_unused and not test_only and imp[name] == "normal":
imp[name] = "test"
changed = True
plan.write()
if not changed:
break
if features:
default_errors, a_default, b_default = check_round(wt, package, [False])
if default_errors:
print("WARNING: errors in the default feature set:", dict(list(default_errors.items())[:5]), flush=True)
moved = 0
for f in todo:
r = rel(f)
for name, kind in list(plan.imports.get(f, {}).items()):
if kind != "residual" and any(name in fl.get(r, ()) for fl in a_default + b_default):
plan.imports[f][name] = "residual"
moved += 1
plan.write()
print(f"{moved} imports used only with some features kept under a narrow allow", flush=True)
left = {f: r for f, r in skipped.items()}
print(json.dumps({rel(f): r for f, r in left.items()}, indent=0)[:3000])
WORK.mkdir(parents=True, exist_ok=True)
(WORK / f"skipped_{package}.json").write_text(json.dumps({rel(f): r for f, r in left.items()}, indent=0))
if __name__ == "__main__":
main()