#!/usr/bin/env python3 """doc_snippets.py — extract ```swift fences from the docs and typecheck them. Driven by scripts/check-doc-snippets.sh; not meant to be run directly. Why this exists: nothing compiles the ~1450 swift fences in the DocC catalog and the /// doc comments, so examples rot silently. `engine.add(...)` became throwing and 11 examples kept calling it without `try` for months; `LyrebirdFloat` was deleted and 75 references outlived it. Both are type errors — so typechecking the fences catches them. Mechanism: - Each fence becomes one generated .swift file: hoisted imports, then the body inside `@MainActor func _fence_N() { ... }`. Everything lives in the function so that two fences declaring the same helper type can't collide at file scope. - `#sourceLocation` is emitted before the body, so swiftc diagnostics point at the ORIGINAL markdown file and line rather than the generated file. - Classification typechecks each fence in its OWN invocation (parallelised): batching is unsound, because a parse error in one file aborts swiftc before later files are reached. A fence that compiles under NONE of the preambles self-excludes — that is how iOS-only examples, Package.swift manifest snippets, and pseudo-code drop out without a skip list. """ import concurrent.futures as cf import hashlib import os import re import subprocess import sys from pathlib import Path # Body text substituted ahead of a fence, keyed by preamble name. `none` is the bare case. # Capped deliberately: if a fence needs a fifth preamble, that is a signal the doc should # be rewritten to stand on its own rather than a signal to grow this table. _MY_SYNTH = ( "final class MySynth: SynthesizerBase {\n" " override func build() { output(bus: 0, source: OscSin.Audio(freq: 440.0) * 0.2) }\n" "}\n" ) _ENGINE = ( "let engine: SynthesisEngine = SynthesisEngine(" "blockSize: 512, sampleRate: 44100, numOutputChannels: 2, " "numInputChannels: 0, driver: OfflineDriver())\n" ) # Tried IN ORDER, least-invasive first: a preamble that declares a name the fence also # declares makes the fence fail, so the narrowest match must win. A fence that defines its # own `MySynth` is caught by `none`; one that defines its own engine but uses `MySynth` is # caught by `synth`; one that uses both is caught by `engine`. # # Capped deliberately. If a fence needs a fifth preamble, that is a signal the DOC should # be rewritten to stand on its own — which is the actual goal — not a signal to grow this. PREAMBLES: dict[str, str] = { "none": "", "synth": _MY_SYNTH, "engine": _MY_SYNTH + _ENGINE + "let synth: MySynth = MySynth()\n_ = (engine, synth)\n", # `member` maps to no prefix text — it is a WRAPPER, handled via MEMBER_PREAMBLES # below; this entry exists only so the classify loop iterates it in order. # `member` is structurally different: it is not a prefix but a WRAPPER. Many fences are # the body of `build()` lifted out of its class — they call `output(bus:source:)` / # `addOutputGenerator`, which are SynthesizerBase members and exist in no other context. # `output` was by far the biggest single blocker among unchecked fences. "member": "", } # Preambles whose body must be wrapped in a SynthesizerBase subclass rather than a function. MEMBER_PREAMBLES: set[str] = {"member"} FENCE_MD = re.compile(r"^\s*```\s*swift\s*$") FENCE_END = re.compile(r"^\s*```\s*$") def extract_from_markdown(path: Path) -> list[dict]: """Fences in a .md file. `line` is 1-based and points at the first body line.""" out: list[dict] = [] lines = path.read_text().split("\n") i = 0 while i < len(lines): if FENCE_MD.match(lines[i]): start = i + 1 body: list[str] = [] i += 1 while i < len(lines) and not FENCE_END.match(lines[i]): body.append(lines[i]) i += 1 out.append({"line": start + 1, "body": "\n".join(body)}) i += 1 return out def extract_from_swift(path: Path) -> list[dict]: """Fences inside `/// ` doc comments. The `/// ` prefix is stripped from each line.""" out: list[dict] = [] lines = path.read_text().split("\n") i = 0 while i < len(lines): stripped = re.sub(r"^\s*///\s?", "", lines[i]) if "///" in lines[i] else None if stripped is not None and FENCE_MD.match(stripped): start = i + 1 body: list[str] = [] i += 1 while i < len(lines): cur = lines[i] if "///" not in cur: break inner = re.sub(r"^\s*///\s?", "", cur) if FENCE_END.match(inner): break body.append(inner) i += 1 out.append({"line": start + 1, "body": "\n".join(body)}) i += 1 return out def collect(root: Path) -> list[dict]: """Every swift fence in the doc corpus, tagged with its file and per-file ordinal.""" fences: list[dict] = [] targets: list[Path] = [] for pat in ("Sources/**/*.md", "Sources/**/*.swift", "docs/**/*.md", "*.md"): targets += sorted(root.glob(pat)) # Root-level docs that narrate history or plans rather than API usage — same # rationale as the docs/00- / docs/01- skip below. skip_root = {"PLAN.md", "DOC_UPDATE_PLAN.md", "RELEASES.md"} for f in targets: rel = str(f.relative_to(root)) # Planning archives narrate history, including APIs that no longer exist. if rel.startswith(("docs/00-", "docs/01-")) or rel in skip_root: continue found = extract_from_swift(f) if f.suffix == ".swift" else extract_from_markdown(f) for ordinal, fence in enumerate(found): fences.append({"file": rel, "ordinal": ordinal, **fence}) return fences def generate(fence: dict, preamble: str, outdir: Path, index: int, remap: bool) -> Path: """Write one generated .swift for a fence. Imports must sit at file scope, so they are hoisted — but each hoisted line is left behind as a BLANK line rather than deleted, which keeps every remaining body line at its original offset so `#sourceLocation` stays exact regardless of where in the fence the import appeared. The wrapper is `throws` so a correct `try engine.add(...)` compiles; a MISSING `try` still errors ("call can throw but is not marked with 'try'"), which is the point. The body is wrapped in a `@MainActor` function: doc examples are language-side code, and a nonisolated wrapper would false-positive on every `@MainActor` `engine.add`. Wrapping everything (including type declarations, which Swift allows locally) also means two fences declaring the same helper name cannot collide at file scope. `remap` controls `#sourceLocation`. With it, diagnostics point at the original markdown — great for a human, but it also means swiftc no longer attributes an error to the generated file, so classification could not tell WHICH fence failed. Classify therefore runs with remap=False and checks run with remap=True. """ body_lines = fence["body"].split("\n") # Only the LEADING import run is hoisted. Scanning the whole body would also match an # `import` line inside a Swift multi-line string literal (the scaffolder/exporter docs # show generated source) and blank it out of the literal. lead = 0 for i, l in enumerate(body_lines): s = l.strip() if s.startswith("import "): lead = i + 1 elif s and not s.startswith("//"): break imports = [l.strip() for l in body_lines[:lead] if l.strip().startswith("import ")] rest = ["" if (i < lead and l.strip().startswith("import ")) else l for i, l in enumerate(body_lines)] head = ["import LyrebirdSynth"] + [i for i in imports if i != "import LyrebirdSynth"] if preamble in MEMBER_PREAMBLES: # The fence is a `build()` body: wrap it in a subclass so SynthesizerBase members # (`output(bus:source:)`, `addOutputGenerator`) resolve. `build()` is @MainActor via # the base, and is not throwing — a `try` inside such a fence will correctly fail. open_lines = [f"final class DocSynth_{index}: SynthesizerBase {{", " override func build() {"] close_lines = [" }", "}"] else: open_lines = [f"@MainActor func _fence_{index}() throws {{", PREAMBLES[preamble]] close_lines = ["}"] src = head + open_lines if remap: src.append(f'#sourceLocation(file: "{fence["file"]}", line: {fence["line"]})') src.append("\n".join(rest)) if remap: src.append("#sourceLocation()") src += close_lines p = outdir / f"fence_{index}.swift" p.write_text("\n".join(src) + "\n") return p def _swiftc(files: list[Path], root: Path, sdk: str, modules: Path): cmd = [ "xcrun", "swiftc", "-typecheck", "-swift-version", "6", "-I", str(modules), "-I", str(root / "Sources/LyrebirdC"), "-sdk", sdk, "-target", host_triple(), ] + [str(f) for f in files] proc = subprocess.run(cmd, capture_output=True, text=True) return proc.returncode, proc.stderr + proc.stdout def typecheck_batch(files: list[Path], root: Path, sdk: str, modules: Path): """Typecheck every file in ONE invocation. Fast, and sound when it comes back clean: no diagnostics at all means swiftc processed the whole set. NOT sound for deciding which individual file failed — a parse error in one file aborts the run before later files are reached, so absence of a diagnostic does not prove a file compiles. Use typecheck_each for that. """ if not files: return 0, "" return _swiftc(files, root, sdk, modules) def typecheck_each(files: list[Path], root: Path, sdk: str, modules: Path) -> set[str]: """Typecheck each file on its own, in parallel. Returns the set of paths that failed. One invocation per file is the only sound way to classify: batching lets an early parse error mask every file after it (observed — an invalid Package.swift snippet aborted the run and silently marked ~1450 unreached fences as 'compiling'). """ failed: set[str] = set() if not files: return failed with cf.ThreadPoolExecutor(max_workers=os.cpu_count() or 8) as ex: futs = {ex.submit(_swiftc, [f], root, sdk, modules): f for f in files} for fut in cf.as_completed(futs): code, _ = fut.result() if code != 0: failed.add(str(futs[fut])) return failed def sdk_path() -> str: proc = subprocess.run(["xcrun", "--show-sdk-path"], capture_output=True, text=True) out = proc.stdout.strip() if proc.returncode != 0 or not out: raise RuntimeError( "xcrun --show-sdk-path failed; refusing to continue. Without an SDK every fence " "would fail to typecheck, which classify would record as 'nothing is checkable' " "and check would then pass trivially forever.") return out def modules_dir(root: Path) -> Path: """Locate the built module dir rather than hardcoding an architecture. A hardcoded arm64 path silently resolves to nothing on an Intel host, which degrades into the same empty-manifest false OK as a missing SDK. """ proc = subprocess.run(["swift", "build", "--show-bin-path"], cwd=root, capture_output=True, text=True) if proc.returncode == 0 and proc.stdout.strip(): d = Path(proc.stdout.strip()) / "Modules" if d.is_dir(): return d raise RuntimeError("could not locate the built Modules dir; run `swift build` first") def host_triple() -> str: machine = subprocess.run(["uname", "-m"], capture_output=True, text=True).stdout.strip() arch = "arm64" if machine == "arm64" else "x86_64" return f"{arch}-apple-macosx15.0" def body_hash(body: str) -> str: """Short content hash of a fence body.""" return hashlib.sha256(body.encode()).hexdigest()[:16] def key(f: dict) -> str: """Manifest identity: file + ordinal + CONTENT HASH. The hash is load-bearing, not decoration. Keying on position alone means inserting a fence shifts every later ordinal while each recorded key still resolves — so the staleness check never fires and the harness silently typechecks a DIFFERENT fence under the preamble recorded for the old one, reporting OK either way. A hash mismatch is treated exactly like a missing fence: re-classify. """ return f"{f['file']}\t{f['ordinal']}\t{body_hash(f['body'])}" def cmd_classify(root: Path, outdir: Path, manifest: Path, allow_shrink: bool = False) -> int: """Ask the compiler which fences compile, and under which preamble. Nobody annotates ~1450 fences by hand: a fence is checkable iff it typechecks. Anything that compiles under NONE of the preambles self-excludes — that is how iOS-only examples, Package.swift manifest snippets and pseudo-code drop out with no skip list. """ fences = collect(root) print(f" {len(fences)} swift fence(s) found") modules = modules_dir(root) sdk = sdk_path() classified: dict[str, str] = {} remaining = list(enumerate(fences)) for pre in PREAMBLES: if not remaining: break d = outdir / pre d.mkdir(parents=True, exist_ok=True) gen: dict[str, tuple] = {} for idx, fence in remaining: p = generate(fence, pre, d, idx, remap=False) gen[str(p)] = (idx, fence) failed = typecheck_each([Path(p) for p in gen], root, sdk, modules) passed = [(i, f) for p, (i, f) in gen.items() if p not in failed] for _, f in passed: classified[key(f)] = pre print(f" preamble '{pre}': {len(passed)} of {len(remaining)} compile") remaining = [(i, f) for p, (i, f) in gen.items() if p in failed] print(f" unclassifiable (left unchecked): {len(remaining)}") # Refuse a silent coverage drop. `check` tells the user to re-classify when it fails, # so without this a real breakage could be "resolved" by quietly checking less. if manifest.exists() and not allow_shrink: previous = len([l for l in manifest.read_text().split("\n") if l.strip()]) if len(classified) < previous: print(f"REFUSED: coverage would drop from {previous} to {len(classified)} fence(s).", file=sys.stderr) print(" A doc example probably broke — fix it rather than un-recording it.", file=sys.stderr) print(" If the drop is intended (an example was deliberately removed):", file=sys.stderr) print(" bash scripts/check-doc-snippets.sh --classify --allow-shrink", file=sys.stderr) return 1 manifest.write_text("\n".join(f"{k}\t{v}" for k, v in sorted(classified.items())) + "\n") print(f"OK: recorded {len(classified)} checkable fence(s) in {manifest.name}") return 0 def cmd_check(root: Path, outdir: Path, manifest: Path) -> int: """Typecheck exactly the fences the manifest records as checkable.""" if not manifest.exists(): print(f"ERROR: no manifest at {manifest}", file=sys.stderr) print(" Create it with: bash scripts/check-doc-snippets.sh --classify", file=sys.stderr) return 1 recorded: dict[str, str] = {} for line in manifest.read_text().split("\n"): if not line.strip(): continue parts = line.split("\t") if len(parts) != 4: print(f"ERROR: malformed manifest line: {line!r}", file=sys.stderr) print(" Re-run: bash scripts/check-doc-snippets.sh --classify", file=sys.stderr) return 1 f, o, h, pre = parts recorded[f"{f}\t{o}\t{h}"] = pre fences = {key(f): f for f in collect(root)} missing = [k for k in recorded if k not in fences] if missing: # A hard failure, not a warning: a recorded fence that no longer matches means the # manifest is stale, and continuing would silently check fewer examples than the # manifest claims — the guard would report OK while protecting nothing. print(f"FAIL: {len(missing)} recorded fence(s) no longer match the docs.", file=sys.stderr) print(" A fence was edited, moved, inserted or deleted. The manifest is keyed", file=sys.stderr) print(" on content, so this is drift — not necessarily breakage.", file=sys.stderr) for m in missing[:8]: f, o, h = m.split("\t") print(f" - {f} (fence #{o})", file=sys.stderr) print("", file=sys.stderr) print(" Re-run: bash scripts/check-doc-snippets.sh --classify", file=sys.stderr) return 1 modules = modules_dir(root) sdk = sdk_path() files: list[Path] = [] outdir.mkdir(parents=True, exist_ok=True) for i, (k, pre) in enumerate(sorted(recorded.items())): if k not in fences: continue files.append(generate(fences[k], pre, outdir, i, remap=True)) code, out = typecheck_batch(files, root, sdk, modules) errs = [l for l in out.split("\n") if re.match(r"^\S.*?:\d+:\d+: error:", l)] if code != 0: if not errs: # swiftc failed but we could not parse its diagnostics — show them raw rather # than printing a confusing "0 example(s) no longer compile". print("FAIL: swiftc reported a failure we could not parse:", file=sys.stderr) print(out[-3000:], file=sys.stderr) return 1 print(f"FAIL: {len(errs)} doc example(s) no longer compile:", file=sys.stderr) for e in errs[:40]: print(f" {e}", file=sys.stderr) print("", file=sys.stderr) print("Each location above is the ORIGINAL doc file and line — fix the example there.", file=sys.stderr) print("If an example is intentionally no longer checkable, re-run --classify.", file=sys.stderr) return 1 print(f"OK: {len(files)} doc example(s) still compile.") return 0 if __name__ == "__main__": if len(sys.argv) < 4: print("run via scripts/check-doc-snippets.sh", file=sys.stderr) sys.exit(2) _mode, _root, _out = sys.argv[1], Path(sys.argv[2]), Path(sys.argv[3]) _shrink = "--allow-shrink" in sys.argv[4:] _man = _root / "scripts/doc-snippets-manifest.txt" try: sys.exit(cmd_classify(_root, _out, _man, _shrink) if _mode == "classify" else cmd_check(_root, _out, _man)) except RuntimeError as e: print(f"ERROR: {e}", file=sys.stderr) sys.exit(1)