diff options
Diffstat (limited to 'tools/arch-census.py')
| -rwxr-xr-x | tools/arch-census.py | 108 |
1 files changed, 100 insertions, 8 deletions
diff --git a/tools/arch-census.py b/tools/arch-census.py index 09f4201..a0f436f 100755 --- a/tools/arch-census.py +++ b/tools/arch-census.py @@ -24,6 +24,14 @@ 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. +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` +of `module.item` -> one-line reason for every item deliberately kept. `--budget` +reads that file and fails on an excess, on a dead item nobody argued for, and on +an allowlist entry that no longer names a real item — a stale permission is as +bad as a missing one, because it is how an item comes back unnoticed. + Reported per module: pub items declared `pub` (fn, struct, enum, trait, const, static, type) dead of those, ones no file outside the module names — including tests/ @@ -46,6 +54,7 @@ Usage: tools/arch-census.py --record FILE append a dated section to a markdown file 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 """ import argparse @@ -107,15 +116,20 @@ def module_of(path): def declarations(texts): - """Every `pub` item name, with the modules that declare it and the files.""" + """Every `pub` item name, with every place that declares it. + + Each entry is `(path, lineno)`, because a count cannot be acted on: the + question a reader asks of a dead item is *where is it*, and a census that can + only answer "db has 8" sends them back to grep. + """ names = collections.defaultdict(list) for path, text in texts.items(): - for line in text.splitlines(): + for lineno, line in enumerate(text.splitlines(), 1): if COMMENT.match(line): continue m = PUB_RE.match(line) if m: - names[m.group(1)].append(path) + names[m.group(1)].append((path, lineno)) return names @@ -156,10 +170,11 @@ def census(): row["largest"] = size row["largest_file"] = os.path.relpath(path, ROOT) + dead_items = [] # A name is dead when no file outside the module that declares it says it. # A name declared in two modules is only dead if neither is referenced. for name, paths in names.items(): - declaring = {module_of(p) for p in paths} + declaring = {module_of(p) for p, _ in paths} for mod in declaring: rows[mod]["pub"] += 1 outside = any( @@ -175,6 +190,14 @@ def census(): rows[mod]["test"] += 1 else: rows[mod]["deadonly"] += 1 + here, line = next((pl for pl in paths if module_of(pl[0]) == mod)) + dead_items.append({ + "module": mod, + "name": name, + "kind": "test" if used_by_tests else "deadonly", + "file": os.path.relpath(here, ROOT), + "line": line, + }) edges = collections.defaultdict(set) for path, text in src_texts.items(): @@ -187,8 +210,10 @@ def census(): if target in rows and target != src_mod: edges[src_mod].add(target) + dead_items.sort(key=lambda d: (d["module"], d["name"])) return { "modules": rows, + "dead_items": dead_items, "edges": {k: sorted(v) for k, v in sorted(edges.items())}, "totals": { "pub": sum(r["pub"] for r in rows.values()), @@ -228,6 +253,55 @@ def check_budget(data, budget): return over +def dead_code_section(budget): + """The `dead_code` section as `(accepted deadonly per module, allowlist)`.""" + section = budget.get("dead_code", {}) + return section.get("deadonly", {}), section.get("allowlist", {}) + + +def check_dead_code(data, budget): + """Every surviving dead item is counted, named, and argued — or it fails. + + Three ways to fail, because three things go wrong. A module can grow past its + 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. + """ + accepted, allowlist = dead_code_section(budget) + problems = [] + actual = {mod: row["deadonly"] 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}.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") + 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")): + 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") + + def print_census(data): totals = data["totals"] width = max(len(m) for m in data["modules"]) @@ -280,6 +354,7 @@ def main(): ap.add_argument("--record", metavar="FILE", help="append a dated section to a markdown file") 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") args = ap.parse_args() data = census() @@ -288,6 +363,8 @@ def main(): # Preserve any section another tool owns (for example `test_surface`, # written by tools/test-surface.py). Two writers of one file must not # erase each other, or the ratchet silently stops checking one axis. + # The same rule applies inside `dead_code`: the accepted counts are this + # tool's to write, the allowlist is a human's to argue. existing = {} if os.path.exists(args.write_budget): try: @@ -297,6 +374,11 @@ def main(): out = dict(existing) out["modules"] = data["modules"] out["totals"] = data["totals"] + dead_code = dict(out.get("dead_code") or {}) + dead_code["deadonly"] = { + mod: row["deadonly"] for mod, row in sorted(data["modules"].items()) + } + out["dead_code"] = dead_code with open(args.write_budget, "w") as handle: json.dump(out, handle, indent=2, sort_keys=True) @@ -308,16 +390,26 @@ def main(): print(json.dumps(data, indent=2, sort_keys=True)) return 0 + if args.list_dead: + list_dead(data) + return 0 + print_census(data) if args.budget: with open(args.budget) as handle: budget = json.load(handle) over = check_budget(data, budget) - if over: - print("\nOVER BUDGET — these numbers grew:") - for mod, key, allowed, actual in over: - print(f" {mod}.{key}: {actual} > {allowed}") + problems = check_dead_code(data, budget) + if over or problems: + if over: + print("\nOVER BUDGET — these numbers grew:") + for mod, key, allowed, actual in over: + print(f" {mod}.{key}: {actual} > {allowed}") + if problems: + print("\nDEAD CODE — every survivor must be counted, named and argued:") + for problem in problems: + print(f" {problem}") return 1 print(f"\nwithin budget: {args.budget}") |
