summaryrefslogtreecommitdiffstats
path: root/tools
diff options
context:
space:
mode:
Diffstat (limited to 'tools')
-rwxr-xr-xtools/arch-census.py206
1 files changed, 191 insertions, 15 deletions
diff --git a/tools/arch-census.py b/tools/arch-census.py
index b734061..231073c 100755
--- a/tools/arch-census.py
+++ b/tools/arch-census.py
@@ -30,6 +30,17 @@ as used: `watch::upstream::resolve` looked live for as long as some unrelated
db message happened to end "... to resolve". A flagged item is a question; a
clean item is not always an answer.
+`pub(crate)` is not automatically the narrow state. A `pub(crate)` item whose
+name is never written outside the one file that declares it is *over-wide*: it
+says "the whole crate may reach this" about something only its own file reaches,
+and it is one keystroke away from being a hole in the module's real interface.
+`overwide` counts those. The search space is `src/` only, because `tests/` is a
+separate crate and cannot name a `pub(crate)` item at all, so a test mentioning
+the word says nothing about crate-internal visibility. Like every other column
+here the flag is a lead, not a verdict — a `pub(crate)` type that appears in a
+`pub` signature in its own file cannot go private without a private-in-public
+error — and the compiler, not this file, decides.
+
The census counts; it does not remember. What is *accepted* lives in exactly one
machine-parsable file, `tests/architecture-budget.json`, which holds a
`dead_code` section: the accepted `deadonly` count per module, and an `allowlist`
@@ -44,12 +55,21 @@ Reported per module:
test of the dead ones, the ones a test does name: pub for the test tier
deadonly dead minus test: exported, and named by nobody at all
priv items declared `pub(crate)`: crate-internal on purpose
+ overwide of those, ones no file outside the declaring file names: wider than
+ anything reaches, and a candidate for plain private
glob `use … ::*` re-exports, which flatten a namespace and hide width
lines total lines of the module, and its largest single file
Reported for the crate: the `crate::x` edge set between modules, which is the
dependency graph the layer map in tests/architecture.rs is allowed to be.
+The over-wide count is held down the same way `deadonly` is: an item that stays
+`pub(crate)` despite nothing outside its file reading it is allowed only by name,
+in `over_visibility.allowlist`, with the compiler fact that forces it written
+beside it. `over_visibility.overwide` is the accepted count per module, and
+`--budget` fails on an excess, on an unargued item, and on a permission whose
+item is gone.
+
`tests/architecture.rs` enforces the same two definitions against a committed
budget and fails when a number grows; this tool is the human-facing report of
where the numbers are and where they moved.
@@ -61,6 +81,7 @@ Usage:
tools/arch-census.py --budget FILE compare against a budget, exit 1 if over
tools/arch-census.py --write-budget FILE write the current numbers as budget
tools/arch-census.py --list-dead name every dead item, with file:line
+ tools/arch-census.py --list-overwide name every over-wide pub(crate) item
"""
import argparse
@@ -81,6 +102,9 @@ PUB_CRATE_RE = re.compile(r"^\s*pub\(crate\)\s+(?:fn|struct|enum|trait|const|sta
PUB_CRATE_NAME_RE = re.compile(
r"^\s*pub\(crate\)\s+(?:fn|struct|enum|trait|const|static|type)\s+([A-Za-z0-9_]+)"
)
+# `pub(crate) use` is a re-export, not a declaration; the same rule the `pub`
+# side follows, so a re-export cannot be counted as an item that could be private.
+PUB_CRATE_USE_RE = re.compile(r"^\s*pub\(crate\)\s+use\s+")
GLOB_RE = re.compile(r"^\s*pub(?:\(crate\))?\s+use\s+[^\n]*::\*")
EDGE_RE = re.compile(r"\bcrate::([a-z_][a-z0-9_]*)")
# The binaries are separate crates, so they name the library through its own
@@ -101,6 +125,17 @@ def load_allowlist(path=None):
return allow if isinstance(allow, dict) else {}
+def load_over_visibility(path=None):
+ """The `module.item` names that stay `pub(crate)` by decision, with reasons."""
+ try:
+ with open(path or BUDGET) as handle:
+ section = json.load(handle).get("over_visibility", {})
+ except (ValueError, OSError):
+ return {}
+ allow = section.get("allowlist", {})
+ return allow if isinstance(allow, dict) else {}
+
+
def rust_files(*dirs):
out = []
for d in dirs:
@@ -154,19 +189,43 @@ def declarations(texts):
return names
-def census(allow=None):
+def pub_crate_declarations(texts):
+ """Every `pub(crate)` item name, with every place that declares it.
+
+ The twin of `declarations`, and it exists for the same reason: a count of
+ over-wide items is only useful if the tool can say which file and line.
+ `pub(crate) use` is a re-export and is not an item, so it is not a candidate
+ for going private on its own.
+ """
+ names = collections.defaultdict(list)
+ for path, text in texts.items():
+ for lineno, line in enumerate(text.splitlines(), 1):
+ if COMMENT.match(line) or PUB_CRATE_USE_RE.match(line):
+ continue
+ m = PUB_CRATE_NAME_RE.match(line)
+ if m:
+ names[m.group(1)].append((path, lineno))
+ return names
+
+
+def census(allow=None, over_allow=None):
allow = set(load_allowlist() if allow is None else allow)
+ over_allow = set(load_over_visibility() if over_allow is None else over_allow)
src_files = rust_files(SRC)
test_files = rust_files(TESTS)
src_texts = read_all(src_files)
test_texts = read_all(test_files)
names = declarations(src_texts)
+ pc_names = pub_crate_declarations(src_texts)
mods = sorted({module_of(p) for p in src_files})
rows = {}
# Every name a module declares, `pub` or `pub(crate)`. The allowlist is
# checked against this, so a permission cannot outlive the item it names.
declared = collections.defaultdict(set)
+ # Only the `pub(crate)` half, because an over-wide permission has to name a
+ # `pub(crate)` item: a key pointing at a `pub` one excuses nothing.
+ pc_declared = collections.defaultdict(set)
for mod in mods:
rows[mod] = {
"pub": 0,
@@ -174,6 +233,7 @@ def census(allow=None):
"test": 0,
"deadonly": 0,
"priv": 0,
+ "overwide": 0,
"glob": 0,
"lines": 0,
"largest": 0,
@@ -191,6 +251,7 @@ def census(allow=None):
m = PUB_CRATE_NAME_RE.match(line)
if m:
declared[module_of(path)].add(m.group(1))
+ pc_declared[module_of(path)].add(m.group(1))
if GLOB_RE.match(line):
row["glob"] += 1
size = text.count("\n") + 1
@@ -240,6 +301,41 @@ def census(allow=None):
"line": line,
})
+ overwide_items = []
+ # A `pub(crate)` name is over-wide when no file except the one that declares
+ # it says the word. `tests/` is not consulted: it is a separate crate and
+ # cannot name a `pub(crate)` item, so a mention there is noise. As with
+ # `dead`, a name declared in several files is only flagged when none of them
+ # is read from outside any of them — the flag is a lead, and a false one is
+ # cheaper than a missed one.
+ for name, places in sorted(pc_names.items()):
+ declaring = {p for p, _ in places}
+ outside = any(
+ p not in declaring and re.search(r"\b%s\b" % re.escape(name), t)
+ for p, t in src_texts.items()
+ )
+ if outside:
+ continue
+ for path, line in places:
+ mod = module_of(path)
+ if f"{mod}.{name}" in over_allow:
+ overwide_items.append({
+ "module": mod,
+ "name": name,
+ "kind": "allowlisted",
+ "file": os.path.relpath(path, ROOT),
+ "line": line,
+ })
+ continue
+ rows[mod]["overwide"] += 1
+ overwide_items.append({
+ "module": mod,
+ "name": name,
+ "kind": "overwide",
+ "file": os.path.relpath(path, ROOT),
+ "line": line,
+ })
+
edges = collections.defaultdict(set)
for path, text in src_texts.items():
src_mod = module_of(path)
@@ -252,10 +348,13 @@ def census(allow=None):
edges[src_mod].add(target)
dead_items.sort(key=lambda d: (d["module"], d["name"]))
+ overwide_items.sort(key=lambda d: (d["module"], d["name"], d["file"], d["line"]))
return {
"modules": rows,
"dead_items": dead_items,
+ "overwide_items": overwide_items,
"declared": {mod: sorted(v) for mod, v in sorted(declared.items())},
+ "pc_declared": {mod: sorted(v) for mod, v in sorted(pc_declared.items())},
"edges": {k: sorted(v) for k, v in sorted(edges.items())},
"totals": {
"pub": sum(r["pub"] for r in rows.values()),
@@ -263,6 +362,7 @@ def census(allow=None):
"test": sum(r["test"] for r in rows.values()),
"deadonly": sum(r["deadonly"] for r in rows.values()),
"priv": sum(r["priv"] for r in rows.values()),
+ "overwide": sum(r["overwide"] for r in rows.values()),
"glob": sum(r["glob"] for r in rows.values()),
"edges": sum(len(v) for v in edges.values()),
"lines": sum(r["lines"] for r in rows.values()),
@@ -275,9 +375,11 @@ def census(allow=None):
# `priv` is deliberately absent: a `pub(crate)` item is the good state, so a
-# rising count is progress and must never be a ceiling. The same list is
+# rising count is progress and must never be a ceiling. `overwide` is the
+# opposite: it counts the `pub(crate)` items nothing outside their own file
+# reaches, and the only direction that number may move is down. The same list is
# mirrored by `budgeted` in tests/architecture.rs.
-BUDGET_KEYS = ("pub", "dead", "test", "deadonly", "glob")
+BUDGET_KEYS = ("pub", "dead", "test", "deadonly", "overwide", "glob")
def check_budget(data, budget):
@@ -338,6 +440,48 @@ def check_dead_code(data, budget):
return problems
+def over_visibility_section(budget):
+ """The `over_visibility` section as `(accepted overwide per module, allowlist)`."""
+ section = budget.get("over_visibility", {})
+ return section.get("overwide", {}), section.get("allowlist", {})
+
+
+def check_over_visibility(data, budget):
+ """Every surviving over-wide item is counted, named and argued — or it fails.
+
+ The mirror of `check_dead_code` for the `pub(crate)` side, with the same
+ three failures: a module past its accepted count, an item nobody argued for,
+ and a permission whose item is gone. A reason has to say why the compiler
+ will not let the item go private — a `pub(crate)` type in a `pub` signature
+ in its own file, a trait impl that has to stay visible — because "it seemed
+ safer" is not a reason and does not stop the next widening.
+ """
+ accepted, allowlist = over_visibility_section(budget)
+ problems = []
+ actual = {mod: row["overwide"] for mod, row in data["modules"].items()}
+ for mod in sorted(set(actual) | set(accepted)):
+ have, allowed = actual.get(mod, 0), accepted.get(mod, 0)
+ if have > allowed:
+ problems.append(f"{mod}.overwide: {have} > {allowed} accepted")
+ for item in data["overwide_items"]:
+ if item["kind"] != "overwide":
+ continue
+ key = f"{item['module']}.{item['name']}"
+ if key not in allowlist:
+ problems.append(f"{key} at {item['file']}:{item['line']} is over-wide and unargued")
+ elif not str(allowlist[key]).strip():
+ problems.append(f"{key} is allowlisted with no reason")
+ pc_declared = data["pc_declared"]
+ for key in sorted(allowlist):
+ mod, _, name = key.partition(".")
+ if name not in pc_declared.get(mod, []):
+ problems.append(
+ f"over_visibility allowlist names {key}, which is no longer a "
+ "`pub(crate)` item here; it is private, or it was never one"
+ )
+ return problems
+
+
def list_dead(data):
"""Name every dead item. A count tells a module is wide; this says which items."""
width = max(len(d["module"]) for d in data["dead_items"]) if data["dead_items"] else 0
@@ -352,20 +496,34 @@ def list_dead(data):
f"{totals['deadonly']} of them unargued")
+def list_overwide(data):
+ """Name every over-wide `pub(crate)` item, with the file that declares it."""
+ items = data["overwide_items"]
+ width = max((len(d["module"]) for d in items), default=0)
+ for kind, label in (("overwide", "wider than anything reaches; a candidate for plain private"),
+ ("allowlisted", "kept `pub(crate)` by decision, reason in the budget file")):
+ rows = [d for d in items if d["kind"] == kind]
+ print(f"\n{label} — {len(rows)} items")
+ for d in rows:
+ print(f" {d['module'].ljust(width)} {d['name'].ljust(34)} {d['file']}:{d['line']}")
+ totals = data["totals"]
+ print(f"\n{totals['overwide']} over-wide of {totals['priv']} pub(crate)")
+
+
def print_census(data):
totals = data["totals"]
width = max(len(m) for m in data["modules"])
print(f"{'module'.ljust(width)} {'pub':>4} {'dead':>5} {'test':>5} {'deadon':>7} "
- f"{'priv':>5} {'glob':>5} {'lines':>6} largest file")
- print("-" * (width + 49))
+ f"{'priv':>5} {'overwd':>7} {'glob':>5} {'lines':>6} largest file")
+ print("-" * (width + 57))
for mod, row in sorted(data["modules"].items()):
print(f"{mod.ljust(width)} {row['pub']:>4} {row['dead']:>5} {row['test']:>5} "
- f"{row['deadonly']:>7} {row['priv']:>5} {row['glob']:>5} {row['lines']:>6} "
- f"{row['largest']:>4} {row['largest_file']}")
- print("-" * (width + 49))
+ f"{row['deadonly']:>7} {row['priv']:>5} {row['overwide']:>7} {row['glob']:>5} "
+ f"{row['lines']:>6} {row['largest']:>4} {row['largest_file']}")
+ print("-" * (width + 57))
print(f"{'total'.ljust(width)} {totals['pub']:>4} {totals['dead']:>5} {totals['test']:>5} "
- f"{totals['deadonly']:>7} {totals['priv']:>5} {totals['glob']:>5} {totals['lines']:>6} "
- f"{totals['largest']:>4} {totals['largest_file']}")
+ f"{totals['deadonly']:>7} {totals['priv']:>5} {totals['overwide']:>7} {totals['glob']:>5} "
+ f"{totals['lines']:>6} {totals['largest']:>4} {totals['largest_file']}")
print(f"\ncrate:: edges between modules: {totals['edges']}")
for src_mod, targets in sorted(data["edges"].items()):
print(f" {src_mod.ljust(width)} -> {' '.join(targets)}")
@@ -382,14 +540,15 @@ def record(data, path):
handle.write(f"totals: {totals['pub']} pub, {totals['dead']} dead "
f"({totals['test']} test-only, {totals['deadonly']} named by nobody), "
f"{totals['priv']} pub(crate), "
+ f"{totals['overwide']} over-wide, "
f"{totals['glob']} glob re-exports, {totals['edges']} edges, "
f"largest file {totals['largest']} ({totals['largest_file']})\n\n")
- handle.write("| module | pub | dead | test-only | dead-only | pub(crate) | glob | lines | largest file |\n")
- handle.write("|---|---|---|---|---|---|---|---|---|\n")
+ handle.write("| module | pub | dead | test-only | dead-only | pub(crate) | over-wide | glob | lines | largest file |\n")
+ handle.write("|---|---|---|---|---|---|---|---|---|---|\n")
for mod, row in sorted(data["modules"].items()):
handle.write(f"| {mod} | {row['pub']} | {row['dead']} | {row['test']} | "
f"{row['deadonly']} | "
- f"{row['priv']} | {row['glob']} | {row['lines']} | "
+ f"{row['priv']} | {row['overwide']} | {row['glob']} | {row['lines']} | "
f"{row['largest']} {row['largest_file']} |\n")
handle.write("\n```\n")
for src_mod, targets in sorted(data["edges"].items()):
@@ -405,10 +564,15 @@ def main():
ap.add_argument("--budget", metavar="FILE", help="fail if a number is over the committed budget")
ap.add_argument("--write-budget", metavar="FILE", help="write the current numbers as the budget")
ap.add_argument("--list-dead", action="store_true", help="name every dead item with its file:line")
+ ap.add_argument("--list-overwide", action="store_true",
+ help="name every over-wide pub(crate) item with its file:line")
ap.add_argument("--allowlist", metavar="FILE", help="read the kept-item allowlist from FILE")
args = ap.parse_args()
- data = census(allow=load_allowlist(args.allowlist) if args.allowlist else None)
+ data = census(
+ allow=load_allowlist(args.allowlist) if args.allowlist else None,
+ over_allow=load_over_visibility(args.allowlist) if args.allowlist else None,
+ )
if args.write_budget:
# Preserve any section another tool owns (for example `test_surface`,
@@ -430,6 +594,14 @@ def main():
mod: row["deadonly"] for mod, row in sorted(data["modules"].items())
}
out["dead_code"] = dead_code
+ # Same split as `dead_code`: the accepted count is the tool's to write,
+ # the allowlist of kept `pub(crate)` items is a human's to argue.
+ over = dict(out.get("over_visibility") or {})
+ over.setdefault("allowlist", {})
+ over["overwide"] = {
+ mod: row["overwide"] for mod, row in sorted(data["modules"].items())
+ }
+ out["over_visibility"] = over
with open(args.write_budget, "w") as handle:
json.dump(out, handle, indent=2,
sort_keys=True)
@@ -445,13 +617,17 @@ def main():
list_dead(data)
return 0
+ if args.list_overwide:
+ list_overwide(data)
+ return 0
+
print_census(data)
if args.budget:
with open(args.budget) as handle:
budget = json.load(handle)
over = check_budget(data, budget)
- problems = check_dead_code(data, budget)
+ problems = check_dead_code(data, budget) + check_over_visibility(data, budget)
if over or problems:
if over:
print("\nOVER BUDGET — these numbers grew:")