#!/usr/bin/env python3 """Plan and apply the rename of mechanically named Rust modules (STRA-338). A split leaves files called `impl_.rs`, `_fn.rs` or `_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 ;` declaration, the `#[path = ".rs"]` attribute and the path segments `::` 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[\w:]+)(?:<[^{]*?>)?\s+for\s+)?(?P[\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"(?