"""Plan a split of one oversized test file into child modules that hold its `#[test]` fns, grouped by topic (STRA-338).""" import re from .items import parse_items, significant from .names import distinct from .lexer import tokenize from .retarget import INCLUDE, _path_edits, _restricted_visibility_edits TEST_ATTR = re.compile(r"#\[\s*(?:\w+::)*test\b") MAX_NAME = 40 STOP = {"a", "an", "the", "is", "are", "to", "of", "and", "or", "in", "on", "by", "for", "with", "it", "its", "no"} def is_test(item): return item.kind == "fn" and TEST_ATTR.search(item.attrs) is not None def lines_of(text): return text.count("\n") + 1 def chunks_of(text, items, target): """Runs of tests in file order, each about `target` lines (helpers between tests stay in the parent).""" runs, current, size = [], [], 0 for item in items: if not is_test(item): continue height = lines_of(text[item.start:item.end]) if current and size + height > target: runs.append(current) current, size = [], 0 current.append(item) size += height return runs + ([current] if current else []) def common_words(names): split = [name.split("_") for name in names] prefix = [] for column in zip(*split): if len(set(column)) != 1: break prefix.append(column[0]) return prefix def trimmed(words): """`words` without the articles and prepositions at either end.""" words = list(words) while words and words[0] in STOP: words.pop(0) while words and words[-1] in STOP: words.pop() return words def topic(items): """A readable module name for a chunk: the words its tests share (three or more), else the first test's first words.""" names = [item.name for item in items] words = trimmed(common_words(names)) if len(names) > 1 else [] if len(words) < 3: words = trimmed(names[0].split("_")[:5]) or names[0].split("_")[:3] name = re.sub(r"[^a-z0-9_]+", "_", "_".join(words).lower()).strip("_") or "tests" return name[:MAX_NAME].rstrip("_") def unique(name, used): """`name`, or `name` plus a word when it is taken (see `names.distinct`).""" return distinct(name, used, MAX_NAME) 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 shifted(chunk): """The chunk one module down: `super::` / `self::` paths, restricted visibilities and relative includes follow.""" sig = significant(tokenize(chunk)) for position, length, replacement in sorted(_path_edits(sig) + _restricted_visibility_edits(sig), reverse=True): chunk = chunk[:position] + replacement + chunk[position + length:] return INCLUDE.sub(lambda m: m.group(1) + "../", chunk) def child_text(stem, items, text): names = ", ".join(item.name for item in items[:4]) + (" ..." if len(items) > 4 else "") pieces = [shifted(text[item.start:item.end]) for item in items] body = "".join(piece if piece.startswith("\n") else "\n" + piece for piece in pieces) header = f"//! Tests of {stem} by topic (moved out of the test file by STRA-338): {names}.\n\n" return header + "#[allow(unused_imports)]\nuse super::*;\n" + body.rstrip("\n") + "\n" def plan_test_split(text, target, stem, explicit_dir=None, reserved=()): """(new parent text, {child name: child text}), or None when there is nothing worth moving.""" items = parse_items(text) runs = chunks_of(text, items, target) # one test fn per file cannot be made smaller by moving it into a module of its own if len(runs) < 2 and (not runs or len(runs[0]) < 2): return None used = set(reserved) | {item.name for item in items if item.kind != "fn"} # a module and a fn live in different namespaces children = {} declarations = [] for run in runs: name = unique(topic(run), used) children[name] = child_text(stem, run, text) attr = f'#[path = "{explicit_dir}/{name}.rs"]\n' if explicit_dir else "" declarations.append(f"{attr}mod {name};") moved = [(item.start, item.end) for run in runs for item in run] parent = remove_ranges(text, moved).rstrip("\n") + "\n\n" + "\n".join(declarations) + "\n" return parent, children