summaryrefslogtreecommitdiffstats
path: root/tools/test-surface.py
blob: 40385ad13fe7a68acf76c03592a7891ca2d55972 (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
#!/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.

Rust has no test-conditional visibility: no attribute makes an item `pub` under
one feature and `pub(crate)` under another, and `pub use` cannot re-export a
`pub(crate)` item. An item that production needs inside its own module *and* a
fixture-bound integration test needs from outside therefore cannot be narrowed
without breaking one or the other. Those rows are `residue`, and the only way to
shrink them is to change the tests, not the visibility.
"""
import argparse, collections, json, os, re, sys

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")

# 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")))


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")


def strip_test_modules(path):
    """Lines of `path` with `#[cfg(test)] mod ... {}` blocks removed."""
    lines = open(path).read().split("\n")
    out, i = [], 0
    while i < len(lines):
        if lines[i].strip() == "#[cfg(test)]":
            j = i + 1
            while j < len(lines) and lines[j].strip().startswith("//"):
                j += 1
            if j < len(lines) and re.match(r"\s*(?:pub(?:\(crate\))?\s+)?mod\s+\w+", lines[j]):
                depth, started, k = 0, False, j
                while k < len(lines):
                    depth += lines[k].count("{") - lines[k].count("}")
                    if "{" in lines[k]:
                        started = True
                    if started and depth <= 0:
                        break
                    k += 1
                i = k + 1
                continue
        out.append(lines[i])
        i += 1
    return out


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 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 analyse():
    src = {p: open(p).read() for p in rust_files(SRC)}
    tests = {p: open(p).read() for p in rust_files(TESTS)}
    names = collections.defaultdict(list)
    for path, text in src.items():
        for line in text.splitlines():
            if COMMENT.match(line):
                continue
            m = PUB_RE.match(line)
            if m:
                names[m.group(1)].append(path)

    rows = []
    for name, paths in sorted(names.items()):
        declaring = {module_of(p) for p in paths}
        if any(module_of(p) not in declaring and re.search(r"\b%s\b" % re.escape(name), t)
               for p, t in src.items()):
            continue
        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)

        # 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 = []
        mod = module_of(paths[0])
        base = os.path.join(SRC, mod)
        files = rust_files(base) if os.path.isdir(base) else [os.path.join(SRC, mod + ".rs")]
        for p in files:
            for i, line in enumerate(strip_test_modules(p), 1):
                if not re.search(r"\b%s\b" % re.escape(name), line):
                    continue
                s = line.strip()
                if s.startswith("//") or s.startswith("///"):
                    continue
                if re.match(r"^\s*pub\s+(?:fn|struct|enum|trait|const|static|type)\s+%s\b"
                            % re.escape(name), line):
                    continue
                if re.match(r"^\s*(?:pub(?:\(crate\))?\s+)?use\s+", line):
                    continue
                internal.append("%s:%d" % (os.path.relpath(p, ROOT), i))

        if 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,
            where=("%s:%d" % (occ[0][0], occ[0][1])) if occ else "?",
            gated=gated, string_only=string_only, tests=users,
            internal=internal, sites=[list(s) for s in sites],
            disp=disp,
            reason=(REASONS.get("%s.%s" % (mod, name))
                    or ("production uses it at %s; the test that names it needs a fixture."
                        % internal[0] if internal
                        else "nothing in src calls it; a test does.")),
            hand_written=("%s.%s" % (mod, name)) in REASONS,
        ))
    return rows


def render(rows):
    order = ["gate", "move-test", "narrow", "residue", "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 — `pub` because Rust has no test-conditional visibility",
             "already-gated": "Already gated"}
    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("| `residue` | stays `pub`, documented, counted | production needs it *inside* its module **and** a fixture-bound integration test needs it from outside |\n")
    A("### Why `residue` exists at all\n")
    A("Rust has no test-conditional visibility. No attribute makes an item `pub`\n"
      "under one feature and `pub(crate)` under another, and `pub use` cannot\n"
      "re-export a `pub(crate)` item. An item that production needs inside its own\n"
      "module *and* an integration test needs from outside cannot be narrowed\n"
      "without breaking one or the other.\n")
    A("The way to shrink that column is not a visibility change. It is to make the\n"
      "integration tests stop reaching in — by moving them into the module, or by\n"
      "exercising the behaviour through the module's real entry point. That is a\n"
      "test-design change with a real cost per row, recorded here rather than\n"
      "attempted blind.\n")
    A("The `residue` count is ratcheted by `tests/architecture.rs`, so it can only\nshrink.\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 | why |\n|---|---|---|---|---|")
        for r in sel:
            A("| `%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 ""),
                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"


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--write", action="store_true")
    a = ap.parse_args()
    rows = analyse()
    if a.json:
        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"])
        print(json.dumps({"rows": rows, "counts": counts}, indent=1))
    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)