summaryrefslogtreecommitdiffstats
path: root/tools/test-surface.py
diff options
context:
space:
mode:
authoraur-build <aur-build@localhost>2026-11-21 11:06:01 +0000
committeraur-build <aur-build@localhost>2026-11-21 11:06:01 +0000
commit7f5d3dc2ae540b7d4faf5e8c854e638fe70b9fd3 (patch)
treef5e71b0e80e430bc0ec0b3956968bbdc38af40b6 /tools/test-surface.py
parent7ccfb9a8f96b6f3000f36bdf76d95a4f6afd2826 (diff)
downloadaur-build-7f5d3dc2ae540b7d4faf5e8c854e638fe70b9fd3.tar.gz
aur-build-7f5d3dc2ae540b7d4faf5e8c854e638fe70b9fd3.zip
tools: a re-export is not a call, and an alias is not a stranger
The auditor's `open_reviews_for` was invisible for one reason: the cross-module mention index counted `pub use` lines as production use, so the item was discarded before it could become a row. The tool's own docstring already said "a re-export is not a call" — the rule was simply applied to the in-module loop and never to the cross-module one. Two implementations of one idea, one of them ignored. Fixing that exposed the next layer, because once re-exports stop counting, the calls that remain are mostly made through a name the declaring module did not choose: - `ap::approve(..)` from `use crate::review::{approve as ap, ..}` - `sources::recipe_hash(..)` from `use crate::watch::sources;` - `crate::db::model::BUILD_STEPS` — a path is not just its last token - `candidates::mark_viewed(..)` — an item declared in `db`, re-exported by `review`, and called through `review` So the mention resolver now resolves import prefixes, walks the whole qualified path, and follows re-export edges (collected from the entire `use` statement, not just its first line — the names live on the continuation lines, which is how `mark_viewed` hid too). It also learned the opposite lesson. `Vec::new()`, `v.parse::<u64>()` and `stop.load(..)` are not mentions of `db::new`, `pkgver::parse` or `pipeline::load`. Treating every unresolvable receiver as ambiguous buried the real rows, so a qualified mention must now name a crate module or an imported prefix to count as anything, and a method name declared in exactly one module is credited on a value receiver — `cfg.validate()` is `config::validate`, because nothing else in the crate could mean it. With that, the ambiguous column is empty instead of full of noise. `use_block_lines`, `gated_declarations`, `line_context` and `use_prefixes` each re-read their file on every call — 15,280 reads of the same dozen files, two and a half minutes per run. Memoised: 20.7s, same output.
Diffstat (limited to 'tools/test-surface.py')
-rw-r--r--tools/test-surface.py191
1 files changed, 172 insertions, 19 deletions
diff --git a/tools/test-surface.py b/tools/test-surface.py
index b8e856b..ae5a78f 100644
--- a/tools/test-surface.py
+++ b/tools/test-surface.py
@@ -45,6 +45,7 @@ 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")
@@ -106,6 +107,7 @@ def module_of(path):
return parts[0].removesuffix(".rs")
+@lru_cache(maxsize=None)
def line_context(path):
"""Per line: (inside_cfg_test_mod, inside_test_support_gate).
@@ -168,6 +170,7 @@ def strip_noise(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
@@ -190,6 +193,7 @@ def use_block_lines(path):
return out
+@lru_cache(maxsize=None)
def gated_declarations(path):
"""{name: (line, gated)} honouring cfg-gated enclosing blocks."""
lines = open(path).read().split("\n")
@@ -300,8 +304,89 @@ def enclosing_mods_are_private(lines, idx):
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::
@@ -319,14 +404,33 @@ def analyse():
names[(module_of(path), m.group(1))].append(path)
# A production mention, counted per line with comments and string literals
- # removed. Searching raw text is what made `review::approve::withdraw` look
- # production-used: the only src/ hits for the bare word outside `review`
- # were the route pattern "packages/{name}/withdraw" and an audit action
- # string, and every real caller named `withdraw_package` or
- # `withdraw_release_in`, which are different items.
- stripped = {p: "\n".join("" if COMMENT.match(l) else strip_noise(l)
- for l in t.splitlines())
+ # 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
@@ -339,22 +443,71 @@ def analyse():
collisions = {name for (mod, name) in names if
len({m for (m, n) in names if n == name}) > 1}
- def mentioned(line, mod, name):
- if not re.search(r"\b%s\b" % re.escape(name), line):
- return None # not a mention at all
- if name not in collisions:
- return True # only one item could mean this
+ 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]
- if re.search(r"\b%s\s*::[^;]*\b%s\b" % (re.escape(top), re.escape(name)), line):
- return True # qualified path through the module
- if re.match(r"^\s*(pub\s+)?use\b", line) and re.search(r"\b%s\s*::" % re.escape(top), line):
- return True # an import from the module
- return False # colliding and unqualified: unknown
+ # 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, text in stripped.items() if module_of(p) != mod
- for v in [mentioned(text, mod, name)] if v is not None]
+ 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)