Files
leleka/scripts/dev/explicit_imports.py
T

918 lines
42 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
import time
sys.path.insert(0, str(pathlib.Path(__file__).parent))
from rust_modtree import IDENT, ITEM_RE, 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"(?<!\]\n)^(?:#\[allow\(unused_imports\)\]\s*\n)?use super::\*;[ \t]*\n", re.M)
INTRINSIC = re.compile(
r"^(?:_mm|_MM_|_CMP_|_SIDD_|_XCR|__m(?:128|256|512)|__cpuid|CpuidResult|_pdep|_pext|_mulx|_tzcnt|_lzcnt|_popcnt"
r"|_bzhi|_bextr|_blsr|_blsi|_blsmsk|_xgetbv|_rdtsc|_cvt|_addcarry|_subborrow|_andn)"
)
PAIR_RE = re.compile(r"^#\[allow\(unused_imports\)\]\s*\nuse super::\*;", re.M)
USE_SUPER_RE = re.compile(r"(?m)^(?:// used only with some cargo features[^\n]*\n(?:#\[cfg\([^\n]*\)\]\n)?#\[allow\(unused_imports\)\]\n)?(?:#\[cfg\(test\)\]\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))"
)
# the gate every driver module shares: it holds on both build hosts, so it does not make a file platform-specific
COMMON_GATE = re.compile(r'any\(\s*target_os\s*=\s*"linux"\s*,\s*target_os\s*=\s*"windows"\s*\)')
def _cfg_value(expr):
"""Three-valued value of a cfg expression when `test` is off and every other predicate is unknown: False, True or None."""
expr = expr.strip()
m = re.match(r"^(all|any|not)\((.*)\)$", expr, re.S)
if not m:
return False if expr == "test" else None
parts, depth, cur = [], 0, ""
for c in m.group(2):
depth += c == "("
depth -= c == ")"
if c == "," and depth == 0:
parts.append(cur)
cur = ""
else:
cur += c
if cur.strip():
parts.append(cur)
values = [_cfg_value(p) for p in parts]
if m.group(1) == "not":
return None if values[0] is None else not values[0]
if m.group(1) == "all":
return False if False in values else (None if None in values else True)
return True if True in values else (None if None in values else False)
def cfg_false_without_test(attrs):
"""True when a `#[cfg(...)]` among `attrs` is false whenever `test` is off: the module only exists in test builds."""
return any(_cfg_value(expr) is False for expr in cfg_exprs(attrs))
def is_platform(text):
"""True when `text` has a cfg that differs between Linux and Windows or between CPU architectures."""
return bool(PLATFORM_CFG.search(COMMON_GATE.sub("", text)))
WIDTH = 120
RUSTFMT = shutil.which("rustfmt") or "rustfmt"
WORK = pathlib.Path(tempfile.gettempdir()) / "explicit-imports"
def wait_for_gpu_idle(wt):
"""The laptop is also the GPU test machine: no build starts while its wanted flag or run lock exists."""
common = subprocess.run(
["git", "rev-parse", "--git-common-dir"], cwd=wt, capture_output=True, text=True, check=False
).stdout.strip()
git_dir = (pathlib.Path(wt) / common).resolve()
names = ("laptop-gpu-wanted.flag", "laptop-gpu-run.lock")
while any((git_dir / n).exists() for n in names):
print(" GPU stretch wanted or running: build paused", flush=True)
time.sleep(60)
if sys.platform == "win32": # little free RAM on the laptop: give the other builds up to two minutes
for _ in range(4):
free = subprocess.run(
["powershell", "-NoProfile", "-Command", "(Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory"],
capture_output=True, text=True, check=False,
).stdout.strip()
if not free.isdigit() or int(free) / 1048576 >= 2.5:
break
print(f" free RAM {int(free) / 1048576:.1f} GB < 2.5 GB: waiting", flush=True)
time.sleep(30)
def run_cargo(wt, args, out_name):
"""Messages of `cargo check --message-format=json ARGS` run in `wt`; the log is kept in WORK."""
wait_for_gpu_idle(wt)
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, pending = [], []
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":
pending.append(record["message"])
elif record.get("reason") == "compiler-artifact":
# the messages of a unit come before its artifact; the profile says whether it was built with cfg(test)
for message in pending:
message["_test_unit"] = bool(record.get("profile", {}).get("test"))
messages += pending
pending = []
return messages + pending
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, test_units_only=False):
"""{file: {name}} of the unused imports; errors as {file: count} when kind == 'errors'. With `test_units_only` the
warnings of units that were not built with cfg(test) (the library built as a dependency of an integration test) are
ignored: a name that only the tests use is unused there."""
out = collections.defaultdict(set)
for m in messages:
if test_units_only and kind != "errors" and not m.get("_test_unit"):
continue
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")(?::[^}]*)?\}")
KEYWORDS = frozenset(
"as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut "
"pub ref return self Self static struct super trait true type unsafe use where while".split()
)
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))) - KEYWORDS
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_token_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]
if f in self.crate.shared_files:
return "declared by several parents"
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_false_without_test(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
included = self.included_tokens(f, set())
if included:
defined = set()
for target in self.included_files(f, set()):
defined |= self.defined_names(target.read_text(encoding="utf-8"))
tokens[f] = (tokens[f] | included) - defined
extra = self.extra_requirements()
req, needs, self.blocked = {}, {}, set()
def depth(f): # the module depth, not the directory depth: `#[path]` puts a child beside its parent
mod, n = orig.by_file[f], 0
while mod.parent is not None:
mod, n = mod.parent, n + 1
return n
for f in sorted(orig.by_file, key=lambda f: -depth(f)):
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 test_tokens(self, f):
"""Identifiers of the items of `f` that exist only in test builds (`#[cfg(test)] mod tests { .. }`, `#[test]` fns)."""
if f not in self._test_token_cache:
out = set()
for attrs, head, start, end in statements(strip_code(self.texts[f], True)):
if cfg_false_without_test(attrs) or re.search(r"#\[test\]", attrs):
out |= set(re.findall(IDENT, head))
# a test-only child module that globs its parent takes what it needs from the imports of this file
stack = [self.crate.by_file[f]]
while stack:
for child in stack.pop().children.values():
if self.is_test_only(child.file) and child.file != f:
out |= tokens_of(strip_code(self.texts.get(child.file, child.file.read_text(encoding="utf-8"))))
stack.append(child)
self._test_token_cache[f] = out
return self._test_token_cache[f]
def included_files(self, f, seen):
"""The files `include!`d by `f`, directly or through each other."""
out = []
text = self.texts[f] if f in self.texts else f.read_text(encoding="utf-8")
for m in re.finditer(r'include!\(\s*"([^"]+)"\s*\)', text):
target = (f.parent / m.group(1)).resolve()
if target not in seen and target.is_file():
seen.add(target)
out.append(target)
out += self.included_files(target, seen)
return out
def defined_names(self, text):
"""Names the top-level items of `text` define (items, extern fns): the includer must not import them."""
names = set()
for attrs, head, _, _ in statements(strip_code(text, True)):
m = ITEM_RE.match(head)
if m:
names.add(m.group(3).removeprefix("r#"))
for _, _, name in re.findall(rf"(pub(?:\s*\([^)]*\))?\s+)?(?:safe\s+|unsafe\s+)?(fn|static)\s+(?:mut\s+)?({IDENT})", head):
names.add(name)
return names
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) - self.defined_names(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.defined_names(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):
"""Names the module declares, imports by name, or takes from its own globs other than `use super::*`."""
items, uses, globs = mod.parsed()
names = set(items) | {n for n, _, _ in uses} | set(mod.children)
for target in self.included_files(mod.file, set()): # items of an `include!`d file belong to the includer
names |= self.defined_names(target.read_text(encoding="utf-8"))
for path, _ in globs:
if path == ["super"]:
continue
target = self.crate.resolve_module(mod, path)
if target is not None:
inner = self.crate.names(target, self.crate.is_ancestor(target, mod))
if inner is not OPAQUE:
names |= set(inner)
return names
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} {feat}" if isinstance(feat, str) else 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
prune_src = (pathlib.Path(crate_dir) / "src").resolve()
for f, text in plan.texts.items():
if prune_src not in f.parents:
continue
names = {}
top = f.relative_to(prune_src).parts[0].removesuffix(".rs")
if top in {n for n in os.environ.get("EXCLUDE", "").split(",") if n} or re.search(
r"(?m)^use super::\{[^}]*[ ]as[ ]", text
):
continue # left as it is: excluded by hand, or an import with an alias
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):
try:
parts = path.resolve().relative_to(src).parts
except ValueError:
return ""
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):
kind = imp[name]
if kind == "residual":
continue
test_only = plan.is_test_only(f)
a_unused = all(name in fl.get(r, ()) for fl in a_flags)
b_unused = all(name in fl.get(r, ()) for fl in b_flags)
# The build without cfg(test) tells which names the non-test code uses. The build with cfg(test) cannot be
# trusted for a file that both builds compile: cargo prints a warning that two units share only once.
if test_only:
drop = b_unused
elif kind == "normal":
tests = plan.test_tokens(f)
# a trait is used by method calls that never write its name: keep it for the test build to judge
drop = a_unused and name not in tests and not (tests and name[:1].isupper())
if a_unused and not drop:
imp[name] = "test" # only the test code of the file uses it
changed = True
continue
else:
drop = b_unused
if drop:
if f in plan.platform_files 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
else:
del imp[name]
changed = True
plan.write()
if not changed:
break
if features:
# the smallest feature set that builds (BASE_CONFIG, for example `--features cuda-driver`), else the default one
default_errors, a_default, b_default = check_round(wt, package, [os.environ.get("BASE_CONFIG") or 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()