summaryrefslogtreecommitdiffstats
path: root/tools/test-surface.py
blob: ae5a78f30f69a27ecbc7a689c82db87ce60ef9a8 (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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
#!/usr/bin/env python3
"""The test surface: every `pub` item that exists because a test names it.

Reads the crate the way `tools/arch-census.py` does — a `pub` item is *dead* when
no file outside its own top-level module names it, and *test-only* when a file
under `tests/` does — and then asks two further questions of every test-only
item, because the census's answer is not the whole answer:

  1. Does a test *call* it, or merely mention it inside a string literal?
     The census matches over raw source, so a string counts. Those items are
     census false positives: nothing in the test tier depends on them.
  2. Does production code inside the declaring module call it? If it does, the
     item is not "test-only" in substance; it is module-internal, and a test
     happens to be the only outside reader.

Those two questions yield the four dispositions written to
`tools/test-surface.md`. Run with `--json` for the machine-readable form, whose
`residue` count `tests/architecture.rs` ratchets.

Two shapes make visibility feature-conditional, and the table records which one
an item uses. For a free function, method, const or static, one body sits behind
two declarations:

    #[cfg(feature = "test-support")]      pub fn probe(..) -> .. { probe_impl(..) }
    #[cfg(not(feature = "test-support"))] pub(crate) fn probe(..) -> .. { probe_impl(..) }
    fn probe_impl(..) -> .. { .. }

For a type, the real definition lives in a private module and a gated `pub use`
is the only path to it:

    mod kata_backend { pub struct KataBackend { .. } }
    #[cfg(feature = "test-support")]      pub use kata_backend::KataBackend;
    #[cfg(not(feature = "test-support"))] pub(crate) use kata_backend::KataBackend;

A `pub` item in a private module has no nameable path from outside, yet is
visible enough to appear in a public trait signature — which is why the return
type of `Sandbox::run` narrows this way when a plain `pub(crate) struct` would
be a private-in-public error.

`residue` is therefore a failure, not a verdict: it means an item is still
ungated and nothing has argued it should be. The only honest dispositions are
the ones that close the release build, plus `interface` for the rare item a
public signature forces open. Whether the table is telling the truth is checked
by compiling against the library, not by reading it — see
`tools/release-surface-probe.py`.
"""
import argparse, collections, json, os, re, sys
from functools import lru_cache

ROOT = os.path.dirname(os.path.abspath(__file__)) + "/.."
SRC = os.path.join(ROOT, "src")
TESTS = os.path.join(ROOT, "tests")
DOC = os.path.join(ROOT, "tools", "test-surface.md")

PUB_RE = re.compile(r"^\s*pub\s+(?:fn|struct|enum|trait|const|static|type)\s+([A-Za-z0-9_]+)")
COMMENT = re.compile(r"^\s*(?://|//!|///)")
GATE = "test-support"
HARNESS = ("Env::new", "env_with_fixture", "Fixture", "tempdir", "Command::new",
           "fs::", "shim_dir", "corpus_root",
           # `Web::` starts a real HTTP server; a test that talks to it is not a
           # unit test however little code it contains. Missing this first made
           # two http route handlers look movable when their tests were
           # driving a live listener.
           "Web::", "web.get", "web.post", "raw_request")

# Reasons that take argument to state; everything else is derived from the
# evidence the analysis already has.
REASONS = json.load(open(os.path.join(ROOT, "tools", "test-surface-reasons.json")))

# Rows whose only in-module evidence is a call in method position on some
# receiver. A name match cannot tell `self.store_dir()` from
# `listener.local_addr()`; a human has to. Each entry below was read at the
# cited line and confirmed to be a call of the item itself. Anything dotted-only
# and absent from this list fails `tests/architecture.rs`.
CONFIRMED = set(json.load(open(os.path.join(ROOT, "tools", "test-surface-confirmed.json"))))

# Rows whose production-use verdict rests on a bare mention of a name the
# detector cannot resolve to one item. Each entry is a human verdict on the
# cited line; a row that is ambiguous and absent here fails the architecture
# test, because "the tool could not tell" is not a disposition.
AMBIGUOUS = json.load(open(os.path.join(ROOT, "tools", "test-surface-ambiguous.json")))

# Items that stay `pub` in a release build because a public signature requires
# them, not because a test asked. Each entry states the signature. This is the
# one disposition that admits reachability, so it is declared by hand and the
# probe verifies it: `db::Writer` is public because `Db.writer` is a `pub` field
# and Rust will not type a public field with a private type.
INTERFACE = json.load(open(os.path.join(ROOT, "tools", "test-surface-interface.json")))


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


def module_of(path):
    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")


@lru_cache(maxsize=None)
def line_context(path):
    """Per line: (inside_cfg_test_mod, inside_test_support_gate).

    Both are tracked by brace depth from the attribute that opens them, so a
    mention inside a `#[cfg(test)] mod tests {}` or a
    `#[cfg(feature = "test-support")] fn ... {}` is not evidence that
    production code uses the name. Getting this wrong is what once let a
    test-only function be classified as production-used because its only
    caller was another test-only function.
    """
    lines = open(path).read().split("\n")
    ctx = []
    depth = 0
    test_mod_depth = None
    gate_stack = []          # depths at which a test-support-gated block opened
    pending = None           # "test" | "gate" | None, from a pending attribute
    i = 0
    while i < len(lines):
        line = lines[i]
        stripped = line.strip()
        if stripped.startswith("#[") and "test-support" in stripped:
            pending = "gate"
        elif stripped == "#[cfg(test)]":
            pending = "test"

        opens = line.count("{")
        closes = line.count("}")
        is_decl = bool(re.match(r"^\s*(?:pub(?:\(crate\))?\s+)?(?:fn|mod|struct|enum|trait|impl|const|static|type|use)\b", line))

        # An attribute only attaches to the declaration on the next code line.
        if pending and is_decl:
            if pending == "test" and re.match(r"^\s*(?:pub(?:\(crate\))?\s+)?mod\b", line):
                test_mod_depth = depth
            elif pending == "gate":
                gate_stack.append(depth)
        if pending and (is_decl or not stripped.startswith("#")):
            if not is_decl:
                pending = None

        ctx.append((test_mod_depth is not None, bool(gate_stack)))

        depth += opens - closes
        if test_mod_depth is not None and depth <= test_mod_depth:
            test_mod_depth = None
        while gate_stack and depth <= gate_stack[-1]:
            gate_stack.pop()
        if not stripped.startswith("#"):
            pending = None
        i += 1
    return ctx


def strip_noise(line):
    """Drop comments and string literals, so a mention inside either is not a
    call. `\binvocations.jsonl\b` matching a filename is what made a shim
    reader look production-used when nothing read it."""
    line = re.sub(r"//[^\"]*$", "", line)
    line = re.sub(r'"(?:[^"\\]|\\.)*"', '""', line)
    line = re.sub(r"r#\".*?\"#", '""', line)
    return line


@lru_cache(maxsize=None)
def use_block_lines(path):
    """Line numbers that are part of a `use ...;` statement, including the
    continuation lines of a brace-delimited `use foo::{\\n ... };` block. A
    re-export is not a call: `pub use pkgbases::{ ..., cas_accepted_release, ... };`
    once made a function with no production caller look production-used."""
    lines = open(path).read().split("\n")
    out = set()
    depth = 0
    in_use = False
    for i, raw in enumerate(lines):
        line = strip_noise(raw)
        if not in_use and re.match(r"^\s*(?:pub(?:\(crate\))?\s+)?use\b", line):
            in_use = True
        if in_use:
            out.add(i)
            depth += line.count("{") - line.count("}")
            if ";" in line and depth <= 0:
                in_use = False
                depth = 0
    return out


@lru_cache(maxsize=None)
def gated_declarations(path):
    """{name: (line, gated)} honouring cfg-gated enclosing blocks."""
    lines = open(path).read().split("\n")
    depth, gated_open, pending = 0, [], False
    out = {}
    for i, line in enumerate(lines):
        s = line.strip()
        if s.startswith("#[") and GATE in s:
            pending = True
        if COMMENT.match(line):
            continue
        m = PUB_RE.match(line)
        if m:
            out.setdefault(m.group(1), []).append((i + 1, pending or bool(gated_open)))
        opens, closes = line.count("{"), line.count("}")
        if re.match(r"^\s*(?:pub(?:\(crate\))?\s+)?(?:mod|impl|trait|enum)\b", line) and pending:
            gated_open.append(None if not opens else depth)
        depth += opens - closes
        while gated_open and gated_open[-1] is not None and depth <= gated_open[-1]:
            gated_open.pop()
        if not s.startswith("#"):
            pending = False
    return out


def aliased_behind_private_module(path, name):
    """True when the only public path to `name` is a gated `pub use` alias.

    The inner-module narrowing declares the item `pub` inside a module nobody
    outside can name, then re-exports it under a feature gate:

        mod kata_backend { pub struct KataBackend { ... } }
        #[cfg(feature = "test-support")]      pub use kata_backend::KataBackend;
        #[cfg(not(feature = "test-support"))] pub(crate) use kata_backend::KataBackend;

    The census sees the inner `pub` and calls it a public declaration. It is
    not one: a `pub` item in a private module has no nameable path, and the
    alias that gives it one is gated. Both halves must hold for this to be true.
    """
    lines = open(path).read().split("\n")

    # 1. is there a `pub use ...::NAME;` whose attribute block carries the gate?
    aliased = False
    for i, line in enumerate(lines):
        if not re.search(r"^\s*pub\s+use\s+[^;]*::%s\b" % re.escape(name), line):
            continue
        k = i - 1
        while k >= i - 8 and (lines[k].strip().startswith("#[")
                              or lines[k].strip().startswith("//")
                              or not lines[k].strip()):
            if GATE in lines[k]:
                aliased = True
            k -= 1
    if not aliased:
        return False

    # 2. does every `pub` declaration of the name sit inside a private module?
    decls = [i for i, l in enumerate(lines)
             if re.match(r"^\s*pub\s+(?:fn|struct|enum|trait|const|static|type)\s+%s\b"
                         % re.escape(name), l)]
    if not decls:
        return False
    for d in decls:
        depth, enclosed = 0, []
        for k in range(d - 1, -1, -1):
            # Walking backwards, an unmatched `{` means that line opens a block
            # we are inside of.
            depth += lines[k].count("{") - lines[k].count("}")
            if depth > 0:
                m = re.match(r"^\s*(pub(?:\(crate\))?\s+)?mod\s+(\w+)", lines[k])
                if m:
                    enclosed.append(m.group(1))
                depth -= 1
        if not enclosed or any(enc for enc in enclosed):
            return False
    return True


def integration_tests(path):
    lines = open(path).read().split("\n")
    starts = [i for i, l in enumerate(lines) if l.lstrip().startswith("#[test]")]
    starts.append(len(lines))
    out = []
    for a, b in zip(starts, starts[1:]):
        body = "\n".join(lines[a:b])
        m = re.search(r"fn (\w+)", body)
        if m:
            out.append((m.group(1), body))
    return out


def enclosing_mods_are_private(lines, idx):
    """True when every module enclosing `lines[idx]` is a private `mod`.

    A `pub` item inside a private module has no nameable path from outside the
    parent, so it is not a public declaration. This is the second half of the
    inner-module narrowing; without it the detector reads `pub fn new` inside
    `mod log_tail` and reports an `http::new` that nothing can reach.
    """
    depth, enclosed = 0, []
    for k in range(idx - 1, -1, -1):
        depth += lines[k].count("{") - lines[k].count("}")
        if depth > 0:
            m = re.match(r"^\s*(pub(?:\(crate\))?\s+)?mod\s+\w+", lines[k])
            if m:
                enclosed.append(m.group(1))
            depth -= 1
    return bool(enclosed) and not any(enclosed)


@lru_cache(maxsize=None)
def use_prefixes(path):
    """{local prefix: top-level module} for the `use` statements in one file.

    Production reaches most items through a name the declaring module did not
    choose: `use crate::review::{approve as ap, ..}` and then `ap::approve(..)`,
    or `use crate::watch::sources;` and then `sources::recipe_hash(..)`. A
    detector that only recognises `watch::recipe_hash` calls those items
    uncalled, which is how `review::approve` and `watch::recipe_hash` landed in
    the residue column looking test-only when three modules call them.
    """
    text = open(path).read()
    out = {}
    for m in re.finditer(r"\buse\s+(?:pub\s+)?crate::([\w:]+)(?:::\{([^}]*)\}|::(\w+))(?:\s+as\s+(\w+))?\s*;",
                         text, re.S):
        base, group, last, alias = m.group(1), m.group(2), m.group(3), m.group(4)
        top = base.split("::")[0]
        if group is not None:
            out.setdefault("self" if last is None and alias is None else "", top)
            out.pop("", None)
            if last:
                out.setdefault(alias or last, top)
            for item in group.split(","):
                item = item.strip()
                if not item:
                    continue
                if item == "self":
                    out.setdefault(base.split("::")[-1], top)
                elif " as " in item:
                    a, b = item.split(" as ", 1)
                    out.setdefault(b.strip(), top)
                else:
                    out.setdefault(item, top)
        elif last:
            out.setdefault(alias or last, top)
    return out


CRATE_MODULES = set()
REEXPORTS = set()
ALIAS_TOP = {}


def reexport_edges(src):
    """{(top module, name)} for every `pub use` that carries `name` out of a module.

    `db::candidates::mark_viewed` is re-exported by `review`, and production
    calls it `candidates::mark_viewed`. A detector that only credits the
    declaring module calls that item uncalled.

    The names are collected from the whole `use` statement, not just its first
    line: `pub use crate::db::candidates::{\n mark_viewed, ... };` keeps its
    names on a continuation line, and reading only the first line hid every one
    of them — which is how `mark_viewed` and `open_reviews_for` stayed invisible.
    """
    edges = set()
    for path, text in src.items():
        top = module_of(path).split(os.sep)[0]
        lines = text.split("\n")
        block = use_block_lines(path)
        i = 0
        while i < len(lines):
            if not re.match(r"^\s*pub\s+use\b", strip_noise(lines[i])):
                i += 1
                continue
            j = i
            stmt = []
            while j in block and j < len(lines):
                stmt.append(strip_noise(lines[j]))
                if ";" in stmt[-1]:
                    break
                j += 1
            body = " ".join(stmt)
            for n in re.findall(r"\b([A-Za-z_][A-Za-z0-9_]*)\b", body):
                edges.add((top, n))
            i = j + 1
    return edges


def analyse():
    global CRATE_MODULES
    src = {p: open(p).read() for p in rust_files(SRC)}
    CRATE_MODULES = {module_of(p) for p in src} | {m.split(os.sep)[0] for m in {module_of(p) for p in src}}
    tests = {p: open(p).read() for p in rust_files(TESTS)}

    # Rows are keyed by (module, name), not by bare name. `pipeline::dispatch::
    # Pool::shutdown` and `db::Writer::shutdown` are two items; keyed by name
    # alone they merged into one row, and because the `db` one is gated the
    # ungated one was reported `already-gated`.
    names = collections.defaultdict(list)
    for path, text in src.items():
        lines = text.splitlines()
        for line_no, line in enumerate(lines):
            if COMMENT.match(line):
                continue
            m = PUB_RE.match(line)
            if m and not enclosing_mods_are_private(lines, line_no):
                names[(module_of(path), m.group(1))].append(path)

    # A production mention, counted per line with comments and string literals
    # removed, and with every line belonging to a `use` statement dropped. Two
    # rules the in-module loop already honoured and this one did not:
    #
    #   - Raw text made `review::approve::withdraw` look production-used: the
    #     only src/ hits outside `review` were the route pattern
    #     "packages/{name}/withdraw" and an audit action string.
    #   - A re-export is not a call. `db::candidates::open_reviews_for` had
    #     exactly one src/ mention outside `db` — the `pub use` line in
    #     `review/candidates.rs` that re-exports it — and that line was counted
    #     as production use, so the item was dropped before it could become a
    #     row. The same line hid `reopen_rejected`, which nothing calls at all.
    stripped = {p: [(i, l) for i, l in enumerate(t.splitlines())
                    if not COMMENT.match(l) and i not in use_block_lines(p)]
                for p, t in src.items()}
    prefixes = {p: use_prefixes(p) for p in src}
    # Which identifiers each file actually writes. Without this the scan below
    # ran a fresh regex for every name against every line of every other file —
    # ~500 names x ~15k lines — and the check took two and a half minutes. A set
    # membership test rejects almost all of them for the cost of a hash.
    file_idents = {p: set(re.findall(r"\b[A-Za-z_][A-Za-z0-9_]*\b", "\n".join(
                        strip_noise(l) for _, l in pairs)))
                   for p, pairs in stripped.items()}
    global REEXPORTS, ALIAS_TOP
    REEXPORTS = reexport_edges(src)
    # A re-exported name — module or item — is a path component that routes back
    # to the module that published it: `notice_kind` routes to `db`.
    ALIAS_TOP = {(m, n): m for (m, n) in REEXPORTS}

    # A bare mention in another module cannot be resolved to one item when the
    # same name is declared in several modules — `new`, `parse` and `open` are
    # declared all over the crate, and a line saying `Foo::new()` in `http` says
    # nothing about `db::open`. For a colliding name a mention counts only if
    # the line actually routes through the declaring module: a qualified path
    # (`db::open`, `crate::db::open`) or a `use` that imports from it. A
    # colliding name with unqualified mentions is kept and flagged, because the
    # honest answer is "a line-based tool cannot tell" and a human should.
    collisions = {name for (mod, name) in names if
                  len({m for (m, n) in names if n == name}) > 1}

    def mentioned(line, mod, name, prefixes, file_mod):
        """Does this line show production reaching `mod::name`?

        True = yes. False = a mention that cannot be resolved either way, which
        makes the row ambiguous for a human. None = not a mention of this item
        at all, so it neither supports nor clouds the verdict.

        Three things had to be resolved before this stopped lying in both
        directions. A qualified path is not just its last token:
        `crate::db::model::BUILD_STEPS` and `pipeline::publish::reconcile` reach
        the item through a submodule. An item may be reached through a module
        that did not declare it — `db::candidates::mark_viewed` is re-exported by
        `review`, and production calls it `candidates::mark_viewed`. And the
        unresolvable cases are mostly std and local names wearing a crate item's
        name: `Vec::new()`, `v.parse::<u64>()`, `stop.load(..)`.
        """
        top = mod.split(os.sep)[0]
        # A method name declared in exactly one module is safe to credit: there
        # is no other item it could mean, so `cfg.validate()` is evidence for
        # `config::validate` even though the receiver is a value, not a path.
        sole_owner = len({m for (m, n) in names if n == name}) == 1
        for m in re.finditer(r"\b%s\b" % re.escape(name), line):
            before = line[:m.start()].rstrip()
            if before.endswith("::"):
                path = re.findall(r"((?:\w+\s*::)+)$", before)
                parts = [p.strip() for p in path[0].split("::")] if path else []
                parts = [p for p in parts if p]
                if not parts:
                    return True              # a bare `Self::name`
                for part in parts:
                    if part == top or part == file_mod:
                        return True          # `db::open`, `crate::db::model::X`
                    owner = prefixes.get(part, part)
                    if owner == top:
                        return True          # `ap::approve`, `sources::record`
                    if (owner, name) in REEXPORTS:
                        return True          # reached through a re-exporting module
                    # The path component is itself something a module re-exported:
                    # `notice_kind::PIN_DRIFT` where `notice_kind` is `db`'s.
                    if any(t == top for (m, n), t in ALIAS_TOP.items()
                           if n == part and (m, n) in REEXPORTS):
                        return True
                    if (owner, part) in REEXPORTS and owner == top:
                        return True
                    if any(t == top for (m, n), t in ALIAS_TOP.items() if n == part):
                        return True
                if any(p in CRATE_MODULES for p in parts):
                    return False             # a crate module's, but not this one's
                continue                     # `Vec::new`, `Raw::parse`: not ours
            if before.endswith("."):
                if sole_owner:
                    return True              # `cfg.validate()`: only one item fits
                continue                     # a method on some value: unknown
            return True                      # bare call: only this item fits
        return None

    rows = []
    for (mod, name), paths in sorted(names.items()):
        hits = [v
                for p, line_pairs in stripped.items()
                if module_of(p) != mod and name in file_idents[p]
                for _, line in line_pairs
                for v in [mentioned(strip_noise(line), mod, name, prefixes[p],
                                    module_of(p))]
                if v is not None]
        if any(hits):
            continue                          # production uses it outside the module
        ambiguous_collision = any(v is False for v in hits)
        users = sorted(os.path.relpath(f, TESTS) for f, t in tests.items()
                       if re.search(r"\b%s\b" % re.escape(name), t))
        if not users:
            continue

        occ = [(os.path.relpath(p, ROOT), ln, g)
               for p in paths for (ln, g) in gated_declarations(p).get(name, [])]
        gated = any(g for _, _, g in occ) or any(
            aliased_behind_private_module(p, name) for p in paths)

        # A mention inside a string literal is not a call.
        string_only = all(
            not re.search(r"\b%s\b" % re.escape(name),
                          re.sub(r'"(?:[^"\\]|\\.)*"', '""', t))
            for t in tests.values())

        sites = []
        if not string_only:
            for f in users:
                for (tname, body) in integration_tests(os.path.join(TESTS, f)):
                    if re.search(r"\b%s\b" % re.escape(name), body):
                        sites.append((f, tname, any(k in body for k in HARNESS)))

        internal = []
        base = os.path.join(SRC, mod)
        files = rust_files(base) if os.path.isdir(base) else [os.path.join(SRC, mod + ".rs")]
        pat = re.compile(r"\b%s\b" % re.escape(name))
        self_impl = re.compile(
            r"^\s*(?:pub(?:\(crate\))?\s+)?impl\s+(?:<[^>]*>\s*)?%s\b" % re.escape(name))
        self_impl_for = re.compile(
            r"^\s*(?:pub(?:\(crate\))?\s+)?impl\s+[^{]*\bfor\s+(?:<[^>]*>\s*)?%s\b" % re.escape(name))
        for p in files:
            ctx = line_context(p)
            uses = use_block_lines(p)
            for i, raw in enumerate(open(p).read().split("\n")):
                if i in uses:
                    continue                       # a re-export is not a call
                if i < len(ctx) and ctx[i][0]:
                    continue                       # inside #[cfg(test)] mod tests
                if i < len(ctx) and ctx[i][1]:
                    continue                       # inside a test-support-gated item
                line = strip_noise(raw)
                if not line.strip():
                    continue
                if self_impl.match(raw) or self_impl_for.match(raw):
                    continue                       # the item's own impl header
                if re.match(r"^\s*pub\s+(?:fn|struct|enum|trait|const|static|type)\s+%s\b"
                            % re.escape(name), raw):
                    continue                       # the item's own declaration
                for m in pat.finditer(line):
                    # A mention in method-call position on some receiver
                    # (`.name(`) is not evidence that *this* item is used:
                    # `KataBackend::local_addr` was credited to
                    # `listener.local_addr()`, a std method on a different
                    # type. Bare calls and qualified paths are evidence.
                    before = line[:m.start()].rstrip()
                    dotted = before.endswith(".")
                    internal.append(("%s:%d" % (os.path.relpath(p, ROOT), i + 1), dotted))

        bare = [h for h, dotted in internal if not dotted]
        # Every piece of in-module evidence for this item is a call in method
        # position on some receiver. That is usually real (`self.store_dir()`,
        # `req.cookie("sid")`) but it is the one shape a name match cannot
        # resolve, so such rows are named for a human rather than trusted.
        dotted_only = bool(internal) and not bare
        internal = [h for h, _ in internal]

        # Feature-conditional visibility: the item is `pub` under `test-support`
        # and `pub(crate)` otherwise, declared twice with the same body. It is
        # not the same as being gated — production *does* use this item, just
        # not from outside its module — and the table should say which is which.
        narrowed = gated and any(
            re.search(r"pub\(crate\)\s+(?:fn|const|static|type)\s+%s\b" % re.escape(name), t)
            or re.search(r"pub\(crate\)\s+use\s+[^;]*::%s\b" % re.escape(name), t)
            for t in (open(pp).read() for pp in paths)
        )

        if ("%s.%s" % (mod, name)) in INTERFACE:
            disp = "interface"
        elif gated and narrowed:
            disp = "narrowed"
        elif gated:
            disp = "already-gated"
        elif string_only:
            disp = "narrow"
        elif sites and all(not h for _, _, h in sites):
            disp = "move-test"
        elif not internal:
            disp = "gate"
        else:
            disp = "residue"

        rows.append(dict(
            module=mod, name=name, ambiguous=ambiguous_collision,
            where=("%s:%d" % (occ[0][0], occ[0][1])) if occ else "?",
            gated=gated, narrowed=narrowed, string_only=string_only, tests=users,
            internal=internal, dotted_only=dotted_only,
            confirmed=("%s.%s" % (mod, name)) in CONFIRMED,
            adjudicated=("%s.%s" % (mod, name)) in AMBIGUOUS,
            justified=("%s.%s" % (mod, name)) in INTERFACE,
            sites=[list(s) for s in sites],
            disp=disp,
            reason=(REASONS.get("%s.%s" % (mod, name))
                    or INTERFACE.get("%s.%s" % (mod, name))
                    or ("production uses it at %s (%d sites in-module); the test that "
                        "names it needs a fixture."
                        % ("`, `".join(internal[:3]), len(internal)) if internal
                        else "nothing in src calls it; a test does.")),
            hand_written=("%s.%s" % (mod, name)) in REASONS
                         or ("%s.%s" % (mod, name)) in INTERFACE,
        ))
    return rows


def render(rows):
    order = ["gate", "move-test", "narrow", "residue", "interface", "narrowed", "already-gated"]
    title = {"gate": "Gate behind `test-support`",
             "move-test": "Move the test into the module, then narrow",
             "narrow": "Narrow — no test actually calls it",
             "residue": "Residue — ungated and unargued; a failure, not a verdict",
             "already-gated": "Already gated",
             "interface": "Public because a public signature requires it; no test asked for it",
             "narrowed": "Feature-conditional visibility — production uses it, only from inside its module"}
    out = [open(DOC).read().split("## gate-marker")[0]] if False else []
    L = []
    A = L.append
    A("# The test surface: every `pub` item that exists because a test names it\n")
    A("Regenerate with `python3 tools/test-surface.py --write`. The reasons in the\n"
      "`why` column live in `tools/test-surface-reasons.json` and are reviewed by\n"
      "hand; everything else is derived from the source.\n")
    A("## What counts\n")
    A("The census (`tools/arch-census.py`) calls a `pub` item **dead** when no file\n"
      "*outside its own top-level module* names it, and **test-only** when a file\n"
      "under `tests/` does. That definition is coarse in two ways that matter here:\n")
    A("- *Module is the top-level directory.* An item in `src/db/candidates.rs` used\n"
      "  only from `src/db/builds/mod.rs` counts as dead, because both are in `db`.\n"
      "  Many rows below are therefore not \"used only by tests\" — they are used only\n"
      "  inside their own module, and a test happens to be the only outside reader.\n")
    A("- *Mentions are matched over raw source, including string literals.* Some\n"
      "  items are named by a test only inside a string. Nothing in the test tier\n"
      "  depends on them; they are census false positives.\n")
    A("## The four dispositions\n")
    A("| disposition | meaning | applies when |\n|---|---|---|")
    A("| `gate` | add `#[cfg(feature = \"test-support\")]` | production never calls it; a test does |")
    A("| `move-test` | move the test into the module, then make the item private | the test that names it builds no fixture, so it is a unit test in the wrong file |")
    A("| `narrow` | `pub(crate)` or private | no test calls it at all (string-only mention) |")
    A("| `interface` | stays `pub`, and the probe proves it is reachable | a public signature requires it; no test asked for it |")
    A("| `residue` | **a failure** | ungated, and nothing has argued why it should be |\n")
    A("### How visibility becomes feature-conditional\n")
    A("For a free function, method, const or static, one body sits behind two\n"
      "declarations, exactly one of which compiles:\n")
    A("```rust\n"
      "#[cfg(feature = \"test-support\")]      pub fn probe(..) -> .. { probe_impl(..) }\n"
      "#[cfg(not(feature = \"test-support\"))] pub(crate) fn probe(..) -> .. { probe_impl(..) }\n"
      "fn probe_impl(..) -> .. { .. }\n"
      "```\n")
    A("For a type, the real definition lives in a private module and a gated\n"
      "`pub use` is the only path to it:\n")
    A("```rust\n"
      "mod kata_backend { pub struct KataBackend { .. } }\n"
      "#[cfg(feature = \"test-support\")]      pub use kata_backend::KataBackend;\n"
      "#[cfg(not(feature = \"test-support\"))] pub(crate) use kata_backend::KataBackend;\n"
      "```\n")
    A("A `pub` item in a private module has no nameable path from outside, yet is\n"
      "visible enough to appear in a public trait signature — which is how the\n"
      "return type of `Sandbox::run` narrows when a plain `pub(crate) struct`\n"
      "would be a private-in-public error.\n")
    A("`residue` is not a verdict, it is an unargued row. The column is shrunk by\n"
      "applying one of the two shapes above, by moving the test into the module,\n"
      "or by deleting the item.\n")
    A("Whether this table tells the truth is not checked by reading it.\n"
      "`tools/release-surface-probe.py` compiles a throwaway crate against the\n"
      "library twice, with and without `test-support`, and fails if any path that\n"
      "reaches the test tier also reaches a release build.\n")
    tot = collections.Counter(r["disp"] for r in rows)
    for d in order:
        sel = sorted([r for r in rows if r["disp"] == d], key=lambda r: (r["module"], r["name"]))
        if not sel:
            continue
        A("\n## %s — %d items\n" % (title[d], len(sel)))
        A("| module | item | declared at | test files | in-module call sites | why |\n"
          "|---|---|---|---|---|---|")
        for r in sel:
            cites = ", ".join("`%s`" % c for c in r["internal"][:3]) or "—"
            if len(r["internal"]) > 3:
                cites += " +%d" % (len(r["internal"]) - 3)
            if r["dotted_only"]:
                cites += " ⚑"
            A("| `%s` | `%s` | `%s` | %s | %s | %s |" % (
                r["module"], r["name"], r["where"],
                ", ".join("`%s`" % t for t in r["tests"][:4]) + (" …" if len(r["tests"]) > 4 else ""),
                cites, r["reason"].replace("|", "\\|")))
    A("\n## Totals\n\n| disposition | count |\n|---|---|")
    for d in order:
        if tot[d]:
            A("| `%s` | %d |" % (d, tot[d]))
    A("| **total** | **%d** |\n" % len(rows))
    A("Of these, %d are ungated today. Gating the `gate` rows and narrowing the\n"
      "`narrow` rows removes %d items from the release build's public surface; the\n"
      "`move-test` rows remove %d more and take their tests home with them.\n"
      % (sum(1 for r in rows if not r["gated"]), tot["gate"] + tot["narrow"], tot["move-test"]))
    return "\n".join(L) + "\n"


def tally(rows):
    """The one definition of the test-surface counts.

    Two copies of this rule drifted the first time the `interface` exclusion was
    added to only one of them, and the budget then recorded as ungated an item
    the report called justified.
    """
    counts = collections.Counter(r["disp"] for r in rows)
    counts["gate_pending"] = sum(1 for r in rows if r["disp"] == "gate" and not r["gated"])
    counts["ungated"] = sum(1 for r in rows
                            if not r["gated"] and r["disp"] != "interface")
    counts["total"] = len(rows)
    counts["release_exposed"] = counts["ungated"]
    return counts


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--write", action="store_true")
    ap.add_argument("--write-budget", metavar="FILE",
                    help="re-record the `test_surface` section of the budget file")
    a = ap.parse_args()
    rows = analyse()
    if a.json:
        print(json.dumps({"rows": rows, "counts": tally(rows)}, indent=1))
    elif a.write_budget:
        counts = tally(rows)
        path = a.write_budget
        if not os.path.isabs(path):
            path = os.path.join(ROOT, path)
        budget = json.load(open(path))
        budget["test_surface"] = {k: counts[k] for k in
                                  ("gate", "gate_pending", "move-test", "narrow",
                                   "residue", "interface", "narrowed", "already-gated",
                                   "total", "ungated")
                                  if counts[k]}
        with open(path, "w") as handle:
            json.dump(budget, handle, indent=2, sort_keys=True)
            handle.write("\n")
        print("wrote", os.path.relpath(path, ROOT), json.dumps(budget["test_surface"], sort_keys=True))
    elif a.write:
        open(DOC, "w").write(render(rows))
        print("wrote", os.path.relpath(DOC, ROOT))
    else:
        sys.stderr.write("nothing to do; use --write or --json\n")
        sys.exit(2)