Files
leleka/scripts/dev/rustsplit/split.py
T
Pavlo Ratushnyi 6b5fcd242e STRA-338 S12b: fns and impl blocks of 59 cold oversize modules move into child modules (model-format, gateway, desktop-core, leaf libraries)
scripts/dev/split_module.py (lexer-based, with 16 self-tests) moves the top-level fn and impl items of 59 oversize module files in control-plane, desktop-core, model-format, gateway-text, leleka-memory, experimental-ref, context, serving-policy, tokenizer, backend-api, quant-core, harmony, igpu, libc-shim, npu-service and runtime-client into foo/<name>.rs groups of about 250 lines; types, constants, macros, nested modules and tests stay, every path stays valid through pub use re-exports, restricted visibilities keep their scope one level down, include paths and super:: paths are shifted. Not touched: leleka-runtime, cuda-driver, native-cpu-expert, sampler-ref and cpu-* (hot path, next wave) and the files kar-off-ab edits.

The baseline drops from 311 to 263 oversize files and from 273,600 to about 233,000 lines; the path-include ratchet ignores dir/name.rs child declarations.
2026-11-05 15:29:39 +01:00

83 lines
2.9 KiB
Python

"""Plan a split of one oversized Rust module file into child modules that hold its fns and impl blocks (STRA-338)."""
import re
from dataclasses import dataclass, field
from .items import parse_items
from .retarget import retarget
MAX_NAME = 48
NOT_MOVED = re.compile(r"#\[\s*(test|bench|cfg\s*\(\s*test\s*\)|ignore)\b|#\[\s*macro_export")
@dataclass
class Group:
name: str
chunks: list = field(default_factory=list)
lines: int = 0
members: list = field(default_factory=list)
def slug(item):
base = re.sub(r"[^a-z0-9]+", "_", item.name.lower()).strip("_") or "items"
return (("impl_" if item.kind == "impl" else "") + base)[:MAX_NAME]
def movable(item):
return item.kind in ("fn", "impl") and item.name != "main" and not NOT_MOVED.search(item.attrs)
def unique(name, used):
candidate, n = name, 2
while candidate in used:
candidate, n = f"{name}_{n}", n + 1
used.add(candidate)
return candidate
def group_items(text, items, target, reserved):
"""Pack the movable items, in file order, into groups of about `target` lines."""
groups, used = [], set(reserved)
for item in items:
if not movable(item):
continue
chunk = retarget(text[item.start:item.end], item.kind, item.inherent)
lines = chunk.count("\n") + 1
if not groups or groups[-1].lines + lines > target:
groups.append(Group(unique(slug(item), used)))
groups[-1].chunks.append(chunk)
groups[-1].members.append(f"{item.kind} {item.name}")
groups[-1].lines += lines
return groups
def remove_ranges(text, ranges):
for start, end in sorted(ranges, reverse=True):
text = text[:start] + text[end:]
return re.sub(r"\n{3,}", "\n\n", text)
def child_text(group):
members = ", ".join(group.members[:6]) + (" ..." if len(group.members) > 6 else "")
header = f"//! Moved out of the parent module by STRA-338: {members}.\n\n#[allow(unused_imports)]\nuse super::*;\n"
body = "".join(chunk if chunk.startswith("\n") else "\n" + chunk for chunk in group.chunks)
return header + body.rstrip("\n") + "\n"
def declarations(groups, explicit_dir):
rows = []
for group in groups:
attr = f'#[path = "{explicit_dir}/{group.name}.rs"]\n' if explicit_dir else ""
rows.append(f"{attr}mod {group.name};\n#[allow(unused_imports)]\npub use {group.name}::*;")
return "\n".join(rows)
def plan_split(text, target, explicit_dir=None, reserved=()):
"""(new parent text, {child name: child text}), or None when nothing would move."""
items = parse_items(text)
groups = group_items(text, items, target, reserved)
if not groups:
return None
moved = [(i.start, i.end) for i in items if movable(i)]
parent = remove_ranges(text, moved).rstrip("\n") + "\n\n" + declarations(groups, explicit_dir) + "\n"
return parent, {g.name: child_text(g) for g in groups}