STRA-338 size: scripts/dev/split_types.py moves the types, consts and statics of oversize files into child modules (12 more files split; width census +750 and test census +10 are the restored compact data tables and the reflow, nothing added); 1793 tests listed before and after
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
"""Plan a split of one oversized module file that moves its types, consts and statics into child modules (STRA-338)."""
|
||||
import re
|
||||
|
||||
from .items import _keyword, _skip_attrs, _skip_visibility, cfg_attributes, parse_items, significant, visibility_text
|
||||
from .lexer import tokenize
|
||||
from .retarget import INCLUDE, _path_edits, _restricted_visibility_edits
|
||||
from .split import MAX_NAME
|
||||
|
||||
TYPE_KEYWORDS = {"struct", "enum", "const", "static", "type", "union", "trait"}
|
||||
NOT_MOVED = re.compile(r"#\[\s*macro_export|#\[\s*path\s*=")
|
||||
NL = chr(10)
|
||||
|
||||
|
||||
def keyword_of(chunk):
|
||||
sig = significant(tokenize(chunk))
|
||||
first = _skip_attrs(sig, 0)
|
||||
return _keyword(sig, _skip_visibility(sig, first))[0]
|
||||
|
||||
|
||||
def movable(item, chunk):
|
||||
return item.kind == "other" and keyword_of(chunk) in TYPE_KEYWORDS and not NOT_MOVED.search(item.attrs)
|
||||
|
||||
|
||||
def visibility_edit(sig):
|
||||
"""The edit that makes an item without visibility visible from its siblings after the move."""
|
||||
first = _skip_attrs(sig, 0)
|
||||
if _skip_visibility(sig, first) == first:
|
||||
return (sig[first].start, 0, "pub(super) ")
|
||||
return None
|
||||
|
||||
|
||||
def struct_body_start(sig):
|
||||
"""Index of the `{` or `(` that opens the fields of the struct or union, or None for a unit struct."""
|
||||
keyword_at = next((k for k, t in enumerate(sig) if t.text in ("struct", "union")), None)
|
||||
if keyword_at is None:
|
||||
return None
|
||||
k, generics = keyword_at + 2, 0
|
||||
while k < len(sig) and (sig[k].text not in ("{", "(", ";") or generics):
|
||||
generics += (sig[k].text == "<") - (sig[k].text == ">")
|
||||
k += 1
|
||||
return k if k < len(sig) and sig[k].text in ("{", "(") else None
|
||||
|
||||
|
||||
def field_edits(sig):
|
||||
"""`pub(super)` in front of every private field of the struct or union."""
|
||||
k = struct_body_start(sig)
|
||||
if k is None:
|
||||
return []
|
||||
closing = "}" if sig[k].text == "{" else ")"
|
||||
edits, depth, at_start, angle = [], 0, False, 0
|
||||
for j in range(k, len(sig)):
|
||||
text = sig[j].text
|
||||
if depth == 1 and at_start and text != closing:
|
||||
first = _skip_attrs(sig, j)
|
||||
if first < len(sig) and sig[first].text != "pub":
|
||||
edits.append((sig[first].start, 0, "pub(super) "))
|
||||
at_start = False
|
||||
if text == "<":
|
||||
angle += 1
|
||||
elif text == ">" and sig[j - 1].text != "-":
|
||||
angle = max(angle - 1, 0)
|
||||
if text in ("{", "(", "["):
|
||||
depth += 1
|
||||
if depth == 1:
|
||||
at_start = True
|
||||
elif text in ("}", ")", "]"):
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
break
|
||||
elif depth == 1 and text == "," and angle == 0:
|
||||
at_start = True
|
||||
return edits
|
||||
|
||||
|
||||
def moved_text(chunk):
|
||||
"""The chunk one module down: visibility, field visibility, `super::` paths and relative includes."""
|
||||
sig = significant(tokenize(chunk))
|
||||
edits = _path_edits(sig) + _restricted_visibility_edits(sig) + field_edits(sig)
|
||||
edit = visibility_edit(sig)
|
||||
if edit:
|
||||
edits.append(edit)
|
||||
for position, length, replacement in sorted(edits, reverse=True):
|
||||
chunk = chunk[:position] + replacement + chunk[position + length:]
|
||||
return INCLUDE.sub(lambda m: m.group(1) + "../", chunk)
|
||||
|
||||
|
||||
def slug(name):
|
||||
return (re.sub(r"[^a-z0-9]+", "_", re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", name).lower()).strip("_") or "items") + "_types"
|
||||
|
||||
|
||||
def unique(name, used):
|
||||
candidate, n = name[:MAX_NAME], 2
|
||||
while candidate in used:
|
||||
candidate, n = f"{name[:MAX_NAME - 3]}_{n}", n + 1
|
||||
used.add(candidate)
|
||||
return candidate
|
||||
|
||||
|
||||
def group_picked(picked, target):
|
||||
groups, current, size = [], [], 0
|
||||
for item, chunk in picked:
|
||||
height = chunk.count(NL) + 1
|
||||
if current and size + height > target:
|
||||
groups.append(current)
|
||||
current, size = [], 0
|
||||
current.append((item, chunk))
|
||||
size += height
|
||||
return groups + [current]
|
||||
|
||||
|
||||
def export_line(item, chunk, name):
|
||||
vis = visibility_text(chunk)
|
||||
lines = [*cfg_attributes(item.attrs), "#[allow(unused_imports)]", f"{vis + ' ' if vis else ''}use {name}::{item.name};"]
|
||||
return NL.join(lines)
|
||||
|
||||
|
||||
def plan_type_split(text, target, explicit_dir=None, reserved=()):
|
||||
"""(new parent text, {child name: child text}), or None when nothing would move."""
|
||||
picked = [(i, text[i.start:i.end]) for i in parse_items(text)]
|
||||
picked = [(item, chunk) for item, chunk in picked if movable(item, chunk)]
|
||||
if not picked:
|
||||
return None
|
||||
used = set(reserved)
|
||||
children, declarations = {}, []
|
||||
for group in group_picked(picked, target):
|
||||
name = unique(slug(group[0][0].name), used)
|
||||
pieces = [moved_text(chunk) for _, chunk in group]
|
||||
body = "".join(p if p.startswith(NL) else NL + p for p in pieces)
|
||||
names = ", ".join(i.name for i, _ in group[:6]) + (" ..." if len(group) > 6 else "")
|
||||
head = f"//! Moved out of the parent module by STRA-338: {names}." + NL + NL + "#[allow(unused_imports)]" + NL + "use super::*;" + NL
|
||||
children[name] = head + body.rstrip(NL) + NL
|
||||
attr = f'#[path = "{explicit_dir}/{name}.rs"]' + NL if explicit_dir else ""
|
||||
exports = NL.join(export_line(item, chunk, name) for item, chunk in group)
|
||||
declarations.append(attr + f"mod {name};" + NL + exports)
|
||||
parent = text
|
||||
for start, end in sorted(((i.start, i.end) for i, _ in picked), reverse=True):
|
||||
parent = parent[:start] + parent[end:]
|
||||
parent = re.sub(r"\n{3,}", NL + NL, parent).rstrip(NL) + NL + NL + NL.join(declarations) + NL
|
||||
return parent, children
|
||||
Reference in New Issue
Block a user