git mv of the files and of the module directories next to them, mod declarations, #[path] attributes and the paths that name the modules, rewritten by scripts/dev/rename_mechanical.py from a reviewed name table. Two files lost one to two lines so the 400-line limit holds again (qsa_prompt_index, original_verify_expert_probe). limits-baseline.json: test fn_lines 0 -> 1 is --allow-increase for crates/deploy builtin_profiles.rs:149 (37 lines, the speed-vs-strata session's file, not touched here); the prod params census falls 108 -> 1 (w_launch, extern C ABI). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
292 lines
12 KiB
Python
292 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""Plan and apply the rename of mechanically named Rust modules (STRA-338).
|
|
|
|
A split leaves files called `impl_<type>.rs`, `<fn>_fn.rs` or `<name>_2.rs`. The architecture gate (`mechanical_names`
|
|
in architecture.json) wants none of them. This tool
|
|
|
|
plan reads the files the gate lists, looks at the items each one holds and writes a JSON table
|
|
{old path: {"new": new file name, "items": ..., "why": ...}} for a human or an agent to review;
|
|
apply renames every file (and the module directory next to it) with `git mv`, then rewrites the `mod <old>;`
|
|
declaration, the `#[path = "<old>.rs"]` attribute and the path segments `<old>::` that name the module in
|
|
the declaring file and in everything below the parent module.
|
|
|
|
The name says what the module holds: `impl Type { fn a }` becomes `type_a`, `impl Trait for Type` becomes
|
|
`type_trait`, `fn name` in `name_fn.rs` becomes `name`. A clash inside one directory gets a descriptive word, never a number.
|
|
Files are edited as bytes so CRLF checkouts stay CRLF.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
sys.path.insert(0, str(ROOT / "scripts"))
|
|
from dev.rustsplit.names import distinct # noqa: E402
|
|
|
|
MAX_NAME = 46
|
|
ITEM = re.compile(
|
|
r"^(?:pub(?:\([^)]*\))?\s+)?(?:unsafe\s+)?(?:const\s+)?(?:async\s+)?(?:extern\s+\"C\"\s+)?"
|
|
r"(fn|struct|enum|trait|type|const|static|union)\s+(\w+)"
|
|
)
|
|
IMPL = re.compile(r"^impl(?:<[^>{]*>)?\s+(?:(?P<tr>[\w:]+)(?:<[^{]*?>)?\s+for\s+)?(?P<ty>[\w:]+)")
|
|
METHOD = re.compile(r"^ (?:pub(?:\([^)]*\))?\s+)?(?:unsafe\s+)?(?:const\s+)?(?:async\s+)?(?:extern\s+\"C\"\s+)?fn\s+(\w+)")
|
|
KEYWORDS = {"as", "break", "const", "continue", "crate", "else", "enum", "extern", "fn", "for", "if", "impl", "in", "let",
|
|
"loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "static", "struct", "super", "trait",
|
|
"type", "unsafe", "use", "where", "while", "async", "await", "dyn", "abstract", "become", "box", "do", "final",
|
|
"macro", "override", "priv", "typeof", "unsized", "virtual", "yield", "try"}
|
|
|
|
|
|
def snake(ident):
|
|
"""`MtpInputPrefix` -> `mtp_input_prefix`; an already lower-case identifier stays as it is."""
|
|
ident = ident.split("::")[-1]
|
|
if ident.islower() or "_" in ident:
|
|
return ident.lower()
|
|
out = re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", ident)
|
|
return out.lower()
|
|
|
|
|
|
def parse(text):
|
|
"""Top-level items of a file: ([(kind, name)], [(type, trait or None, [methods])])."""
|
|
items, impls, current = [], [], None
|
|
for line in text.splitlines():
|
|
if not line or line[0] in " \t}/#":
|
|
m = METHOD.match(line)
|
|
if m and current is not None:
|
|
current[2].append(m.group(1))
|
|
continue
|
|
i = IMPL.match(line)
|
|
if i:
|
|
current = (i.group("ty"), i.group("tr"), [])
|
|
impls.append(current)
|
|
continue
|
|
current = None
|
|
m = ITEM.match(line)
|
|
if m:
|
|
items.append((m.group(1), m.group(2)))
|
|
return items, impls
|
|
|
|
|
|
def common_prefix_word(names):
|
|
"""The leading word shared by every name (`read` for read_a, read_b), or None."""
|
|
words = [n.split("_")[0] for n in names]
|
|
return words[0] if len(set(words)) == 1 and len(names) > 1 else None
|
|
|
|
|
|
def methods_part(methods):
|
|
"""A short phrase for a list of methods: the method, two methods, or the verb they share."""
|
|
if len(methods) == 1:
|
|
return methods[0]
|
|
if len(methods) == 2:
|
|
return f"{methods[0]}_and_{methods[1]}"
|
|
word = common_prefix_word(methods)
|
|
return f"{word}_group" if word else methods[0]
|
|
|
|
|
|
def owner_of(stem, impls):
|
|
"""The type an `impl_*` file is about: the impl'd type whose lower-case name appears in the stem, else the first."""
|
|
squashed = stem.replace("_", "")
|
|
for ty, _tr, _m in impls:
|
|
if ty.split("::")[-1].lower() in squashed:
|
|
return ty
|
|
return impls[0][0]
|
|
|
|
|
|
def propose(path, text, siblings):
|
|
"""(new stem, reason) for one mechanically named file."""
|
|
stem = path.stem
|
|
items, impls = parse(text)
|
|
fns = [n for k, n in items if k == "fn"]
|
|
types = [n for k, n in items if k in ("struct", "enum", "trait", "type", "union")]
|
|
base = re.sub(r"(_[0-9]+)+$", "", stem)
|
|
if impls and (stem.startswith("impl_") or not fns):
|
|
ty = owner_of(stem, impls)
|
|
owner = snake(ty)
|
|
mine = [i for i in impls if i[0] == ty]
|
|
traits = sorted({snake(i[1]) for i in mine if i[1]})
|
|
inherent = [m for i in mine if not i[1] for m in i[2]]
|
|
if traits and not inherent:
|
|
return f"{owner}_{'_'.join(traits)}", "trait impl"
|
|
numbered = stem != base
|
|
if not numbered and stem == f"impl_{ty.split('::')[-1].lower()}" and owner not in siblings:
|
|
return owner, "the inherent impl of the type"
|
|
if inherent:
|
|
return f"{owner}_{methods_part(inherent)}", "methods of the type"
|
|
return f"{owner}_impls", "impl blocks of the type"
|
|
if stem.endswith("_fn") or stem.endswith("_fns"):
|
|
cand = re.sub(r"_fns?$", "", stem)
|
|
if cand and cand not in KEYWORDS:
|
|
return cand, "free function named by the split"
|
|
if fns and not impls:
|
|
return (methods_part(fns[:2]) if len(fns) > 1 else fns[0]), "free functions"
|
|
if types:
|
|
return snake(types[0]), "type definition"
|
|
if impls:
|
|
ty, tr, methods = impls[0]
|
|
return f"{snake(ty)}_{methods_part(methods) if methods else 'impls'}", "impl block with fns"
|
|
header = re.match(r"//! Moved out of the parent module by STRA-338: impl (?:\w+ for )?(\w+)", text)
|
|
if stem.startswith("impl_") and header:
|
|
return snake(header.group(1)), "hub of the type's impl modules"
|
|
return base or stem, "kept the stem without its number"
|
|
|
|
|
|
def cut_at_word(name, limit):
|
|
"""`name` shortened to `limit` characters at a word boundary."""
|
|
if len(name) <= limit:
|
|
return name
|
|
return name[:limit].rsplit("_", 1)[0] if "_" in name[:limit] else name[:limit]
|
|
|
|
|
|
def mechanical_files(patterns):
|
|
out = []
|
|
for p in sorted((ROOT / "crates").rglob("*.rs")):
|
|
name = p.name
|
|
if any(re.search(rx, name) for rx in patterns):
|
|
out.append(p)
|
|
return out
|
|
|
|
|
|
def load_patterns():
|
|
arch = json.loads((ROOT / "architecture.json").read_text())["mechanical_names"]
|
|
allow = [re.compile(a) for a in arch.get("allow", [])]
|
|
pats = arch["patterns"]
|
|
return [p for p in pats], allow
|
|
|
|
|
|
def plan(out_path):
|
|
pats, allow = load_patterns()
|
|
files = [f for f in mechanical_files(pats) if not any(a.search(f.name) for a in allow)]
|
|
decided = {}
|
|
used_per_dir = {}
|
|
for f in files:
|
|
directory = f.parent
|
|
used = used_per_dir.setdefault(
|
|
directory, {c.stem for c in directory.glob("*.rs") if c not in files} | {c.name for c in directory.iterdir() if c.is_dir()}
|
|
)
|
|
parent_mod = directory.name
|
|
text = f.read_text(encoding="utf-8", errors="replace")
|
|
stem, why = propose(f, text, used)
|
|
stem = re.sub(r"[^a-z0-9_]", "_", stem.lower()).strip("_") or "module"
|
|
if stem in KEYWORDS or stem == parent_mod:
|
|
stem = f"{stem}_items" if stem != parent_mod else f"{stem}_methods"
|
|
new = distinct(cut_at_word(stem, MAX_NAME), used, MAX_NAME)
|
|
items, impls = parse(text)
|
|
decided[str(f.relative_to(ROOT)).replace("\\", "/")] = {
|
|
"new": new + ".rs",
|
|
"why": why,
|
|
"items": [f"{k} {n}" for k, n in items][:6] + [f"impl {i[1] + ' for ' if i[1] else ''}{i[0]} [{', '.join(i[2][:12])}]" for i in impls][:4],
|
|
}
|
|
Path(out_path).write_text(json.dumps(decided, indent=1, sort_keys=True))
|
|
print(f"{len(decided)} files planned -> {out_path}")
|
|
|
|
|
|
def git(*args):
|
|
subprocess.run(["git", "-C", str(ROOT), *args], check=True)
|
|
|
|
|
|
def replace_bytes(path, old, new):
|
|
data = path.read_bytes()
|
|
pattern = re.compile(rb"(?<![A-Za-z0-9_])" + re.escape(old.encode()) + rb"(?![A-Za-z0-9_])")
|
|
changed = pattern.sub(new.encode(), data)
|
|
if changed != data:
|
|
path.write_bytes(changed)
|
|
return True
|
|
return False
|
|
|
|
|
|
def parent_module_file(directory):
|
|
"""The file that declares the modules living in `directory` (dir.rs next to it, or mod.rs/lib.rs inside)."""
|
|
for cand in (directory.parent / f"{directory.name}.rs", directory / "mod.rs", directory / "lib.rs", directory / "main.rs"):
|
|
if cand.exists():
|
|
return cand
|
|
return None
|
|
|
|
|
|
def validate(table):
|
|
"""Every new name is a valid snake_case module name, free in its directory and different from the directory name."""
|
|
problems, taken = [], {}
|
|
for old_rel, entry in table.items():
|
|
directory = (ROOT / old_rel).parent
|
|
stem = entry["new"][:-3]
|
|
if not re.fullmatch(r"[a-z][a-z0-9_]*", stem) or stem in KEYWORDS:
|
|
problems.append(f"{old_rel}: `{stem}` is not a module name")
|
|
if stem == directory.name:
|
|
problems.append(f"{old_rel}: `{stem}` repeats the directory name")
|
|
key = (directory, stem)
|
|
if key in taken:
|
|
problems.append(f"{old_rel}: `{stem}` is also the new name of {taken[key]}")
|
|
taken[key] = old_rel
|
|
renamed = {ROOT / k for k in table}
|
|
for (directory, stem), old_rel in taken.items():
|
|
clash = directory / f"{stem}.rs"
|
|
if clash.exists() and clash not in renamed:
|
|
problems.append(f"{old_rel}: `{stem}.rs` already exists")
|
|
if (directory / stem).is_dir() and (directory / f"{stem}.rs") not in renamed and not (ROOT / old_rel).with_suffix("").is_dir():
|
|
problems.append(f"{old_rel}: directory `{stem}` already exists")
|
|
return problems
|
|
|
|
|
|
def apply(plan_path, override_paths):
|
|
table = json.loads(Path(plan_path).read_text())
|
|
for path in override_paths:
|
|
for old_rel, new_name in json.loads(Path(path).read_text()).items():
|
|
table[old_rel]["new"] = new_name
|
|
problems = validate(table)
|
|
if problems:
|
|
print("\n".join(problems))
|
|
sys.exit(1)
|
|
# deepest first: renaming a directory moves the files below it, so their own paths must already be done
|
|
for old_rel, entry in sorted(table.items(), key=lambda kv: (-kv[0].count("/"), kv[0])):
|
|
old = ROOT / old_rel
|
|
if not old.exists():
|
|
print(f"skip (gone): {old_rel}")
|
|
continue
|
|
new = old.with_name(entry["new"])
|
|
old_stem, new_stem = old.stem, new.stem
|
|
git("mv", str(old), str(new))
|
|
old_dir = old.with_suffix("")
|
|
if old_dir.is_dir():
|
|
git("mv", str(old_dir), str(new.with_suffix("")))
|
|
declaring = parent_module_file(old.parent)
|
|
scope = [declaring] if declaring else []
|
|
# a module declared with #[path] from a sibling file also names its file in the attribute
|
|
for sibling in old.parent.glob("*.rs"):
|
|
if replace_bytes(sibling, old.name, new.name):
|
|
scope.append(sibling)
|
|
for source in {s for s in scope if s}:
|
|
replace_bytes(source, old_stem, new_stem)
|
|
for source in old.parent.rglob("*.rs"):
|
|
replace_bytes(source, old_stem, new_stem)
|
|
print(f"{len(table)} renamed")
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
p = sub.add_parser("plan")
|
|
p.add_argument("out")
|
|
a = sub.add_parser("apply")
|
|
a.add_argument("plan")
|
|
a.add_argument("--overrides", nargs="*", default=[], help="JSON files {old path: new file name} that replace plan names")
|
|
c = sub.add_parser("check")
|
|
c.add_argument("plan")
|
|
c.add_argument("--overrides", nargs="*", default=[])
|
|
args = ap.parse_args()
|
|
if args.cmd == "plan":
|
|
plan(args.out)
|
|
elif args.cmd == "apply":
|
|
apply(args.plan, args.overrides)
|
|
else:
|
|
table = json.loads(Path(args.plan).read_text())
|
|
for path in args.overrides:
|
|
for old_rel, new_name in json.loads(Path(path).read_text()).items():
|
|
table[old_rel]["new"] = new_name
|
|
problems = validate(table)
|
|
print("\n".join(problems) or "ok")
|
|
sys.exit(1 if problems else 0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|