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:
co-authored by
Claude Sonnet 5.5
parent
4b04c24981
commit
ac60df040f
@@ -1,7 +1,7 @@
|
||||
"""The baseline file: what may be written to it, and what a rewrite may never raise."""
|
||||
import json
|
||||
|
||||
EMPTY = {"violations": [], "oversize": {}, "source": {}}
|
||||
EMPTY = {"violations": [], "oversize": {}, "source": {}, "mechanical_names": []}
|
||||
COMMENT = ("Debt that exists today. Every number may only fall (scripts/check-architecture.py --update-baseline "
|
||||
"refuses to raise one). Do not edit by hand; regenerate. Policy: architecture.json.")
|
||||
|
||||
@@ -16,13 +16,14 @@ def save(path, baseline):
|
||||
handle.write(json.dumps(baseline, indent=1) + "\n")
|
||||
|
||||
|
||||
def build(limit, violations, sizes, counts):
|
||||
def build(limit, violations, sizes, counts, names=()):
|
||||
"""The baseline that describes the current state."""
|
||||
return {
|
||||
"_comment": COMMENT,
|
||||
"violations": sorted(violations),
|
||||
"oversize": {p: n for p, n in sorted(sizes.items()) if n > limit},
|
||||
"source": dict(sorted(counts.items())),
|
||||
"mechanical_names": sorted(names),
|
||||
}
|
||||
|
||||
|
||||
@@ -92,4 +93,7 @@ def raised_source(old, new):
|
||||
def raised(old, new):
|
||||
"""Everything a baseline rewrite would raise."""
|
||||
problems = [f"new violation {v}" for v in new["violations"] if v not in old["violations"]]
|
||||
return problems + raised_oversize(old["oversize"], new["oversize"]) + raised_source(old["source"], new["source"])
|
||||
names = [f"new mechanical file name {p}" for p in new.get("mechanical_names", [])
|
||||
if p not in old.get("mechanical_names", [])]
|
||||
sections = raised_oversize(old["oversize"], new["oversize"]) + raised_source(old["source"], new["source"])
|
||||
return problems + sections + names
|
||||
|
||||
@@ -42,7 +42,7 @@ def update_baseline(path, old, current, allow_increase):
|
||||
return 1
|
||||
bl.save(path, current)
|
||||
print(f"wrote {path.name}: {len(current['violations'])} violations, {len(current['oversize'])} oversize files, "
|
||||
f"{len(current['source'])} ratchets")
|
||||
f"{len(current['source'])} ratchets, {len(current['mechanical_names'])} mechanical file names")
|
||||
return 0
|
||||
|
||||
|
||||
@@ -67,11 +67,12 @@ def main(argv, default_root):
|
||||
packages = measure.load_metadata(root)
|
||||
sizes = measure.file_lines(root, packages)
|
||||
counts = measure.count_patterns(packages, config["source_patterns"])
|
||||
found = rules.evaluate(packages, config, old, sizes, counts)
|
||||
names = measure.mechanical_names(root, packages, config.get("mechanical_names", {}))
|
||||
found = rules.evaluate(packages, config, old, rules.Measured(sizes, counts, names))
|
||||
if args.report:
|
||||
report(packages, config, sizes, counts)
|
||||
return 0
|
||||
if args.update_baseline:
|
||||
current = bl.build(config["max_lines"], found.violations, sizes, counts)
|
||||
current = bl.build(config["max_lines"], found.violations, sizes, counts, names)
|
||||
return update_baseline(baseline_path, old, current, args.allow_increase)
|
||||
return print_findings(found)
|
||||
|
||||
@@ -45,6 +45,19 @@ def file_lines(root, packages):
|
||||
return sizes
|
||||
|
||||
|
||||
def mechanical_names(root, packages, config):
|
||||
"""Sorted relative paths of the .rs files whose NAME is a leftover of a mechanical split (`impl_*.rs`,
|
||||
`*_fn.rs`, `*_<N>.rs`): a name must say what the module is and what it is for. `allow` lists legitimate stems."""
|
||||
bad = [re.compile(p) for p in config.get("patterns", [])]
|
||||
ok = [re.compile(p) for p in config.get("allow", [])]
|
||||
found = set()
|
||||
for pkg in packages:
|
||||
for path in rust_files(pkg["dir"]):
|
||||
if any(p.search(path.name) for p in bad) and not any(p.search(path.name) for p in ok):
|
||||
found.add(path.relative_to(root).as_posix())
|
||||
return sorted(found)
|
||||
|
||||
|
||||
def is_test_file(path, src):
|
||||
"""A test module in its own file counts like the inline `#[cfg(test)]` module it replaces."""
|
||||
parts = path.relative_to(src).parts
|
||||
|
||||
@@ -117,13 +117,32 @@ def ratchet_findings(counts, baseline):
|
||||
return errors, stale
|
||||
|
||||
|
||||
def evaluate(packages, config, baseline, sizes, counts):
|
||||
"""Run every rule. Returns Findings."""
|
||||
def mechanical_findings(names, baseline):
|
||||
"""(errors, stale) for file names left over from mechanical splits: none may be new, the baselined ones only go."""
|
||||
known = set(baseline.get("mechanical_names", []))
|
||||
errors = [f"{path}: a file name from a mechanical split (impl_*, *_fn, *_<N>); name it for what it is and what "
|
||||
f"it is for" for path in names if path not in known]
|
||||
stale = [f"mechanical file name is gone: {path}: tighten the baseline" for path in sorted(known - set(names))]
|
||||
return errors, stale
|
||||
|
||||
|
||||
@dataclass
|
||||
class Measured:
|
||||
"""What was measured in the source tree: file line counts, source pattern counts, mechanical file names."""
|
||||
sizes: dict
|
||||
counts: dict
|
||||
names: tuple = ()
|
||||
|
||||
|
||||
def evaluate(packages, config, baseline, measured):
|
||||
"""Run every rule on the package graph and the measurements. Returns Findings."""
|
||||
sizes, counts, names = measured.sizes, measured.counts, measured.names
|
||||
result = Findings(errors=assignment_errors(packages, config))
|
||||
result.violations = graph_violations(packages, config)
|
||||
errors, result.debt, stale = classify(result.violations, baseline)
|
||||
size_errors, size_stale = size_findings(sizes, baseline, config["max_lines"])
|
||||
ratchet_errors, ratchet_stale = ratchet_findings(counts, baseline)
|
||||
result.errors += errors + size_errors + ratchet_errors
|
||||
result.stale = stale + size_stale + ratchet_stale
|
||||
name_errors, name_stale = mechanical_findings(names, baseline)
|
||||
result.errors += errors + size_errors + ratchet_errors + name_errors
|
||||
result.stale = stale + size_stale + ratchet_stale + name_stale
|
||||
return result
|
||||
|
||||
@@ -39,7 +39,7 @@ def packages(**overrides):
|
||||
|
||||
|
||||
def run(pkgs, baseline=None, sizes=None, counts=None):
|
||||
return rules.evaluate(pkgs, CONFIG, baseline or EMPTY, sizes or {}, counts or {})
|
||||
return rules.evaluate(pkgs, CONFIG, baseline or EMPTY, rules.Measured(sizes or {}, counts or {}))
|
||||
|
||||
|
||||
def base(violations=(), oversize=None, source=None):
|
||||
@@ -129,6 +129,41 @@ class BaselineRewrite(unittest.TestCase):
|
||||
self.assertEqual(len(bl.raised(old, base(oversize={"src/big.rs": 600, "src/big/part.rs": 480}))), 1)
|
||||
|
||||
|
||||
class MechanicalNames(unittest.TestCase):
|
||||
"""A file named by a mechanical split (impl_*, *_fn, numbered) may not be new; the baselined ones only go."""
|
||||
|
||||
DOT = chr(92) + ".rs$"
|
||||
SPEC = {"patterns": ["^impl_.*" + DOT, "_fn" + DOT, "_[0-9]+(_[0-9]+)*" + DOT], "allow": ["^q[0-9]_[0-9]" + DOT]}
|
||||
|
||||
def test_a_new_mechanical_name_is_an_error_and_a_baselined_one_is_debt(self):
|
||||
known = dict(EMPTY, mechanical_names=["src/impl_old.rs"])
|
||||
found = run(packages(), known).errors
|
||||
self.assertEqual(found, [])
|
||||
errors, _ = rules.mechanical_findings(["src/impl_old.rs", "src/impl_new.rs"], known)
|
||||
self.assertEqual(len(errors), 1)
|
||||
self.assertIn("src/impl_new.rs", errors[0])
|
||||
|
||||
def test_a_file_that_was_renamed_makes_its_baseline_entry_stale(self):
|
||||
known = dict(EMPTY, mechanical_names=["src/impl_old.rs"])
|
||||
self.assertEqual(rules.mechanical_findings([], known)[0], [])
|
||||
self.assertEqual(len(rules.mechanical_findings([], known)[1]), 1)
|
||||
|
||||
def test_the_rewrite_may_not_add_a_mechanical_name(self):
|
||||
old = dict(base(), mechanical_names=["a/impl_x.rs"])
|
||||
self.assertEqual(bl.raised(old, dict(base(), mechanical_names=[])), [])
|
||||
self.assertEqual(len(bl.raised(old, dict(base(), mechanical_names=["a/impl_x.rs", "a/b_fn.rs"]))), 1)
|
||||
|
||||
def test_the_measurement_matches_the_patterns_and_honours_the_allow_list(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = pathlib.Path(tmp) / "src"
|
||||
src.mkdir()
|
||||
for name in ("impl_a.rs", "b_fn.rs", "c_2.rs", "d_2_3.rs", "q4_0.rs", "plain.rs", "tests.rs"):
|
||||
(src / name).write_text("")
|
||||
package = dict(pkg("p"), dir=pathlib.Path(tmp))
|
||||
found = measure.mechanical_names(pathlib.Path(tmp), [package], self.SPEC)
|
||||
self.assertEqual(found, ["src/b_fn.rs", "src/c_2.rs", "src/d_2_3.rs", "src/impl_a.rs"])
|
||||
|
||||
|
||||
class Measurement(unittest.TestCase):
|
||||
def test_counter_stops_at_a_test_module_and_skips_comments(self):
|
||||
text = 'let a = std::env::var("A");\n// env::var("B")\n#[cfg(test)]\nmod t {}\nlet c = env::var("C");\n'
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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__":
|
||||
|
||||
Reference in New Issue
Block a user