Files
leleka/scripts/dev/rustsplit/implsplit.py
Pavlo Ratushnyi cb790da36b STRA-338 S12d: long impl blocks are cut between methods and the remaining oversize modules split (53 files)
The splitter now cuts an inherent impl longer than its target into several impl blocks of the same type between associated items (the generics and where clause repeated, the doc comment kept on the first block), so the giant impls left by S12b/S12c (up to 2,000 lines) split too. 53 further module files of the cold and hot crates are split; the baseline drops to 127 oversize files holding 109,000 lines (329 files and 303,000 lines on main). Types, constants, macros, tests and the files kar-off-ab edits stay; crate roots and bins are untouched.
2026-11-05 16:16:36 +01:00

60 lines
2.1 KiB
Python

"""Cut one long inherent `impl` block into several `impl` blocks of the same type, between its associated items."""
import re
from .items import parse_items, significant
from .lexer import tokenize
DOC_LINE = re.compile(r"^\s*(///|#\[\s*doc\b)")
def _header_end(chunk):
"""(index of the opening `{` of the impl body, index of its closing `}`) in `chunk`, or None."""
sig = significant(tokenize(chunk))
keyword = next((k for k, t in enumerate(sig) if t.text == "impl"), None)
if keyword is None:
return None
depth, opening = 0, None
for tok in sig[keyword:]:
depth += (tok.text in "([") - (tok.text in ")]")
if tok.text == "{" and depth == 0:
opening = tok.start
break
return (opening, sig[-1].start) if opening is not None and sig[-1].text == "}" else None
def _without_docs(header):
return "\n".join(row for row in header.split("\n") if not DOC_LINE.match(row))
def _line_count(text):
return text.count("\n") + 1
def _pack(items, body, target):
"""Consecutive associated items packed into parts of about `target` lines."""
parts, current = [], []
for item in items:
if current and _line_count(body[current[0].start:item.end]) > target:
parts.append(current)
current = []
current.append(item)
return parts + ([current] if current else [])
def split_impl(chunk, target):
"""The impl blocks that replace `chunk`: one when it is short or has fewer than two associated items."""
bounds = _header_end(chunk)
if bounds is None or _line_count(chunk) <= target:
return [chunk]
opening, closing = bounds
header, body = chunk[:opening + 1], chunk[opening + 1:closing]
parts = _pack(parse_items(body), body, target)
if len(parts) < 2:
return [chunk]
blocks = []
for n, part in enumerate(parts):
end = len(body) if n == len(parts) - 1 else part[-1].end
text = header if n == 0 else _without_docs(header)
blocks.append(text + body[0 if n == 0 else part[0].start:end].rstrip() + "\n}")
return blocks