STRA-338: architecture gate forbids new mechanical file names (impl_*, *_fn, numbered), baseline lists the 964 existing; rustsplit names modules after what they hold

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-08 00:50:17 +01:00
co-authored by Claude Sonnet 5.5
parent 4b04c24981
commit ac60df040f
14 changed files with 1124 additions and 42 deletions
+9 -7
View File
@@ -87,16 +87,18 @@ def _item_end(sig, k, keyword):
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, []
"""`Foo` for `impl Foo`, `Trait_for_Foo` for `impl<T> path::Trait for path::Foo<T>`: the last identifier of each path."""
j, depth, before, after, seen_for = k + 1, 0, None, None, False
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")
if depth == 0 and sig[j].text == "for":
seen_for = True
elif depth == 0 and sig[j].kind == "ident":
before, after = (before, sig[j].text) if seen_for else (sig[j].text, after)
j += 1
return "_".join(words[:3]) or "impl"
if seen_for:
return f"{before}_for_{after}" if before and after else before or after or "impl"
return before or "impl"
def _name_of(sig, k, keyword):
+18
View File
@@ -0,0 +1,18 @@
"""Module names for the files a split creates: they say what the module holds, never how it was produced."""
# Added to a name that is already taken, in order; a number is the last resort and a name worth a human rename.
DISAMBIGUATORS = ("more", "further", "extra", "additional", "other")
def distinct(name, used, limit):
"""`name` (cut to `limit` characters) or the first `name_<word>` that is not in `used`; the result joins `used`."""
candidate = name[:limit].rstrip("_")
for word in DISAMBIGUATORS:
if candidate not in used:
break
candidate = f"{name[:limit - len(word) - 1]}_{word}".lstrip("_")
n = 2
while candidate in used:
candidate, n = f"{name[:limit - 4]}_{DISAMBIGUATORS[-1]}_{n}", n + 1
used.add(candidate)
return candidate
+14 -8
View File
@@ -4,6 +4,7 @@ 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
@@ -20,8 +21,16 @@ class Group:
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 (("impl_" if item.kind == "impl" else "") + base + ("_fn" if item.kind == "fn" else ""))[:MAX_NAME]
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):
@@ -29,11 +38,8 @@ def movable(item):
def unique(name, used):
candidate, n = name, 2
while candidate in used:
candidate, n = f"{name}_{n}", n + 1
used.add(candidate)
return candidate
"""`name`, or `name` plus a word when it is taken (see `names.distinct`)."""
return distinct(name, used, MAX_NAME)
class Packer:
@@ -43,7 +49,7 @@ class Packer:
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 "_2", "_3" ... for cut blocks)."""
"""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:
@@ -63,7 +69,7 @@ def group_items(text, items, target, reserved):
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, f"_{number}" if number > 1 else "")
packer.add(item, part, continuation(part) if number > 1 else "")
return packer.groups
+3 -5
View File
@@ -2,6 +2,7 @@
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
@@ -64,11 +65,8 @@ def topic(items):
def unique(name, used):
candidate, n = name, 2
while candidate in used:
candidate, n = f"{name}_{n}", n + 1
used.add(candidate)
return candidate
"""`name`, or `name` plus a word when it is taken (see `names.distinct`)."""
return distinct(name, used, MAX_NAME)
def remove_ranges(text, ranges):
+3 -5
View File
@@ -4,6 +4,7 @@ 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 .names import distinct
from .split import MAX_NAME
TYPE_KEYWORDS = {"struct", "enum", "const", "static", "type", "union", "trait"}
@@ -89,11 +90,8 @@ def slug(name):
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
"""`name`, or `name` plus a word when it is taken (see `names.distinct`)."""
return distinct(name, used, MAX_NAME)
def group_picked(picked, target):
+21 -5
View File
@@ -68,7 +68,7 @@ class Items(unittest.TestCase):
def test_item_kinds_and_names(self):
found = [(i.kind, i.name) for i in parse_items(SOURCE)]
self.assertEqual(found, [("other", "std"), ("other", "LIMIT"), ("other", "Thing"), ("impl", "Thing"),
("impl", "fmt_Display_for"), ("fn", "helper"), ("fn", "shared"), ("other", "tests")])
("impl", "Display_for_Thing"), ("fn", "helper"), ("fn", "shared"), ("other", "tests")])
def test_inherent_impl_is_detected(self):
self.assertEqual([i.inherent for i in parse_items(SOURCE) if i.kind == "impl"], [True, False])
@@ -111,6 +111,22 @@ class Retargeting(unittest.TestCase):
class Planning(unittest.TestCase):
def test_module_names_say_what_they_hold_and_never_how_they_were_made(self):
_, children = plan_split(SOURCE, 8)
self.assertEqual(sorted(children), ["display_for_thing", "helper", "shared", "thing_methods"])
for name in children:
self.assertFalse(name.startswith("impl_") or name.endswith("_fn") or re.search(r"_[0-9]+$", name), name)
def test_a_cut_impl_names_its_continuation_after_its_first_method(self):
method = " fn m{n}(&self) {{\n let x = {n};\n }}\n"
source = "struct S;\nimpl S {\n" + "".join(method.format(n=n) for n in range(6)) + "}\n"
_, children = plan_split(source, 8)
self.assertTrue(any(name.startswith("s_methods_from_m") for name in children), sorted(children))
def test_a_taken_name_gets_a_word_not_a_number(self):
_, children = plan_split("fn a() {}\nfn a() {}\n", 1)
self.assertEqual(sorted(children), ["a", "a_more"])
def test_fns_and_impls_move_and_the_rest_stays(self):
parent, children = plan_split(SOURCE, 8)
self.assertIn("pub struct Thing", parent)
@@ -120,12 +136,12 @@ class Planning(unittest.TestCase):
self.assertTrue(all("use super::*;" in text for text in children.values()))
for name in children:
self.assertIn(f"mod {name};", parent)
self.assertIn("use helper_fn::helper;", parent)
self.assertIn("pub(crate) use shared_fn::shared;", parent)
self.assertIn("use helper::helper;", parent)
self.assertIn("pub(crate) use shared::shared;", parent)
def test_cfg_attributes_follow_the_fn_to_its_use(self):
parent, _ = plan_split('#[cfg(unix)]\npub fn a() {}\n', 100)
self.assertIn('#[cfg(unix)]\n#[allow(unused_imports)]\npub use a_fn::a;', parent)
self.assertIn('#[cfg(unix)]\n#[allow(unused_imports)]\npub use a::a;', parent)
def test_a_long_inherent_impl_is_cut_between_its_methods(self):
methods = "".join(f" fn m{n}(&self) -> u32 {{\n {n}\n }}\n" for n in range(6))
@@ -147,7 +163,7 @@ class Planning(unittest.TestCase):
def test_explicit_paths_are_written_for_path_loaded_files(self):
parent, _ = plan_split("fn a() {}\n", 100, explicit_dir="foo")
self.assertIn('#[path = "foo/a_fn.rs"]', parent)
self.assertIn('#[path = "foo/a.rs"]', parent)
if __name__ == "__main__":