Files
leleka/scripts/dev/unglob_by_errors.py

248 lines
11 KiB
Python

"""Replace `use super::*;` by explicit imports, guided by the compiler's errors (STRA-338 stage 10, `glob-super-import`).
Usage: python scripts/dev/unglob_by_errors.py WORKTREE CRATE_DIR PACKAGE [--include-tests] [--max-rounds N]
`explicit_imports.py` expands every glob file at once and gives a file back its glob when the build fails. This driver keeps
the expansion and repairs it from the compiler's messages instead, so the files that tool could not close (GPU proofs, test
modules, names behind an inner cfg) become explicit too:
* a name the file uses but does not have (`cannot find type/value/function/trait/macro X`, an `enum Result takes 2 generic
arguments` from the prelude instead of the crate alias) is added as `use super::X;`;
* `unresolved import super::X` adds X to the parent's own imports when the parent is also expanded here;
* a trait whose methods are called but is not in scope is added with the path rustc suggests;
* a name that only the test build needs gets `#[cfg(test)]`; a name no build uses is removed.
Each round is one `cargo check --lib --bins` and one `--tests` (through scripts/dev/wsl-cargo.sh on Windows). The Plan, the module
tree and the rendering are those of explicit_imports.py. Offline refactoring aid, not part of the product.
"""
import collections
import json
import pathlib
import posixpath
import re
import sys
sys.path.insert(0, str(pathlib.Path(__file__).parent))
import explicit_imports as ei # noqa: E402
IDENT = ei.IDENT
MISSING = [
re.compile(rf"cannot find (?:type|value|function|trait|macro|struct, variant or union type|tuple struct or tuple variant|"
rf"unit struct, unit variant or constant|derive macro|attribute macro|function, tuple struct or tuple variant|"
rf"value, found) `({IDENT})` in this scope"),
re.compile(rf"failed to resolve: use of undeclared (?:type|module|crate or module) `({IDENT})`"),
re.compile(rf"failed to resolve: use of unresolved module or unlinked crate `({IDENT})`"),
re.compile(rf"failed to resolve: use of undeclared type or module `({IDENT})`"),
re.compile(rf"(?:enum|struct|type alias|trait) `({IDENT})` takes \d+ generic argument"),
re.compile(rf"cannot find .*? `({IDENT})` in module"),
]
BAD_IMPORT = re.compile(r"unresolved imports? (.*)")
SUPER_NAME = re.compile(rf"`super::({IDENT})`")
TRAIT_HELP = re.compile(r"(?:trait|traits).*(?:not in scope|perhaps you want to import)")
def messages(wt, package, args, out_name):
"""compiler-message dicts of `cargo check --message-format=json` over `args`."""
return ei.run_cargo(wt, f"-p {package} {args}", out_name)
def span_file(message):
for span in message.get("spans", []):
if span.get("is_primary"):
return posixpath.normpath(span["file_name"])
return None
def missing_names(message):
text = message["message"]
for rx in MISSING:
m = rx.search(text)
if m:
return [m.group(1)]
return []
def trait_paths(message):
"""`crate::a::Trait` paths rustc suggests importing for a method call (children of an E0599)."""
found = []
for child in message.get("children", []):
if not TRAIT_HELP.search(child.get("message", "")):
continue
for span in child.get("spans", []):
replacement = span.get("suggested_replacement") or ""
for m in re.finditer(r"use ([\w:]+);", replacement):
found.append(m.group(1))
return found
def collect(msgs):
"""({file: {name}}, {file: {bad super name}}, {file: {trait path}}, {file: other error text}) of one build."""
missing, bad, traits, other = (collections.defaultdict(set) for _ in range(4))
for m in msgs:
if m["level"] != "error":
continue
f = span_file(m)
if f is None:
continue
names = missing_names(m)
paths = trait_paths(m)
bad_import = BAD_IMPORT.match(m["message"])
if names:
missing[f].update(names)
elif bad_import:
bad[f].update(SUPER_NAME.findall(bad_import.group(1)))
elif paths:
traits[f].update(paths)
else:
other[f].add(m["message"][:100])
return missing, bad, traits, other
PLATFORM_FILES = {
"backend/original_serve/runner/owner_run_steps.rs", "memory_governor/page_cache.rs",
"model_binding/weight_binding/mtp/backing.rs", "model_binding/weight_binding/mtp/mtp_weight_reads.rs",
"model_binding/weight_binding/mtp/read_expert_rows.rs", "model_binding/kar_ple_source/pinned_profile_tests.rs",
"model_binding/kar_ple_source/private_copy/inode.rs", "model_binding/kar_ple_source/private_copy/checked_reader.rs",
"model_binding/kar_ple_source/inherited_kar_archive.rs", "model_binding/kar_ple_source/load_pinned_inherited_archive.rs",
"model_binding/kar_ple_source/pinned_profile.rs", "qwen_forward/original_serve_residency/open_tier.rs",
}
def prune_existing(plan, rel):
"""Files that already carry explicit `use super::{..}` lists: their names become the seed of the prune."""
plan.prune = True
todo = []
for f, text in plan.texts.items():
names = {}
for m in ei.USE_SUPER_RE.finditer(text):
block = m.group(0)
cfg_lines = [ln for ln in block.splitlines() if ln.startswith("#[cfg(")]
cfg = chr(10).join(cfg_lines)
kind = "test" if cfg == "#[cfg(test)]" else "normal"
if cfg == "#[cfg(test)]":
cfg = ""
for name in re.findall(IDENT, block.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)
return todo
def select(plan, rel):
"""(todo, skipped, keep_all) of the glob files, by the skip rules and the --include-tests/--platform/--opaque flags."""
only = [a for a in sys.argv[4:] if not a.startswith("--") and not a.isdigit()]
todo, skipped, keep_all = [], {}, set()
for f in plan.candidates():
reason = plan.skip_reason(f)
if reason == "test module" and "--include-tests" in sys.argv:
reason = None
if reason == "platform cfg" and "--platform" in sys.argv:
reason = None
keep_all.add(f) # the other platform's code is not compiled here: unused names are reported, not removed
if reason == "opaque glob in the parent chain" and "--opaque" in sys.argv:
reason = None
if only and not any(o in rel(f) for o in only):
continue
(skipped.__setitem__(f, reason) if reason else todo.append(f))
return todo, skipped, keep_all
def main():
wt, crate_dir, package = sys.argv[1:4]
max_rounds = int(sys.argv[sys.argv.index("--max-rounds") + 1]) if "--max-rounds" in sys.argv else 12
plan = ei.Plan(wt, crate_dir)
wtp = pathlib.Path(wt).resolve()
rel = lambda f: f.resolve().relative_to(wtp).as_posix() # noqa: E731
by_rel = {rel(f): f for f in plan.crate.by_file}
only = [a for a in sys.argv[4:] if not a.startswith("--") and not a.isdigit()]
todo, skipped, keep_all = [], {}, set()
if "--prune-existing" in sys.argv:
todo = prune_existing(plan, rel)
keep_all = {f for f in todo if rel(f).split("/src/", 1)[1] in PLATFORM_FILES}
todo = [f for f in todo if f not in keep_all]
for f in keep_all:
plan.imports.pop(f, None)
else:
todo, skipped, keep_all = select(plan, rel)
needs = plan.compute_needs(todo)
plan.blocked = {f for f in plan.blocked if f in todo} # a conditional name is repaired by the build below
plan.apply(todo, needs)
for f, conditional in plan.cfgs.items(): # a name declared twice under complementary platform cfgs is always there
for n in [n for n, c in conditional.items() if "not(true)" in c or c.strip() in ("", "true")]:
del conditional[n]
print(f"{package}: {len(todo)} files to expand, {len(skipped)} skipped", flush=True)
for reason, n in collections.Counter(skipped.values()).items():
print(f" skipped {n}: {reason}", flush=True)
for round_no in range(1, max_rounds + 1):
plan.write()
a = messages(wt, package, "--lib --bins", "ug-a.json")
b = messages(wt, package, "--tests", "ug-b.json")
am, ab, at, ao = collect(a)
bm, bb, bt, bo = collect(b)
changed = 0
for f in todo:
r, imp = rel(f), plan.imports.setdefault(f, {})
wanted = (am[r], "normal"), (bm[r] - am[r], "test")
for names, kind in wanted:
for n in names:
if n not in imp:
imp[n] = kind
changed += 1
elif plan.cfgs.get(f, {}).pop(n, None) is not None: # the name is there but its cfg hides it
changed += 1
for path in at[r] | bt[r]:
key = "@anon:" + path
if key not in imp:
imp[key] = "normal" if path in at[r] else "test"
changed += 1
for n in ab[r] | bb[r]:
parent = plan.crate.by_file[f].parent
if parent is not None and parent.file in todo:
kind = "normal" if n in ab[r] else "test"
if plan.imports.setdefault(parent.file, {}).get(n) != "normal":
plan.imports[parent.file][n] = kind
changed += 1
elif n in imp:
del imp[n] # the name is not in the parent: another path is needed (listed below)
changed += 1
other = {r: v for r, v in {**ao, **bo}.items() if r in {rel(f) for f in todo}}
print(f"round {round_no}: {changed} imports added, {sum(len(v) for v in other.values())} other errors in "
f"{len(other)} files", flush=True)
if changed:
continue
if other:
for r, v in sorted(other.items())[:20]:
print(" ", r, sorted(v)[:2])
break
unused_a, unused_b = ei.flagged(a, "unused"), ei.flagged(b, "unused")
pruned = 0
for f in todo:
r, imp = rel(f), plan.imports[f]
if f in keep_all:
print(" unused here, kept:", r, sorted(set(unused_a.get(r, ())) & set(unused_b.get(r, ()))), flush=True)
continue
for name in list(imp):
a_unused = name in unused_a.get(r, ())
b_unused = name in unused_b.get(r, ())
if b_unused:
del imp[name]
pruned += 1
elif a_unused and imp[name] == "normal":
imp[name] = "test"
pruned += 1
print(f" pruned or moved to cfg(test): {pruned}", flush=True)
if not pruned:
break
plan.write()
left = [rel(f) for f in plan.texts if ei.GLOB_RE.search(open(f, encoding="utf-8").read())]
print(f"{len(left)} files still carry the glob")
ei.WORK.mkdir(parents=True, exist_ok=True)
(ei.WORK / f"unglob_{package}.json").write_text(json.dumps(left, indent=0))
if __name__ == "__main__":
main()