v1.3.0 release: graceful-release fix, quickstart template + demo, documentation accuracy pass
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated synths were hard-freed instead of released). - New: quickstart project template + LyrebirdQuickstartDemo. - Docs: every example typechecked or provably illustrative (426->542); ~20 wrong-API examples fixed; root docs brought under the compile guard. - Fixed: NRT/Score demo Package.swift build from terminal again. See RELEASES.md for details.
This commit is contained in:
@@ -0,0 +1,354 @@
|
||||
#!/usr/bin/env python3
|
||||
"""doc_impact.py — report which docs a diff's public-API changes may have invalidated.
|
||||
|
||||
Driven by scripts/check-doc-impact.sh; not meant to be run directly.
|
||||
|
||||
Why this exists: doc rot is overwhelmingly *caused* by a public-API change, and a review
|
||||
that reads only the diff structurally cannot find it — the stale references live in files
|
||||
the diff never touches. Every incident in this series has that shape:
|
||||
|
||||
- `engine.add` gained `throws`; 11 examples elsewhere kept calling it without `try`.
|
||||
- `LyrebirdFloat` was deleted; 75 references elsewhere outlived it.
|
||||
- `maxEventsPerBlock` was added; it reached zero `.docc` files in the cycle it shipped.
|
||||
|
||||
The review agent already carries an instruction to grep for stale forms when a signature
|
||||
changes. It demonstrably under-delivers — the same review that added that instruction then
|
||||
missed `LyrebirdInt` inside a fence whose adjacent lines the diff edited. Prose guidance
|
||||
asks a reviewer to remember; this reports the candidates mechanically.
|
||||
|
||||
**This tool reports; it does not judge.** It cannot tell "intentionally unaffected" from
|
||||
"forgotten", so it never fails a build. It hands the review agent a list to adjudicate.
|
||||
"""
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
import doc_snippets as ds
|
||||
|
||||
# Matching declarations by regex against DIFF LINES does not work, and the failure is
|
||||
# silent. `init` has no identifier to capture; CLAUDE.md *mandates* multi-line signatures
|
||||
# for >=2 parameters, so an added parameter arrives as a bare continuation line
|
||||
# (`+ q: any ValidGeneratorInput,`) that no declaration pattern matches; and
|
||||
# `public private(set) var` / `public required init` / members of a `public extension`
|
||||
# never match at all. The first version of this tool dropped every one of those — it
|
||||
# reported "no doc impact" for exactly the `SynthesisEngine.init` change it cites as its
|
||||
# own motivation.
|
||||
#
|
||||
# So: take the changed LINE RANGES from the diff, parse the file for declarations with
|
||||
# their full spans and nesting-aware owners, and intersect. A change anywhere inside a
|
||||
# declaration's signature counts as touching it, however it is formatted.
|
||||
|
||||
DECL_LINE = re.compile(
|
||||
r"^\s*(?:@\w+(?:\([^)]*\))?\s+)*" # attributes
|
||||
r"(?:(?:public|open|internal|private|fileprivate)"
|
||||
r"(?:\(set\))?\s+)*" # access, incl. private(set)
|
||||
r"(?:(?:static|final|class|override|mutating|required|convenience|"
|
||||
r"nonisolated|dynamic|lazy|weak|unowned|indirect)\s+)*"
|
||||
r"(func|var|let|init|subscript|typealias|enum|struct|class|protocol|actor|case)\b"
|
||||
r"\s*([A-Za-z_]\w*)?"
|
||||
)
|
||||
TYPE_DECL = re.compile(
|
||||
r"^\s*(?:(?:public|open|internal|private|fileprivate)\s+)*"
|
||||
r"(?:final\s+)?(?:class|struct|enum|extension|protocol|actor)\s+([A-Za-z_]\w*)"
|
||||
)
|
||||
IS_PUBLIC = re.compile(r"\b(?:public|open)\b")
|
||||
|
||||
|
||||
def changed_lines(root: Path, rng: str) -> dict[str, set[int]]:
|
||||
"""New-side line numbers touched by the diff, per file."""
|
||||
proc = subprocess.run(["git", "diff", "-U0", "--no-color", rng, "--", "*.swift"],
|
||||
cwd=root, capture_output=True, text=True)
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError(f"git diff {rng} failed: {proc.stderr.strip()}")
|
||||
out: dict[str, set[int]] = {}
|
||||
cur = ""
|
||||
HUNK = re.compile(r"^@@ -\S+ \+(\d+)(?:,(\d+))? @@")
|
||||
for line in proc.stdout.split("\n"):
|
||||
if line.startswith("+++ b/"):
|
||||
cur = line[6:]
|
||||
continue
|
||||
m = HUNK.match(line)
|
||||
if m and cur:
|
||||
s = int(m.group(1)); n = int(m.group(2) or 1)
|
||||
out.setdefault(cur, set()).update(range(s, s + n))
|
||||
return out
|
||||
|
||||
|
||||
def removed_decls(root: Path, rng: str) -> set[str]:
|
||||
"""Names of public declarations the diff DELETED — they no longer exist to be parsed,
|
||||
but doc references to them are exactly the `LyrebirdFloat` case."""
|
||||
proc = subprocess.run(["git", "diff", "--no-color", rng, "--", "*.swift"],
|
||||
cwd=root, capture_output=True, text=True)
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError(f"git diff {rng} failed: {proc.stderr.strip()}")
|
||||
names: set[str] = set()
|
||||
for line in proc.stdout.split("\n"):
|
||||
if not line.startswith("-") or line.startswith("---"):
|
||||
continue
|
||||
body = line[1:]
|
||||
if not IS_PUBLIC.search(body):
|
||||
continue
|
||||
m = DECL_LINE.match(body)
|
||||
if m and m.group(2):
|
||||
names.add(m.group(2))
|
||||
return names
|
||||
|
||||
|
||||
def end_rev(rng: str) -> str:
|
||||
"""The revision a range ends at. The diff's new-side line numbers refer to the file as
|
||||
it exists THERE, not in the working tree — parsing the working tree for a historical
|
||||
range reads unrelated lines and reports the wrong declarations."""
|
||||
for sep in ("...", ".."):
|
||||
if sep in rng:
|
||||
right = rng.split(sep, 1)[1].strip()
|
||||
return right or "HEAD"
|
||||
return rng.strip() or "HEAD"
|
||||
|
||||
|
||||
def read_at(root: Path, rev: str, rel: str) -> "str | None":
|
||||
"""File content at `rev`. Falls back to the working tree when rev is the working tree."""
|
||||
proc = subprocess.run(["git", "show", f"{rev}:{rel}"], cwd=root,
|
||||
capture_output=True, text=True)
|
||||
if proc.returncode == 0:
|
||||
return proc.stdout
|
||||
f = root / rel
|
||||
return f.read_text() if f.exists() else None
|
||||
|
||||
|
||||
def file_decls(text: str) -> list[tuple[str, str, int, int]]:
|
||||
"""Public declarations in a file as (label, kind, start_line, end_line).
|
||||
|
||||
Tracks an owner stack by brace depth, so a member of the codebase's canonical
|
||||
`enum Foo { public final class Audio { … } }` shape is labelled `Foo.Audio.init`
|
||||
rather than the outer `Foo.init` that git's hunk header would suggest.
|
||||
"""
|
||||
lines = text.split("\n")
|
||||
out: list[tuple[str, str, int, int]] = []
|
||||
stack: list[tuple[str, int]] = [] # (type name, brace depth at which it opened)
|
||||
depth = 0
|
||||
public_scope: list[bool] = [] # is the enclosing type public?
|
||||
i = 0
|
||||
while i < len(lines):
|
||||
raw = lines[i]
|
||||
line = raw.split("//")[0]
|
||||
stripped = line.strip()
|
||||
|
||||
tm = TYPE_DECL.match(line)
|
||||
if tm:
|
||||
stack.append((tm.group(1), depth))
|
||||
public_scope.append(bool(IS_PUBLIC.search(line)))
|
||||
else:
|
||||
dm = DECL_LINE.match(line)
|
||||
# Only a direct member of the type is API. Without this depth test, a `let`
|
||||
# inside a function body (`let dropped: UInt64 = …`) is reported as public API
|
||||
# simply because the function lives in a public type.
|
||||
at_member_depth = (depth == stack[-1][1] + 1) if stack else (depth == 0)
|
||||
# A member is API if it says so, or if it sits in a public extension/protocol —
|
||||
# where members carry no access keyword of their own.
|
||||
if dm and at_member_depth and (IS_PUBLIC.search(line)
|
||||
or (public_scope and public_scope[-1])):
|
||||
kind, name = dm.group(1), dm.group(2)
|
||||
if kind in ("class", "struct", "enum", "protocol", "actor"):
|
||||
pass # handled by TYPE_DECL
|
||||
else:
|
||||
label = ".".join(n for n, _ in stack)
|
||||
label = f"{label}.{name or kind}" if label else (name or kind)
|
||||
# Span the whole signature: multi-line inits are the norm here.
|
||||
end = i
|
||||
if "(" in line:
|
||||
bal = line.count("(") - line.count(")")
|
||||
while bal > 0 and end + 1 < len(lines):
|
||||
end += 1
|
||||
nxt = lines[end].split("//")[0]
|
||||
bal += nxt.count("(") - nxt.count(")")
|
||||
out.append((label, kind, i + 1, end + 1))
|
||||
i = end
|
||||
line = lines[end].split("//")[0]
|
||||
|
||||
depth += line.count("{") - line.count("}")
|
||||
while stack and depth <= stack[-1][1]:
|
||||
stack.pop()
|
||||
if public_scope:
|
||||
public_scope.pop()
|
||||
i += 1
|
||||
return out
|
||||
|
||||
|
||||
def changed_api(root: Path, rng: str) -> dict[str, set[str]]:
|
||||
"""Public declarations added/removed/modified by the diff, as {label: {kinds}}."""
|
||||
found: dict[str, set[str]] = {}
|
||||
touched = changed_lines(root, rng)
|
||||
rev = end_rev(rng)
|
||||
for rel, lns in touched.items():
|
||||
text = read_at(root, rev, rel)
|
||||
if text is None:
|
||||
continue # file deleted at rev — caught by removed_decls
|
||||
for label, kind, start, end in file_decls(text):
|
||||
if any(start <= n <= end for n in lns):
|
||||
found.setdefault(label, set()).add(kind)
|
||||
for name in removed_decls(root, rng):
|
||||
found.setdefault(name, set()).add("removed")
|
||||
return found
|
||||
|
||||
|
||||
def doc_files(root: Path) -> list[Path]:
|
||||
out: list[Path] = []
|
||||
for pat in ("Sources/**/*.md", "Sources/**/*.swift", "docs/**/*.md"):
|
||||
out += sorted(root.glob(pat))
|
||||
return [f for f in out
|
||||
if not str(f.relative_to(root)).startswith(("docs/00-", "docs/01-"))]
|
||||
|
||||
|
||||
def load_corpus(root: Path, files: list[Path]) -> list[tuple[str, bool, list[str]]]:
|
||||
"""Read every doc file once. The previous version re-read all ~1450 files for each
|
||||
changed declaration, against this tool's "fast, no build required" promise."""
|
||||
out: list[tuple[str, bool, list[str]]] = []
|
||||
for f in files:
|
||||
try:
|
||||
out.append((str(f.relative_to(root)), f.suffix == ".swift", f.read_text().split("\n")))
|
||||
except Exception:
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def references(corpus: list[tuple[str, bool, list[str]]], name: str,
|
||||
kinds: set[str]) -> list[tuple[str, int, str]]:
|
||||
"""Doc references to `name`, restricted to CODE-SHAPED mentions.
|
||||
|
||||
Matching the bare word is hopeless: `add` is also English, and a word-boundary search
|
||||
for it returns 1329 hits, almost all prose ("must add the same two-line extension").
|
||||
That is the signal-to-noise failure that sank the corpus-wide identifier lint — a
|
||||
reviewer handed 1329 candidates checks none of them.
|
||||
|
||||
So a reference must look like code:
|
||||
- a call `add(` / `.add(`
|
||||
- a symbol link ``Engine/add(_:)``
|
||||
- a code span `add`
|
||||
Only doc CONTENT is searched — `///` comments and markdown — never live Swift code,
|
||||
which the compiler already checks.
|
||||
"""
|
||||
n = re.escape(name)
|
||||
if kinds & {"func", "init", "subscript"}:
|
||||
pat = re.compile(rf"(?:\b|\.){n}\s*\(") # a call or a signature link
|
||||
else:
|
||||
pat = re.compile(rf"`[^`]*\b{n}\b[^`]*`|\.{n}\b|(?:\b|\.){n}\s*[(=:]")
|
||||
hits: list[tuple[str, int, str]] = []
|
||||
for rel, is_swift, lines in corpus:
|
||||
for i, ln in enumerate(lines, 1):
|
||||
if is_swift and "///" not in ln:
|
||||
continue # live code, not documentation
|
||||
if pat.search(ln):
|
||||
hits.append((rel, i, ln.strip()[:90]))
|
||||
return hits
|
||||
|
||||
|
||||
def covered_ranges(root: Path) -> dict[str, list[tuple[int, int]]]:
|
||||
"""Line ranges of fences that `check-doc-snippets.sh` already typechecks.
|
||||
|
||||
References inside these are deliberately suppressed: the compile guard verifies them on
|
||||
every run, so re-reporting them buries the references nobody is checking. This tool's
|
||||
value is precisely the complement — uncovered fences and prose.
|
||||
"""
|
||||
man = root / "scripts/doc-snippets-manifest.txt"
|
||||
if not man.exists():
|
||||
return {}
|
||||
recorded: set[str] = set()
|
||||
for line in man.read_text().split("\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
parts = line.split("\t")
|
||||
if len(parts) != 4:
|
||||
# This tool is advisory and must never fail. A malformed manifest degrades it to
|
||||
# "suppress nothing", which is noisier but still correct.
|
||||
continue
|
||||
f, o, h, _ = parts
|
||||
recorded.add(f"{f}\t{o}\t{h}")
|
||||
out: dict[str, list[tuple[int, int]]] = {}
|
||||
for fence in ds.collect(root):
|
||||
if ds.key(fence) in recorded:
|
||||
start = fence["line"]
|
||||
end = start + fence["body"].count("\n")
|
||||
out.setdefault(fence["file"], []).append((start, end))
|
||||
return out
|
||||
|
||||
|
||||
def is_covered(covered: dict[str, list[tuple[int, int]]], path: str, line: int) -> bool:
|
||||
return any(a <= line <= b for a, b in covered.get(path, []))
|
||||
|
||||
|
||||
def main(root: Path, rng: str) -> int:
|
||||
api = changed_api(root, rng)
|
||||
if not api:
|
||||
print("OK: the diff changes no public declarations — no doc impact to review.")
|
||||
return 0
|
||||
|
||||
corpus = load_corpus(root, doc_files(root))
|
||||
covered = covered_ranges(root)
|
||||
print(f"Public declarations touched by {rng}: {len(api)}\n")
|
||||
|
||||
undocumented: list[str] = []
|
||||
total = 0
|
||||
suppressed = 0
|
||||
for label in sorted(api):
|
||||
kinds = "/".join(sorted(api[label]))
|
||||
member = label.split(".")[-1]
|
||||
hits = references(corpus, member, api[label])
|
||||
gated = [h for h in hits if is_covered(covered, h[0], h[1])]
|
||||
hits = [h for h in hits if not is_covered(covered, h[0], h[1])]
|
||||
suppressed += len(gated)
|
||||
if not hits and not gated:
|
||||
undocumented.append(f"{label} ({kinds})")
|
||||
continue
|
||||
if not hits:
|
||||
print(f" {label} [{kinds}] — all {len(gated)} reference(s) sit in fences the "
|
||||
f"compile guard already checks. Nothing to review.")
|
||||
print()
|
||||
continue
|
||||
total += len(hits)
|
||||
print(f" {label} [{kinds}] — {len(hits)} UNGATED doc reference(s)"
|
||||
+ (f" ({len(gated)} more already compile-checked)" if gated else "") + ":")
|
||||
# Grouped by file, not a flat sample. For a common member name a flat list is
|
||||
# hundreds of lines and a reviewer checks none of them; the file list is what you
|
||||
# actually act on.
|
||||
byfile: dict[str, list[tuple[int, str]]] = {}
|
||||
for path, line, text in hits:
|
||||
byfile.setdefault(path, []).append((line, text))
|
||||
for path in sorted(byfile, key=lambda k: (-len(byfile[k]), k)):
|
||||
entries = byfile[path]
|
||||
print(f" {path} ({len(entries)})")
|
||||
for line, text in entries[:2]:
|
||||
print(f" :{line} {text}")
|
||||
if len(entries) > 2:
|
||||
print(f" … {len(entries) - 2} more in this file")
|
||||
print()
|
||||
|
||||
if undocumented:
|
||||
print("Changed public API with NO doc reference anywhere:")
|
||||
for u in undocumented:
|
||||
print(f" - {u}")
|
||||
print(" (New API this shape reached zero .docc files when `maxEventsPerBlock` shipped.")
|
||||
print(" Is it genuinely internal-facing, or is documentation missing?)")
|
||||
print()
|
||||
|
||||
if total == 0 and not undocumented:
|
||||
print("OK: every doc reference to the changed API sits in a fence the compile guard "
|
||||
"already checks.")
|
||||
return 0
|
||||
print(f"REVIEW REQUIRED: {total} ungated doc reference(s) to {len(api)} changed "
|
||||
f"declaration(s); {suppressed} further reference(s) suppressed because the compile "
|
||||
f"guard already covers them.")
|
||||
print("Each is a candidate, not a defect — confirm it was updated, or is unaffected.")
|
||||
print("This tool reports; it cannot tell the difference, so it never fails.")
|
||||
print("Note: a member name is matched across types (a changed `add` also matches")
|
||||
print("`group.add(`), so qualify by the owning type shown above when judging.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 3:
|
||||
print("run via scripts/check-doc-impact.sh", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
sys.exit(main(Path(sys.argv[1]), sys.argv[2]))
|
||||
Reference in New Issue
Block a user