summaryrefslogtreecommitdiffstats
path: root/tools/arch-census.py
blob: a0f436ff06ec619defc9dc1f9778aad15ccbdb30 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#!/usr/bin/env python3
"""Census the module tree: how wide each interface is, and what reaches into what.

An interface is only as narrow as the items a module actually hands out, so the
two numbers that matter are how many `pub` items a module declares and how many
of them nothing outside that module ever names. A `pub` item with no outside
reader is not an interface, it is a hole: every one of them is a thing a caller
may depend on and a thing a later refactor cannot change without a grep across
the crate. `tests/` counts as an outside reader on purpose — the integration
tests are separate crates, so a name only they use is genuinely `pub`, and the
honest way to say that is to count it rather than pretend it is private.

What `dead` means precisely is *the name is never written outside the module*.
That is a lead, not a verdict. A row type returned by a public query is part of
the interface even though no caller ever writes its name — they bind it with
`let` and call methods on it — so the way to find out which flagged items are
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.

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
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/
  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
  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.

`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.

Usage:
  tools/arch-census.py                 print the census
  tools/arch-census.py --json          the same numbers as JSON
  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
import collections
import json
import os
import re
import sys
from datetime import datetime, timezone

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = os.path.join(ROOT, "src")
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+")
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*(?://|//!|///)")


def rust_files(*dirs):
    out = []
    for d in dirs:
        for base, _, names in os.walk(d):
            for name in names:
                if name.endswith(".rs"):
                    out.append(os.path.join(base, name))
    return sorted(out)


def read_all(files):
    texts = {}
    for path in files:
        with open(path, errors="replace") as handle:
            texts[path] = handle.read()
    return texts


def module_of(path):
    """The module a file belongs to.

    A directory is one module (`src/db/*.rs` is `db`); a top-level file is a
    module of its own (`src/ops.rs` is `ops`), because a layer map that lumps
    eleven unrelated files into one box cannot say anything about them. The
    binaries are separate crates and keep their own names.
    """
    rel = os.path.relpath(path, SRC)
    parts = rel.split(os.sep)
    if parts[0] == "bin":
        return os.path.join("bin", *parts[1:]).removesuffix(".rs")
    if len(parts) > 1:
        return parts[0]
    return parts[0].removesuffix(".rs")


def declarations(texts):
    """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 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, lineno))
    return names


def census():
    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)

    mods = sorted({module_of(p) for p in src_files})
    rows = {}
    for mod in mods:
        rows[mod] = {
            "pub": 0,
            "dead": 0,
            "test": 0,
            "deadonly": 0,
            "priv": 0,
            "glob": 0,
            "lines": 0,
            "largest": 0,
            "largest_file": "",
        }

    for path, text in src_texts.items():
        row = rows[module_of(path)]
        row["lines"] += text.count("\n") + 1
        for line in text.splitlines():
            if COMMENT.match(line):
                continue
            if PUB_CRATE_RE.match(line):
                row["priv"] += 1
            if GLOB_RE.match(line):
                row["glob"] += 1
        size = text.count("\n") + 1
        if size > row["largest"]:
            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}
        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)
            for p, t in src_texts.items()
        )
        if outside:
            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:
            rows[mod]["dead"] += 1
            if used_by_tests:
                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():
        src_mod = module_of(path)
        pattern = LIB_EDGE_RE if src_mod.startswith("bin") or src_mod == "main" else EDGE_RE
        for line in text.splitlines():
            if COMMENT.match(line):
                continue
            for target in pattern.findall(line):
                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()),
            "dead": sum(r["dead"] for r in rows.values()),
            "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()),
            "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()),
            "largest": max((r["largest"] for r in rows.values()), default=0),
            "largest_file": max(rows.values(), key=lambda r: r["largest"])["largest_file"]
            if rows
            else "",
        },
    }


# `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
# mirrored by `budgeted` in tests/architecture.rs.
BUDGET_KEYS = ("pub", "dead", "test", "deadonly", "glob")


def check_budget(data, budget):
    """Numbers over budget, as (module, key, budget, actual) tuples."""
    over = []
    mods = budget.get("modules", {})
    for mod, row in sorted(data["modules"].items()):
        allowed = mods.get(mod)
        if allowed is None:
            over.append((mod, "module", "absent from budget", "present"))
            continue
        for key in BUDGET_KEYS:
            if key in allowed and row[key] > allowed[key]:
                over.append((mod, key, allowed[key], row[key]))
    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"])
    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))
    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))
    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']}")
    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)}")


def record(data, path):
    stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M")
    totals = data["totals"]
    new = not os.path.exists(path)
    with open(path, "a") as handle:
        if new:
            handle.write("# Architecture census\n")
        handle.write(f"\n## {stamp}\n\n")
        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['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")
        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['largest']} {row['largest_file']} |\n")
        handle.write("\n```\n")
        for src_mod, targets in sorted(data["edges"].items()):
            handle.write(f"{src_mod} -> {' '.join(targets)}\n")
        handle.write("```\n")
    print(f"recorded in {path}")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--json", action="store_true", help="print the census as JSON")
    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()

    if args.write_budget:
        # 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:
                existing = json.load(open(args.write_budget))
            except (ValueError, OSError):
                existing = {}
        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)
            handle.write("\n")
        print(f"wrote {args.write_budget}")
        return 0

    if args.json:
        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)
        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}")

    if args.record:
        record(data, args.record)
    return 0


if __name__ == "__main__":
    sys.exit(main())