"""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 import time sys.path.insert(0, str(pathlib.Path(__file__).parent)) from rust_modtree import IDENT, OPAQUE, Crate, _attribute_end, _skip_balanced, cfg_exprs, statements, strip_code # noqa: E402 # the pair rustsplit leaves, or a plain glob; a glob under another attribute (`#[cfg(test)]`) is not touched GLOB_RE = re.compile(r"(?", "--") 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.platform_files = set() # platform-cfg files expanded anyway (--platform-residual): unused names stay self.platform_residual = False self._cond_index = None self._platform_cache = {} self._test_files = None self.cfg_names = collections.defaultdict(dict) # file -> {name: cfg expression its import needs} def candidates(self): src = (pathlib.Path(self.crate.root_dir) / "src").resolve() return [ f for f, t in self.texts.items() if GLOB_RE.search(t) and self.crate.by_file[f].parent is not None and src in f.parents ] def skip_reason(self, f): mod = self.crate.by_file[f] decl = mod.parent.decl_attrs.get(mod.name, "") if is_platform(decl) or is_platform(self.texts[f]): if not self.platform_residual: return "platform cfg" self.platform_files.add(f) if f.name == "tests.rs" or f.name.endswith("_tests.rs"): return "test module" if not PAIR_RE.search(self.texts[f]) and (self.is_test_only(f) or not self.counts_as_production(f)): return "test module" if self.crate.names(mod.parent, True) is OPAQUE: return "opaque glob in the parent chain" return None def counts_as_production(self, f): """Whether the architecture gate counts `f` as production code (it skips test files and test-only modules).""" if self._test_files is None: sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent)) from archcheck import measure self._measure = measure self._src = (self.wt / self.crate.root_dir / "src").resolve() if not self.crate.root_dir.is_absolute() else self.crate.root_dir / "src" self._test_files = measure.test_only_modules(self._src) return not ( self._measure.is_test_file(f, self._src) or self._measure._under_test_module(f, self._test_files) ) 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 "cfg-gated names 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} for f in orig.by_file: # `include!("file.rs")`: the included text is compiled as part of this file tokens[f] |= self.included_tokens(f, set()) 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)} if self.sees_arch_glob(mod): needs[f] |= {n for n in wanted if INTRINSIC.match(n) and n not in self._own_names(mod)} for n in sorted(needs[f]): if n in parent_names and parent_names[n][1] and not self.cond_implied(mod, n): expr = self.cond_expression(n) if expr is None: self.blocked.add(f) else: self.cfg_names[f][n] = expr needs[f] |= {"@anon:" + p for p in orig.anon_paths(mod.parent, True) if p not in self._own_anon(mod)} return needs def platform_tokens(self, f): """Identifiers of the items of `f` that sit under a platform cfg (all of them when the module itself does): the names that only code of another target uses.""" if f in self._platform_cache: return self._platform_cache[f] mod = self.crate.by_file[f] decl = mod.parent.decl_attrs.get(mod.name, "") if mod.parent else "" stripped = strip_code(self.texts[f], True) out = set() if is_platform(decl): out = set(re.findall(IDENT, stripped)) for m in re.finditer(r"#\[cfg\(", stripped): end = _attribute_end(stripped, m.start()) if not is_platform(stripped[m.start() : end]): continue j = end while j < len(stripped): c = stripped[j] if c == "{": j = _skip_balanced(stripped, j, "{", "}") break if c == ";": j += 1 break j += 1 out |= set(re.findall(IDENT, stripped[end:j])) self._platform_cache[f] = out return out def included_tokens(self, f, seen): out = set() for m in re.finditer(r'include!\(\s*"([^"]+)"\s*\)', self.texts[f]): target = (f.parent / m.group(1)).resolve() if target in seen or not target.is_file(): continue seen.add(target) text = target.read_text(encoding="utf-8") out |= tokens_of(strip_code(text), text) out |= self.included_tokens_text(target, text, seen) return out def included_tokens_text(self, target, text, seen): out = set() for m in re.finditer(r'include!\(\s*"([^"]+)"\s*\)', text): inner = (target.parent / m.group(1)).resolve() if inner not in seen and inner.is_file(): seen.add(inner) body = inner.read_text(encoding="utf-8") out |= tokens_of(strip_code(body), body) | self.included_tokens_text(inner, body, seen) return out def sees_arch_glob(self, mod): """Whether a `use std::arch::x86_64::*;` sits on the module's parent chain (its intrinsics come through `super`).""" ancestor = mod.parent while ancestor is not None: self.crate.names(ancestor, True) if ancestor.arch_glob: return True ancestor = ancestor.parent return False def cond_declarations(self, name): """[set of cfg expressions] of every conditional declaration of `name` in the crate.""" if self._cond_index is None: self._cond_index = collections.defaultdict(list) for mod in self.crate.by_file.values(): mod.parsed() for n, decls in mod.cond_cfgs.items(): self._cond_index[n] += decls return self._cond_index.get(name, []) def cond_expression(self, name): """The cfg expression under which `name` exists in the parent: its declaration's attributes (all of them), or `any(...)` of several declarations; None when unknown.""" decls = self.cond_declarations(name) if not decls: return None parts = [] for decl in decls: expr = "all(" + ", ".join(sorted(decl)) + ")" if len(decl) > 1 else next(iter(decl)) if decl else None if expr is None: return None if expr not in parts: parts.append(expr) return parts[0] if len(parts) == 1 else "any(" + ", ".join(parts) + ")" def chain_cfgs(self, mod): """The cfg expressions of the `mod x;` declarations from the crate root down to `mod`.""" out = set() while mod is not None and mod.parent is not None: out |= cfg_exprs(mod.parent.decl_attrs.get(mod.name, "")) mod = mod.parent return out def cond_implied(self, mod, name): """True when a module compiled only under the cfg of one declaration of `name` may import it without a cfg: every cfg expression of that declaration is on the module's declaration chain (or, when it names cargo features, every feature of it is: the platform terms of a feature gate are shared by the whole tree).""" chain = self.chain_cfgs(mod) chain_features = set(re.findall(r'feature="([^"]+)"', " ".join(chain))) for decl in self.cond_declarations(name): if decl <= chain: return True features = set(re.findall(r'feature="([^"]+)"', " ".join(decl))) if features and features <= chain_features and "not(" not in " ".join(decl): return True return False 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 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:")] 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) gated = self.cfg_names.get(f, {}) plain = lambda names: [n for n in names if n not in gated] block += (pack_use_fixed(plain(normal)) if plain(normal) else "") + ( pack_use_fixed(plain(test), True) if plain(test) else "" ) for expr in sorted(set(gated.values())): for names, prefix in ((normal, f"#[cfg({expr})]"), (test, f"#[cfg(all(test, {expr}))]")): group = [n for n in names if gated.get(n) == expr] if group: block += prefix + chr(10) + pack_use_fixed(group) if residual: note = "// used only with some cargo features or targets of this crate" + chr(10) block += note + "#[allow(unused_imports)]" + chr(10) + pack_use_fixed(plain(residual)) for expr in sorted(set(gated.values())): group = [n for n in residual if gated.get(n) == expr] if group: block += note + f"#[cfg({expr})]" + chr(10) + "#[allow(unused_imports)]" + chr(10) + pack_use_fixed(group) 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) if not block: # nothing left to import: drop the blank line the removed pair leaves behind as well text = re.sub(chr(10) * 3 + "+", chr(10) * 2, 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) if text != self.texts[f]: 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) plan.platform_residual = "--platform-residual" in sys.argv 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) kind = "residual" if text0.startswith("// used only") else "test" if "#[cfg(test)]" in text0 else "normal" for name in re.findall(IDENT, m.group(0).split("use super::", 1)[1]): names[name] = kind 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} only = {n for n in os.environ.get("ONLY", "").split(",") if n} # top-level modules to expand; the rest keep their globs src = pathlib.Path(crate_dir).resolve() / "src" for f in cands: reason = plan.skip_reason(f) top = f.relative_to(src).parts[0].removesuffix(".rs") if not reason and top in excluded: reason = "excluded by hand (a glob source the tool cannot trace)" if not reason and only and top not in only: reason = "not in this batch (ONLY)" (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) if a_unused and b_unused and f in plan.platform_files and imp[name] != "residual" and name in plan.platform_tokens(f) and name[:1].isupper(): imp[name] = "residual" # probably used by code of another target: keep, under a narrow allow changed = True elif a_unused and b_unused and imp[name] != "residual": 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) for f in plan.platform_files: low = sorted(n for n in plan.platform_tokens(f) if n in plan.crate.by_file[f].parsed()[0] or n in plan.crate.by_file[f].children) if low: print(" REVIEW platform-cfg file", rel(f)) 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()