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.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Mechanical splitting of oversized Rust module files (STRA-338). Entry point: scripts/dev/split_module.py."""
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Top-level items of a Rust file: where each starts and ends, what it is, and what must change when it moves."""
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .lexer import tokenize
|
||||
|
||||
OPEN, CLOSE = "{([", "})]"
|
||||
BRACE_ITEMS = {"fn", "impl", "trait", "mod", "struct", "enum", "union", "macro_rules", "extern"}
|
||||
SEMI_ITEMS = {"use", "const", "static", "type", "crate"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Item:
|
||||
start: int # first character carried by the item: the comments and blanks before it
|
||||
head: int # first character of the item proper (after attributes and doc comments)
|
||||
end: int # one past the last character
|
||||
kind: str # fn impl or other
|
||||
name: str
|
||||
attrs: str # text of the outer attributes
|
||||
inherent: bool = False
|
||||
|
||||
|
||||
def significant(tokens):
|
||||
return [t for t in tokens if t.kind not in ("ws", "comment")]
|
||||
|
||||
|
||||
def _skip_bracket(sig, k):
|
||||
"""Index after the balanced `[ ... ]` group whose `[` is at sig[k]."""
|
||||
depth = 0
|
||||
while k < len(sig):
|
||||
depth += (sig[k].text == "[") - (sig[k].text == "]")
|
||||
k += 1
|
||||
if depth == 0:
|
||||
break
|
||||
return k
|
||||
|
||||
|
||||
def _skip_attrs(sig, k):
|
||||
"""Index of the first token after the outer attributes starting at k."""
|
||||
while k + 1 < len(sig) and sig[k].text == "#" and sig[k + 1].text == "[":
|
||||
k = _skip_bracket(sig, k + 1)
|
||||
return k
|
||||
|
||||
|
||||
def _skip_visibility(sig, k):
|
||||
if sig[k].text != "pub":
|
||||
return k
|
||||
k += 1
|
||||
if sig[k].text == "(":
|
||||
while sig[k].text != ")":
|
||||
k += 1
|
||||
k += 1
|
||||
return k
|
||||
|
||||
|
||||
def _keyword(sig, k):
|
||||
"""The keyword naming the item whose first token (after attributes and visibility) is sig[k], and its index."""
|
||||
while sig[k].text in ("unsafe", "async", "default", "const", "extern"):
|
||||
word, nxt = sig[k].text, sig[k + 1]
|
||||
if word == "const" and nxt.text not in ("fn", "unsafe", "async", "extern"):
|
||||
break
|
||||
if word == "extern":
|
||||
skip = 2 if nxt.kind == "string" else 1
|
||||
if sig[k + skip].text not in ("fn", "unsafe"):
|
||||
break
|
||||
k += skip
|
||||
continue
|
||||
k += 1
|
||||
return sig[k].text, k
|
||||
|
||||
|
||||
def _ends_with_brace(sig, k, bang_brace):
|
||||
"""Index of the last token when the `}` at sig[k] closes a braced item (a macro call may be followed by `;`)."""
|
||||
return k + 1 if bang_brace and k + 1 < len(sig) and sig[k + 1].text == ";" else k
|
||||
|
||||
|
||||
def _item_end(sig, k, keyword):
|
||||
"""Index in `sig` of the last token of the item whose keyword is at sig[k]."""
|
||||
depth, semi_only = 0, keyword in SEMI_ITEMS
|
||||
bang_brace = keyword not in BRACE_ITEMS | SEMI_ITEMS and sig[k + 1].text == "!"
|
||||
while k < len(sig):
|
||||
text = sig[k].text
|
||||
depth += (text in OPEN) - (text in CLOSE)
|
||||
if depth == 0 and (text == ";" or text == "}" and not semi_only):
|
||||
return k if text == ";" else _ends_with_brace(sig, k, bang_brace)
|
||||
k += 1
|
||||
return len(sig) - 1
|
||||
|
||||
|
||||
def _impl_name(sig, k):
|
||||
"""`Foo` for `impl Foo`, `Trait_for_Foo` for `impl<T> Trait for Foo`; at most three identifiers."""
|
||||
j, depth, words = k + 1, 0, []
|
||||
while j < len(sig) and sig[j].text not in ("{", "where"):
|
||||
depth += (sig[j].text == "<") - (sig[j].text == ">")
|
||||
if depth == 0 and sig[j].kind == "ident" and sig[j].text != "for":
|
||||
words.append(sig[j].text)
|
||||
elif depth == 0 and sig[j].text == "for":
|
||||
words.append("for")
|
||||
j += 1
|
||||
return "_".join(words[:3]) or "impl"
|
||||
|
||||
|
||||
def _name_of(sig, k, keyword):
|
||||
if keyword == "impl":
|
||||
return _impl_name(sig, k)
|
||||
return sig[k + 1].text if k + 1 < len(sig) and sig[k + 1].kind == "ident" else keyword
|
||||
|
||||
|
||||
def _is_inherent(sig, k, end):
|
||||
"""An `impl` is inherent when no `for` appears before its opening brace."""
|
||||
for j in range(k, end):
|
||||
if sig[j].text == "{":
|
||||
return True
|
||||
if sig[j].text == "for":
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def preamble_end(text, tokens):
|
||||
"""End of the file header: `//!` docs, `#![...]` inner attributes and the blanks between them."""
|
||||
sig = significant(tokens)
|
||||
end, k = 0, 0
|
||||
for t in tokens:
|
||||
if t.kind == "comment" and t.text.startswith(("//!", "/*!")) or t.kind == "ws":
|
||||
end = t.end
|
||||
elif t.kind != "comment" or t.text.startswith("//"):
|
||||
break
|
||||
while k + 2 < len(sig) and sig[k].text == "#" and sig[k + 1].text == "!":
|
||||
k = _skip_bracket(sig, k + 2)
|
||||
end = max(end, sig[k - 1].end)
|
||||
return end, k
|
||||
|
||||
|
||||
def parse_items(text):
|
||||
"""Top-level items of `text` in order; the text between items is carried by the item that follows it."""
|
||||
tokens = tokenize(text)
|
||||
sig = significant(tokens)
|
||||
previous_end, k = preamble_end(text, tokens)
|
||||
items = []
|
||||
while k < len(sig):
|
||||
attrs_end = _skip_attrs(sig, k)
|
||||
if attrs_end >= len(sig):
|
||||
break
|
||||
keyword, at = _keyword(sig, _skip_visibility(sig, attrs_end))
|
||||
last = _item_end(sig, at, keyword)
|
||||
kind = keyword if keyword in ("fn", "impl") else "other"
|
||||
items.append(Item(previous_end, sig[attrs_end].start, sig[last].end, kind, _name_of(sig, at, keyword),
|
||||
text[sig[k].start:sig[attrs_end].start], kind == "impl" and _is_inherent(sig, at, last)))
|
||||
previous_end, k = sig[last].end, last + 1
|
||||
return items
|
||||
@@ -0,0 +1,120 @@
|
||||
"""A small Rust lexer: enough to find item boundaries and `super::` paths without a parser (STRA-338)."""
|
||||
from dataclasses import dataclass
|
||||
|
||||
IDENT_START = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_")
|
||||
IDENT_PART = IDENT_START | set("0123456789")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Token:
|
||||
kind: str # ws comment string char lifetime ident number punct
|
||||
start: int
|
||||
end: int
|
||||
text: str
|
||||
|
||||
|
||||
def _skip_line_comment(text, i):
|
||||
end = text.find("\n", i)
|
||||
return len(text) if end < 0 else end
|
||||
|
||||
|
||||
def _skip_block_comment(text, i):
|
||||
depth, n = 0, len(text)
|
||||
while i < n:
|
||||
if text.startswith("/*", i):
|
||||
depth, i = depth + 1, i + 2
|
||||
elif text.startswith("*/", i):
|
||||
depth, i = depth - 1, i + 2
|
||||
if depth == 0:
|
||||
return i
|
||||
else:
|
||||
i += 1
|
||||
return n
|
||||
|
||||
|
||||
def _skip_quoted(text, i, quote):
|
||||
"""End index after the closing quote of a string or char literal that opens at `i`."""
|
||||
i += 1
|
||||
while i < len(text) and text[i] != quote:
|
||||
i += 2 if text[i] == "\\" else 1
|
||||
return i + 1
|
||||
|
||||
|
||||
def _raw_string_end(text, i):
|
||||
"""End of a raw string `r"..."` / `r#"..."#` whose `r` is at `i` (after a `b` prefix too); None if it is not one."""
|
||||
j = i + 1
|
||||
while j < len(text) and text[j] == "#":
|
||||
j += 1
|
||||
if j >= len(text) or text[j] != '"':
|
||||
return None
|
||||
closing = '"' + "#" * (j - i - 1)
|
||||
end = text.find(closing, j + 1)
|
||||
return len(text) if end < 0 else end + len(closing)
|
||||
|
||||
|
||||
def _char_or_lifetime_end(text, i):
|
||||
"""(kind, end) of what starts with a `'`."""
|
||||
if text[i + 1:i + 2] == "\\" or text[i + 2:i + 3] == "'":
|
||||
return "char", _skip_quoted(text, i, "'")
|
||||
j = i + 1
|
||||
while j < len(text) and text[j] in IDENT_PART:
|
||||
j += 1
|
||||
return "lifetime", j
|
||||
|
||||
|
||||
def _ident_end(text, i):
|
||||
j = i
|
||||
while j < len(text) and text[j] in IDENT_PART:
|
||||
j += 1
|
||||
return j
|
||||
|
||||
|
||||
def _literal_prefix(text, i):
|
||||
"""(kind, end) for r"", b"", br"", b'' starting at i, or None."""
|
||||
for prefix in ("br", "r", "b"):
|
||||
if text.startswith(prefix, i) and prefix[-1] == "r":
|
||||
end = _raw_string_end(text, i + len(prefix) - 1)
|
||||
if end is not None:
|
||||
return "string", end
|
||||
if prefix == "b" and text.startswith('b"', i):
|
||||
return "string", _skip_quoted(text, i + 1, '"')
|
||||
if prefix == "b" and text.startswith("b'", i):
|
||||
return "char", _skip_quoted(text, i + 1, "'")
|
||||
return None
|
||||
|
||||
|
||||
def _simple_token(text, i):
|
||||
"""(kind, end) for whitespace, comments and quoted literals, or None."""
|
||||
c = text[i]
|
||||
if c.isspace():
|
||||
j = i
|
||||
while j < len(text) and text[j].isspace():
|
||||
j += 1
|
||||
return "ws", j
|
||||
if text.startswith("//", i):
|
||||
return "comment", _skip_line_comment(text, i)
|
||||
if text.startswith("/*", i):
|
||||
return "comment", _skip_block_comment(text, i)
|
||||
return ("string", _skip_quoted(text, i, '"')) if c == '"' else None
|
||||
|
||||
|
||||
def _next_token(text, i):
|
||||
simple = _simple_token(text, i)
|
||||
if simple:
|
||||
return simple
|
||||
c = text[i]
|
||||
if c == "'":
|
||||
return _char_or_lifetime_end(text, i)
|
||||
if c in IDENT_START:
|
||||
return _literal_prefix(text, i) or ("ident", _ident_end(text, i))
|
||||
return ("number", _ident_end(text, i)) if c.isdigit() else ("punct", i + 1)
|
||||
|
||||
|
||||
def tokenize(text):
|
||||
"""All tokens of a Rust source text; they tile the text exactly."""
|
||||
tokens, i = [], 0
|
||||
while i < len(text):
|
||||
kind, end = _next_token(text, i)
|
||||
tokens.append(Token(kind, i, end, text[i:end]))
|
||||
i = end
|
||||
return tokens
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Edits a function or impl chunk needs when it moves one module down: visibility and `super::` / `self::` paths."""
|
||||
import re
|
||||
|
||||
from .items import CLOSE, OPEN, _keyword, _skip_attrs, _skip_visibility, significant
|
||||
from .lexer import tokenize
|
||||
|
||||
VIS = "pub(super) "
|
||||
INCLUDE = re.compile(r'(include_(?:str|bytes)!\(\s*")(?=[^/])')
|
||||
|
||||
|
||||
def _is_double_colon(sig, k):
|
||||
return k >= 1 and sig[k].text == ":" and sig[k - 1].text == ":"
|
||||
|
||||
|
||||
def _restricted_visibility_edits(sig):
|
||||
"""`pub(super)` and `pub(self)` name a scope relative to the module; one level down they need `pub(in ...)`."""
|
||||
edits = []
|
||||
for k, tok in enumerate(sig[:-3]):
|
||||
if tok.text == "pub" and sig[k + 1].text == "(" and sig[k + 3].text == ")":
|
||||
inner = sig[k + 2]
|
||||
replacement = {"super": "in super::super", "self": "in super"}.get(inner.text)
|
||||
if replacement:
|
||||
edits.append((inner.start, len(inner.text), replacement))
|
||||
return edits
|
||||
|
||||
|
||||
def _path_edits(sig):
|
||||
"""(position, length, replacement) for every path that starts with `super` or `self` (not after `::`)."""
|
||||
edits = []
|
||||
for k, tok in enumerate(sig[:-2]):
|
||||
follows_path = k >= 2 and _is_double_colon(sig, k - 1)
|
||||
if tok.kind != "ident" or follows_path or not _is_double_colon(sig, k + 2):
|
||||
continue
|
||||
if tok.text == "super":
|
||||
edits.append((tok.start, 5, "super::super"))
|
||||
elif tok.text == "self":
|
||||
edits.append((tok.start, 4, "super"))
|
||||
return edits
|
||||
|
||||
|
||||
def _assoc_item_starts(sig):
|
||||
"""Indexes in `sig` where an associated item of an impl body (brace depth 1) begins."""
|
||||
starts, depth = [], 0
|
||||
for k, tok in enumerate(sig):
|
||||
depth += (tok.text in OPEN) - (tok.text in CLOSE)
|
||||
if k > 0 and sig[k - 1].text in ("{", "}", ";") and depth == 1 and tok.text != "}":
|
||||
starts.append(k)
|
||||
return starts
|
||||
|
||||
|
||||
def _assoc_visibility_edits(sig):
|
||||
"""`pub(super)` before every private fn or const of an inherent impl body."""
|
||||
edits = []
|
||||
for k in _assoc_item_starts(sig):
|
||||
first = _skip_attrs(sig, k)
|
||||
if first < len(sig) and sig[first].text != "pub" and _keyword(sig, first)[0] in ("fn", "const"):
|
||||
edits.append((sig[first].start, 0, VIS))
|
||||
return edits
|
||||
|
||||
|
||||
def _fn_visibility_edits(sig):
|
||||
"""`pub(super)` for a free fn that has no visibility."""
|
||||
first = _skip_attrs(sig, 0)
|
||||
if sig[first].text == "pub" or _keyword(sig, first)[0] != "fn":
|
||||
return []
|
||||
return [(sig[first].start, 0, VIS)]
|
||||
|
||||
|
||||
def apply_edits(text, edits):
|
||||
for pos, length, replacement in sorted(edits, reverse=True):
|
||||
text = text[:pos] + replacement + text[pos + length:]
|
||||
return text
|
||||
|
||||
|
||||
def retarget(chunk, kind, inherent):
|
||||
"""The chunk (one fn or impl, from its leading comments on) as it must read inside a child module."""
|
||||
sig = significant(tokenize(chunk))
|
||||
edits = _path_edits(sig) + _restricted_visibility_edits(sig)
|
||||
if kind == "fn":
|
||||
edits += _fn_visibility_edits(sig)
|
||||
elif inherent:
|
||||
edits += _assoc_visibility_edits(sig)
|
||||
return INCLUDE.sub(lambda m: m.group(1) + "../", apply_edits(chunk, edits))
|
||||
@@ -0,0 +1,82 @@
|
||||
"""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}
|
||||
Reference in New Issue
Block a user