diff options
| author | aur-build <aur-build@localhost> | 2026-11-21 13:28:55 +0000 |
|---|---|---|
| committer | aur-build <aur-build@localhost> | 2026-11-21 13:28:55 +0000 |
| commit | 48fecfe03be4f214eaf4f9c49cb3c27496bb74ba (patch) | |
| tree | 432f6e32351df60d36a115561c1bf8b8013c5430 /tools/arch-census.py | |
| parent | a200edaac2056dd9c85d6bddff3ca181f0cc277e (diff) | |
| download | aur-build-48fecfe03be4f214eaf4f9c49cb3c27496bb74ba.tar.gz aur-build-48fecfe03be4f214eaf4f9c49cb3c27496bb74ba.zip | |
src: narrow what only its own module reads, and delete what nothing reads at all
The census's 35 `deadonly` items were a lead, not a verdict, and the compiler
answered it: 17 of them are read only inside their own module and were declared
`pub` for no reason, so they are `pub(crate)` now — `db::OpenReview` and its two
queries, `ReviewSubject` and its query, `fetch::Body`, `http`'s `form_get`,
`query_get` and `Page::flash`, `ops::EvictPlan`, `usecase`'s `StageB`… — and two
are read by nobody: `ReleaseState::can_transition` and
`SubscriptionState::can_transition`, both already annotated "nothing consults
this table today", which is the definition of dead rather than the argument for
keeping.
Narrowing them is what made the compiler look harder, and it found three more:
`ReviewSubject::pkgbase` was selected out of the database and never read,
`StageB::cached` was written in three places and never read, and
`StageB::version` was never called. All gone, the SELECT column with them.
The other 18 cannot be narrowed and now say so, once at the declaration and once
in the budget file: a row type the `aur-build` binary binds without naming
(`PackageRow`, `Checked`, `GcPlan`, `Prepared`), a type behind a `pub` fn a test
calls (`Unbuilt`, `BulkItem`, `StageA`, `CheckReport`, `PkgInfo`, `Installed`,
`Subscription`, `Manifest`), a trait a public test provisioner implements
(`Provisioner`, `ProvisionRequest`), and three that a release build never even
compiles because their module is `test-support`-gated (`shims::*`, `VirtualClock`).
`deadonly` therefore means *dead and unargued* now: an allowlisted item leaves the
dead columns, which is the only way the number can be held at zero forever.
448 pub, 49 dead, 0 unargued; 284 tests pass, one ignored, none lost.
Diffstat (limited to 'tools/arch-census.py')
| -rwxr-xr-x | tools/arch-census.py | 67 |
1 files changed, 59 insertions, 8 deletions
diff --git a/tools/arch-census.py b/tools/arch-census.py index a0f436f..b734061 100755 --- a/tools/arch-census.py +++ b/tools/arch-census.py @@ -18,6 +18,12 @@ real is to privatize them and let the compiler answer: it rejects the ones that are load-bearing and says nothing about the rest. Whatever survives that is budgeted rather than zeroed, and the budget is where the reason lives. +An item whose reason has been written is no longer a hole, so it is not counted +as one: the `dead_code.allowlist` in `tests/architecture-budget.json` names +every item that stays `pub` by decision, and those items leave the `dead`, +`test` and `deadonly` columns. `deadonly` therefore means *dead and unargued*, +which is the one number that can honestly be held at zero forever. + The metric errs the other way too. Mentions are matched as words over the raw file, so a name that appears only inside someone else's error *string* counts as used: `watch::upstream::resolve` looked live for as long as some unrelated @@ -72,12 +78,27 @@ TESTS = os.path.join(ROOT, "tests") # A declaration, not a re-export: `pub use` is counted separately as a glob. PUB_RE = re.compile(r"^\s*pub\s+(?:fn|struct|enum|trait|const|static|type)\s+([A-Za-z0-9_]+)") PUB_CRATE_RE = re.compile(r"^\s*pub\(crate\)\s+(?:fn|struct|enum|trait|const|static|type)\s+") +PUB_CRATE_NAME_RE = re.compile( + r"^\s*pub\(crate\)\s+(?:fn|struct|enum|trait|const|static|type)\s+([A-Za-z0-9_]+)" +) 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 # name rather than through `crate::`. Those edges are part of the graph too. LIB_EDGE_RE = re.compile(r"\baur_build::([a-z_][a-z0-9_]*)") COMMENT = re.compile(r"^\s*(?://|//!|///)") +BUDGET = os.path.join(ROOT, "tests", "architecture-budget.json") + + +def load_allowlist(path=None): + """The `module.item` names that stay `pub` by decision, with their reasons.""" + try: + with open(path or BUDGET) as handle: + section = json.load(handle).get("dead_code", {}) + except (ValueError, OSError): + return {} + allow = section.get("allowlist", {}) + return allow if isinstance(allow, dict) else {} def rust_files(*dirs): @@ -133,7 +154,8 @@ def declarations(texts): return names -def census(): +def census(allow=None): + allow = set(load_allowlist() if allow is None else allow) src_files = rust_files(SRC) test_files = rust_files(TESTS) src_texts = read_all(src_files) @@ -142,6 +164,9 @@ def census(): 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) for mod in mods: rows[mod] = { "pub": 0, @@ -163,6 +188,9 @@ def census(): continue if PUB_CRATE_RE.match(line): row["priv"] += 1 + m = PUB_CRATE_NAME_RE.match(line) + if m: + declared[module_of(path)].add(m.group(1)) if GLOB_RE.match(line): row["glob"] += 1 size = text.count("\n") + 1 @@ -176,6 +204,8 @@ def census(): for name, paths in names.items(): declaring = {module_of(p) for p, _ in paths} for mod in declaring: + declared[mod].add(name) + for mod in declaring: rows[mod]["pub"] += 1 outside = any( module_of(p) not in declaring and re.search(r"\b%s\b" % re.escape(name), t) @@ -185,6 +215,17 @@ def census(): continue used_by_tests = any(re.search(r"\b%s\b" % re.escape(name), t) for t in test_texts.values()) for mod in declaring: + if f"{mod}.{name}" in allow: + # Argued, so not a hole: it stays `pub` on purpose and the reason + # is in the budget file next to its name. + dead_items.append({ + "module": mod, + "name": name, + "kind": "allowlisted", + "file": os.path.relpath(next(p for p, _ in paths if module_of(p) == mod), ROOT), + "line": next(ln for p, ln in paths if module_of(p) == mod), + }) + continue rows[mod]["dead"] += 1 if used_by_tests: rows[mod]["test"] += 1 @@ -214,6 +255,7 @@ def census(): return { "modules": rows, "dead_items": dead_items, + "declared": {mod: sorted(v) for mod, v in sorted(declared.items())}, "edges": {k: sorted(v) for k, v in sorted(edges.items())}, "totals": { "pub": sum(r["pub"] for r in rows.values()), @@ -266,6 +308,12 @@ def check_dead_code(data, budget): accepted count. An item can appear that no one argued for. And an allowlist entry can outlive the item it excused, which is how a deleted item comes back: the permission is still on the books, so nobody notices the new one. + + An entry stays valid while the item it names is still declared in that module, + even once the item has been narrowed to `pub(crate)` — the reason a caller + outside the module does not name it is worth keeping. Re-widening a narrowed + item is not caught here; it raises the module's `deadonly` over its accepted + count, which is what the count is for. """ accepted, allowlist = dead_code_section(budget) problems = [] @@ -274,32 +322,34 @@ def check_dead_code(data, budget): have, allowed = actual.get(mod, 0), accepted.get(mod, 0) if have > allowed: problems.append(f"{mod}.deadonly: {have} > {allowed} accepted") - named = set() for item in data["dead_items"]: if item["kind"] != "deadonly": continue key = f"{item['module']}.{item['name']}" - named.add(key) if key not in allowlist: problems.append(f"{key} at {item['file']}:{item['line']} is dead and unargued") elif not str(allowlist[key]).strip(): problems.append(f"{key} is allowlisted with no reason") - for key in sorted(set(allowlist) - named): - problems.append(f"allowlist names {key}, which is not dead; delete the permission") + declared = data["declared"] + for key in sorted(allowlist): + mod, _, name = key.partition(".") + if name not in declared.get(mod, []): + problems.append(f"allowlist names {key}, which no module member is; delete the permission") 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 - for kind, label in (("deadonly", "named by nobody"), ("test", "named only by tests")): + for kind, label in (("deadonly", "named by nobody"), ("test", "named only by tests"), + ("allowlisted", "kept `pub` by decision, reason in the budget file")): rows = [d for d in data["dead_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['dead']} dead of {totals['pub']} pub; " - f"{totals['deadonly']} of them named by nobody") + f"{totals['deadonly']} of them unargued") def print_census(data): @@ -355,9 +405,10 @@ 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("--allowlist", metavar="FILE", help="read the kept-item allowlist from FILE") args = ap.parse_args() - data = census() + data = census(allow=load_allowlist(args.allowlist) if args.allowlist else None) if args.write_budget: # Preserve any section another tool owns (for example `test_surface`, |
