Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
116 lines
4.7 KiB
Python
116 lines
4.7 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 .implsplit import split_impl
|
|
from .items import cfg_attributes, parse_items, visibility_text
|
|
from .names import distinct
|
|
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)
|
|
exports: list = field(default_factory=list) # (cfg attributes, visibility, fn name) of the moved free fns
|
|
|
|
|
|
def slug(item):
|
|
"""The module name of a moved item: a fn keeps its name, `impl Type` becomes `type_methods`, `impl Trait for Type`
|
|
becomes `trait_for_type`."""
|
|
base = re.sub(r"[^a-z0-9]+", "_", item.name.lower()).strip("_") or "items"
|
|
return (base + ("_methods" if item.kind == "impl" and item.inherent else ""))[:MAX_NAME]
|
|
|
|
|
|
def continuation(part):
|
|
"""The suffix of a cut impl block after the first: the first method it holds (`_from_prefill`)."""
|
|
found = re.search(r"\bfn\s+([a-z_][a-z0-9_]*)", part)
|
|
return f"_from_{found.group(1)}" if found else "_continued"
|
|
|
|
|
|
def movable(item):
|
|
return item.kind in ("fn", "impl") and item.name != "main" and not NOT_MOVED.search(item.attrs)
|
|
|
|
|
|
def unique(name, used):
|
|
"""`name`, or `name` plus a word when it is taken (see `names.distinct`)."""
|
|
return distinct(name, used, MAX_NAME)
|
|
|
|
|
|
class Packer:
|
|
"""Fills groups of about `target` lines with chunks, in order."""
|
|
|
|
def __init__(self, target, reserved):
|
|
self.target, self.used, self.groups = target, set(reserved), []
|
|
|
|
def add(self, item, part, label):
|
|
"""Append one chunk, a whole item or one block of a cut impl (`label` is "" or "_from_<first method>" for cut blocks)."""
|
|
chunk = retarget(part, item.kind, item.inherent)
|
|
lines = chunk.count("\n") + 1
|
|
if not self.groups or self.groups[-1].lines + lines > self.target:
|
|
self.groups.append(Group(unique(slug(item) + label, self.used)))
|
|
group = self.groups[-1]
|
|
group.chunks.append(chunk)
|
|
group.members.append(f"{item.kind} {item.name}" + (f" ({label.strip('_')})" if label else ""))
|
|
if item.kind == "fn":
|
|
group.exports.append((cfg_attributes(item.attrs), visibility_text(part), item.name))
|
|
group.lines += lines
|
|
|
|
|
|
def group_items(text, items, target, reserved):
|
|
"""Pack the movable items, in file order, into groups of about `target` lines."""
|
|
packer = Packer(target, reserved)
|
|
for item in (i for i in items if movable(i)):
|
|
original = text[item.start:item.end]
|
|
parts = split_impl(original, target) if item.kind == "impl" and item.inherent else [original]
|
|
for number, part in enumerate(parts, 1):
|
|
packer.add(item, part, continuation(part) if number > 1 else "")
|
|
return packer.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 export_lines(group):
|
|
"""`use` lines that bring each moved free fn back under its old name with its old visibility."""
|
|
rows = []
|
|
for cfgs, vis, name in group.exports:
|
|
lines = [*cfgs, "#[allow(unused_imports)]", f"{vis + ' ' if vis else ''}use {group.name}::{name};"]
|
|
rows.append("\n".join(lines))
|
|
return rows
|
|
|
|
|
|
def declarations(groups, explicit_dir):
|
|
rows = []
|
|
for group in groups:
|
|
attr = [f'#[path = "{explicit_dir}/{group.name}.rs"]'] if explicit_dir else []
|
|
rows.append("\n".join([*attr, f"mod {group.name};"]))
|
|
rows.extend(export_lines(group))
|
|
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 or len(groups) == 1 and groups[0].lines >= 0.8 * (text.count(chr(10)) + 1):
|
|
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}
|