STRA-338 S17: inline modules of the cuda-driver root and FFI files move to files, lib.rs and ffi/enabled.rs split by responsibility
lib.rs 3508 -> 938 lines, ffi.rs 1897 -> small, qwen_dispatch.rs 2003 and qwen_ffi.rs 1696 lose their inline test and installed-proof modules (scripts/dev/extract_modules.py, 5 self-tests; split_module.py --allow-root for lib.rs). Module paths, visibility and test ids are unchanged: 544 test ids before and after, cuda-driver tests 433 passed / 78 ignored before and after (Linux), host check clean. GPU identity and A/B follow with the combined batch 1+2 gate.
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Move large inline `mod NAME { ... }` blocks of a Rust file into their own files (STRA-338).
|
||||
|
||||
`foo.rs` keeps the attributes, visibility and name of the module and ends the block with `;`; the body moves, dedented,
|
||||
to `foo/NAME.rs` (beside the file for `mod.rs`, `lib.rs` and `main.rs`). The module path is the same as before, so
|
||||
`super::` paths, test ids and visibility need no edit. Relative `include_str!` / `include_bytes!` paths get one more `../`
|
||||
(the body sits one directory deeper). A block that contains a `#[path]` attribute is left alone. The compiler judges the rest.
|
||||
|
||||
Usage: scripts/dev/extract_modules.py [--dry-run] [--min-lines 60] FILE.rs... prints "moved|skipped <file> <detail>"
|
||||
"""
|
||||
import argparse
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from rustsplit.items import parse_items # noqa: E402
|
||||
from rustsplit.lexer import tokenize # noqa: E402
|
||||
|
||||
INCLUDE = re.compile(r'(include(?:_str|_bytes)?!\(\s*")(?=[^/])')
|
||||
PATH_ATTR = re.compile(r"#\[\s*path\s*=")
|
||||
MODULE = re.compile(r"(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)\s*\{")
|
||||
HEADER = "//! Moved out of the parent file by STRA-338 (same module path as before).\n\n"
|
||||
|
||||
|
||||
def read(path):
|
||||
with open(path, encoding="utf-8", newline="") as handle:
|
||||
return handle.read().replace("\r\n", "\n")
|
||||
|
||||
|
||||
def write(path, text):
|
||||
with open(path, "w", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(text)
|
||||
|
||||
|
||||
def child_dir(path):
|
||||
return path.parent if path.name in ("mod.rs", "lib.rs", "main.rs") else path.with_suffix("")
|
||||
|
||||
|
||||
def brace_index(text, item):
|
||||
"""Index of the `{` that opens the module body."""
|
||||
for tok in tokenize(text[item.head:item.end]):
|
||||
if tok.text == "{":
|
||||
return item.head + tok.start
|
||||
raise ValueError("no opening brace")
|
||||
|
||||
|
||||
def dedent(body):
|
||||
return "\n".join(row[4:] if row.startswith(" ") else row for row in body.split("\n"))
|
||||
|
||||
|
||||
def plan(text, directory, min_lines):
|
||||
"""(new source text, {file: text}, [skipped reasons]) for the inline modules of `text` with at least `min_lines` lines."""
|
||||
edits, files, skipped = [], {}, []
|
||||
for item in parse_items(text):
|
||||
found = MODULE.match(text[item.head:item.end]) if item.kind == "other" else None
|
||||
if found is None:
|
||||
continue
|
||||
name, opening = found.group(1), brace_index(text, item)
|
||||
body = text[opening + 1:item.end - 1]
|
||||
if body.count("\n") < min_lines:
|
||||
continue
|
||||
if PATH_ATTR.search(body):
|
||||
skipped.append(f"{name}: contains a #[path] attribute")
|
||||
elif (directory / f"{name}.rs").exists():
|
||||
skipped.append(f"{name}: {directory / (name + '.rs')} exists")
|
||||
else:
|
||||
content = INCLUDE.sub(lambda m: m.group(1) + "../", dedent(body).strip("\n"))
|
||||
files[directory / f"{name}.rs"] = HEADER + content + "\n"
|
||||
edits.append((opening, item.end))
|
||||
for start, end in sorted(edits, reverse=True):
|
||||
text = text[:start].rstrip() + ";" + text[end:]
|
||||
return text, files, skipped
|
||||
|
||||
|
||||
def process(path, min_lines, dry_run):
|
||||
text, files, skipped = plan(read(path), child_dir(path), min_lines)
|
||||
if not files:
|
||||
return "skipped", "; ".join(skipped) or "no inline module of that size"
|
||||
if not dry_run:
|
||||
for target, body in files.items():
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
write(target, body)
|
||||
write(path, text)
|
||||
detail = ", ".join(f"{p.name} ({b.count(chr(10))} lines)" for p, b in files.items())
|
||||
return "moved", detail + (f" | left: {'; '.join(skipped)}" if skipped else "")
|
||||
|
||||
|
||||
def main(argv):
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
parser.add_argument("--min-lines", type=int, default=60)
|
||||
parser.add_argument("files", nargs="+")
|
||||
args = parser.parse_args(argv)
|
||||
for name in args.files:
|
||||
verdict, detail = process(pathlib.Path(name), args.min_lines, args.dry_run)
|
||||
print(f"{verdict} {name} {detail}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Proofs for scripts/dev/extract_modules.py on synthetic sources."""
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from extract_modules import plan # noqa: E402
|
||||
|
||||
BODY = "".join(f" fn f{n}() {{}}\n" for n in range(5))
|
||||
SOURCE = f'use a::b;\n\n#[cfg(test)]\nmod tests {{\n const P: &str = include_str!("x.ptx");\n{BODY}}}\n\npub(crate) mod small {{\n fn g() {{}}\n}}\n\nfn keep() {{}}\n'
|
||||
|
||||
|
||||
class ExtractModules(unittest.TestCase):
|
||||
def test_a_large_inline_module_moves_and_keeps_its_attributes(self):
|
||||
text, files, skipped = plan(SOURCE, pathlib.Path("d"), 3)
|
||||
self.assertIn("#[cfg(test)]\nmod tests;", text)
|
||||
self.assertEqual(list(files), [pathlib.Path("d/tests.rs")])
|
||||
self.assertEqual(skipped, [])
|
||||
|
||||
def test_the_body_is_dedented_and_includes_go_one_level_up(self):
|
||||
_, files, _ = plan(SOURCE, pathlib.Path("d"), 3)
|
||||
body = files[pathlib.Path("d/tests.rs")]
|
||||
self.assertIn('include_str!("../x.ptx")', body)
|
||||
self.assertIn("\nfn f0() {}\n", body)
|
||||
|
||||
def test_small_modules_and_functions_stay(self):
|
||||
text, _, _ = plan(SOURCE, pathlib.Path("d"), 3)
|
||||
self.assertIn("pub(crate) mod small {", text)
|
||||
self.assertIn("fn keep() {}", text)
|
||||
|
||||
def test_include_macro_without_a_suffix_is_deepened(self):
|
||||
_, files, _ = plan("mod m {\n include!(\"a.rs\");\n fn f() {}\n}\n", pathlib.Path("d"), 1)
|
||||
self.assertIn('include!("../a.rs")', files[pathlib.Path("d/m.rs")])
|
||||
|
||||
def test_a_path_attribute_inside_the_block_keeps_it_in_place(self):
|
||||
text, files, skipped = plan('mod m {\n #[path = "q.rs"]\n mod q;\n fn f() {}\n}\n', pathlib.Path("d"), 1)
|
||||
self.assertEqual(files, {})
|
||||
self.assertIn("mod m {", text)
|
||||
self.assertEqual(len(skipped), 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -36,7 +36,7 @@ def is_root(path):
|
||||
|
||||
|
||||
def child_dir(path):
|
||||
return path.parent if path.name == "mod.rs" else path.with_suffix("")
|
||||
return path.parent if path.name in ("mod.rs", "lib.rs", "main.rs") else path.with_suffix("")
|
||||
|
||||
|
||||
def path_targets():
|
||||
@@ -50,8 +50,8 @@ def path_targets():
|
||||
return found
|
||||
|
||||
|
||||
def process(path, target, dry_run, loaded):
|
||||
if is_root(path):
|
||||
def process(path, target, dry_run, loaded, allow_root=False):
|
||||
if is_root(path) and not (allow_root and path.name == "lib.rs"):
|
||||
return "skipped", "crate root, bin or example"
|
||||
directory = child_dir(path)
|
||||
explicit = directory.name if path.name in loaded else None
|
||||
@@ -71,11 +71,12 @@ def main(argv):
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
parser.add_argument("--target", type=int, default=250)
|
||||
parser.add_argument("--allow-root", action="store_true", help="also split a lib.rs crate root")
|
||||
parser.add_argument("files", nargs="+")
|
||||
args = parser.parse_args(argv)
|
||||
loaded = path_targets()
|
||||
for name in args.files:
|
||||
verdict, detail = process(pathlib.Path(name), args.target, args.dry_run, loaded)
|
||||
verdict, detail = process(pathlib.Path(name), args.target, args.dry_run, loaded, args.allow_root)
|
||||
print(f"{verdict} {name} {detail}")
|
||||
return 0
|
||||
|
||||
|
||||
Reference in New Issue
Block a user