1.0.0 release
This commit is contained in:
@@ -0,0 +1,452 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Annotate inferred Swift `let` / `var` bindings with explicit type annotations.
|
||||
|
||||
Drives `/usr/bin/sourcekit-lsp` via LSP-JSON-RPC over stdio. For each file in
|
||||
scope it sends `textDocument/didOpen`, requests `textDocument/inlayHint` for
|
||||
the full range, and applies the LSP `textEdits` returned in each hint (the
|
||||
edits already specify the exact `: Type` insertion). Hints from sourcekit-lsp
|
||||
include inferred-type insertion points for `let` / `var` bindings, closure
|
||||
parameter types, and some other locations; we filter to inlay hints whose
|
||||
`label` begins with ":" so we only apply type annotations.
|
||||
|
||||
Usage:
|
||||
|
||||
python3 annotate_bindings.py [--dry-run] [--limit N] PATH [PATH ...]
|
||||
|
||||
PATH may be a file or directory. Directories are walked recursively for
|
||||
`.swift` files. Files / directories named `.build`, `.git`, `legacy` are
|
||||
skipped.
|
||||
|
||||
Tested on Swift 6.2 / Xcode 16+. Run from the repo root so SwiftPM workspace
|
||||
auto-detection finds Package.swift.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Iterator, Optional
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Configuration
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
REPO_ROOT = Path("/Users/josh/Documents/LyrebirdII")
|
||||
SOURCEKIT_LSP = "/usr/bin/sourcekit-lsp"
|
||||
SKIP_DIR_NAMES = {".build", ".git", "legacy", ".swiftpm", "DerivedData"}
|
||||
DIDOPEN_WARMUP_SECONDS = 1.5
|
||||
INITIALIZE_WARMUP_SECONDS = 6.0
|
||||
INLAYHINT_TIMEOUT_SECONDS = 30.0
|
||||
DEFAULT_TIMEOUT_SECONDS = 15.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# LSP framing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _frame(msg: dict) -> bytes:
|
||||
body = json.dumps(msg).encode("utf-8")
|
||||
return f"Content-Length: {len(body)}\r\n\r\n".encode("utf-8") + body
|
||||
|
||||
|
||||
def _reader_loop(stream, inbox: list, alive: threading.Event) -> None:
|
||||
while alive.is_set():
|
||||
headers = b""
|
||||
while True:
|
||||
line = stream.readline()
|
||||
if not line:
|
||||
alive.clear()
|
||||
return
|
||||
headers += line
|
||||
if line == b"\r\n":
|
||||
break
|
||||
length: Optional[int] = None
|
||||
for h in headers.decode("utf-8", errors="replace").split("\r\n"):
|
||||
if h.lower().startswith("content-length:"):
|
||||
length = int(h.split(":")[1].strip())
|
||||
if length is None:
|
||||
continue
|
||||
body = stream.read(length)
|
||||
try:
|
||||
inbox.append(json.loads(body))
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# LSP client
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class InlayEdit:
|
||||
line: int # zero-indexed
|
||||
character: int # UTF-16 code-units (LSP)
|
||||
new_text: str
|
||||
|
||||
|
||||
class LSPClient:
|
||||
def __init__(self, repo_root: Path) -> None:
|
||||
self._repo_root = repo_root
|
||||
self._proc = subprocess.Popen(
|
||||
[SOURCEKIT_LSP],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
cwd=str(repo_root),
|
||||
)
|
||||
self._inbox: list[dict] = []
|
||||
self._alive = threading.Event()
|
||||
self._alive.set()
|
||||
self._reader = threading.Thread(
|
||||
target=_reader_loop,
|
||||
args=(self._proc.stdout, self._inbox, self._alive),
|
||||
daemon=True,
|
||||
)
|
||||
self._reader.start()
|
||||
self._next_id = 1
|
||||
self._doc_versions: dict[str, int] = {}
|
||||
|
||||
# ---- Low-level send / wait --------------------------------------------
|
||||
|
||||
def _send(self, msg: dict) -> None:
|
||||
assert self._proc.stdin is not None
|
||||
self._proc.stdin.write(_frame(msg))
|
||||
self._proc.stdin.flush()
|
||||
|
||||
def _wait_for(self, req_id: int, timeout: float) -> dict:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
for m in list(self._inbox):
|
||||
if m.get("id") == req_id and ("result" in m or "error" in m):
|
||||
self._inbox.remove(m)
|
||||
return m
|
||||
time.sleep(0.02)
|
||||
raise TimeoutError(f"LSP request {req_id} timed out after {timeout}s")
|
||||
|
||||
def _new_id(self) -> int:
|
||||
i = self._next_id
|
||||
self._next_id += 1
|
||||
return i
|
||||
|
||||
# ---- High-level lifecycle ---------------------------------------------
|
||||
|
||||
def initialize(self) -> None:
|
||||
rid = self._new_id()
|
||||
self._send({
|
||||
"jsonrpc": "2.0", "id": rid, "method": "initialize",
|
||||
"params": {
|
||||
"processId": os.getpid(),
|
||||
"rootUri": f"file://{self._repo_root}",
|
||||
"capabilities": {
|
||||
"textDocument": {
|
||||
"inlayHint": {"dynamicRegistration": False}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
init = self._wait_for(rid, DEFAULT_TIMEOUT_SECONDS)
|
||||
if "error" in init:
|
||||
raise RuntimeError(f"LSP initialize failed: {init['error']}")
|
||||
caps = init.get("result", {}).get("capabilities", {})
|
||||
if not caps.get("inlayHintProvider"):
|
||||
raise RuntimeError("sourcekit-lsp does not advertise inlayHintProvider")
|
||||
self._send({"jsonrpc": "2.0", "method": "initialized", "params": {}})
|
||||
time.sleep(INITIALIZE_WARMUP_SECONDS)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
try:
|
||||
rid = self._new_id()
|
||||
self._send({"jsonrpc": "2.0", "id": rid, "method": "shutdown"})
|
||||
self._wait_for(rid, 5.0)
|
||||
self._send({"jsonrpc": "2.0", "method": "exit"})
|
||||
except Exception:
|
||||
pass
|
||||
self._alive.clear()
|
||||
try:
|
||||
self._proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
self._proc.terminate()
|
||||
|
||||
# ---- File-level operations --------------------------------------------
|
||||
|
||||
def did_open(self, file_path: Path, text: str) -> None:
|
||||
uri = f"file://{file_path}"
|
||||
version = self._doc_versions.get(uri, 0) + 1
|
||||
self._doc_versions[uri] = version
|
||||
self._send({
|
||||
"jsonrpc": "2.0", "method": "textDocument/didOpen",
|
||||
"params": {
|
||||
"textDocument": {
|
||||
"uri": uri,
|
||||
"languageId": "swift",
|
||||
"version": version,
|
||||
"text": text,
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
def did_close(self, file_path: Path) -> None:
|
||||
self._send({
|
||||
"jsonrpc": "2.0", "method": "textDocument/didClose",
|
||||
"params": {"textDocument": {"uri": f"file://{file_path}"}}
|
||||
})
|
||||
|
||||
def inlay_hints(self, file_path: Path, line_count: int) -> list[dict]:
|
||||
rid = self._new_id()
|
||||
self._send({
|
||||
"jsonrpc": "2.0", "id": rid, "method": "textDocument/inlayHint",
|
||||
"params": {
|
||||
"textDocument": {"uri": f"file://{file_path}"},
|
||||
"range": {
|
||||
"start": {"line": 0, "character": 0},
|
||||
"end": {"line": line_count + 1, "character": 0}
|
||||
}
|
||||
}
|
||||
})
|
||||
resp = self._wait_for(rid, INLAYHINT_TIMEOUT_SECONDS)
|
||||
if "error" in resp:
|
||||
raise RuntimeError(f"inlayHint error for {file_path.name}: {resp['error']}")
|
||||
result = resp.get("result") or []
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Edit application
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def collect_edits(hints: list[dict]) -> list[InlayEdit]:
|
||||
edits: list[InlayEdit] = []
|
||||
for h in hints:
|
||||
label = h.get("label")
|
||||
if not isinstance(label, str) or not label.startswith(":"):
|
||||
# Skip non-type hints (parameter-name hints, etc.).
|
||||
continue
|
||||
# Prefer textEdits if present; else synthesise from position + label.
|
||||
text_edits = h.get("textEdits")
|
||||
if isinstance(text_edits, list) and text_edits:
|
||||
for te in text_edits:
|
||||
rng = te.get("range", {}).get("start", {})
|
||||
edits.append(InlayEdit(
|
||||
line=int(rng.get("line", 0)),
|
||||
character=int(rng.get("character", 0)),
|
||||
new_text=str(te.get("newText", label)),
|
||||
))
|
||||
else:
|
||||
pos = h.get("position", {})
|
||||
edits.append(InlayEdit(
|
||||
line=int(pos.get("line", 0)),
|
||||
character=int(pos.get("character", 0)),
|
||||
new_text=label,
|
||||
))
|
||||
return edits
|
||||
|
||||
|
||||
def _is_in_tuple_pattern(line: str, col: int) -> bool:
|
||||
"""True if the position at `col` on `line` sits inside an unclosed `(`
|
||||
on the same line — typically a tuple-destructure pattern like
|
||||
`for (i, buf) in ...` or `let (a, b) = ...` or
|
||||
`if case let (.foo, .bar) = ...`. Swift does not allow
|
||||
`: T` annotations inside these patterns, so we must skip them.
|
||||
|
||||
Counts `(` minus `)` on `line[:col]` ignoring characters inside
|
||||
string / char literals. If positive, the hint sits inside parens.
|
||||
"""
|
||||
depth = 0
|
||||
in_string = False
|
||||
i = 0
|
||||
while i < col and i < len(line):
|
||||
c = line[i]
|
||||
if in_string:
|
||||
if c == "\\" and i + 1 < len(line):
|
||||
i += 2
|
||||
continue
|
||||
if c == '"':
|
||||
in_string = False
|
||||
else:
|
||||
if c == '"':
|
||||
in_string = True
|
||||
elif c == "(":
|
||||
depth += 1
|
||||
elif c == ")":
|
||||
depth -= 1
|
||||
i += 1
|
||||
return depth > 0
|
||||
|
||||
|
||||
def _is_function_signature_context(line: str, col: int) -> bool:
|
||||
"""True if the line looks like a function / initializer / subscript
|
||||
signature parameter — those bindings already have a type annotation
|
||||
grammar of their own and inlayHints occasionally surface there for
|
||||
default-value params we should not double-annotate."""
|
||||
prefix = line[:col].lstrip()
|
||||
# `func foo(` / `init(` / `subscript(` on the same line implies we are
|
||||
# in a parameter list; SourceKit normally suppresses hints here but
|
||||
# check defensively.
|
||||
return any(
|
||||
kw in prefix
|
||||
for kw in (" func ", " init(", " subscript(",
|
||||
"func ", "init(", "subscript(")
|
||||
)
|
||||
|
||||
|
||||
_BINDING_SUFFIX_RE = re.compile(r"(?:^|[^A-Za-z_0-9])(let|var|for)\s+([A-Za-z_]\w*)$")
|
||||
_PATTERN_CONTEXT_RE = re.compile(r"\b(case|catch)\b")
|
||||
|
||||
|
||||
def _has_binding_keyword_before(line: str, col: int) -> bool:
|
||||
"""True iff `line[:col]` ends with `<let|var|for><whitespace><identifier>`
|
||||
with NOTHING intervening — i.e. the inlay hint is on the identifier
|
||||
immediately following the binding keyword — AND the binding is not in
|
||||
a pattern context (`case let ...` / `catch let ...`), where Swift
|
||||
treats the identifier as a pattern variable that cannot carry a
|
||||
`: Type` annotation inline.
|
||||
|
||||
This rejects every spot where SourceKit emits a `: Type` hint that
|
||||
Swift would not accept inline:
|
||||
- closure-header params: `... { ptr in` (no let/var/for)
|
||||
- closure-header w/ paren: `... { (ptr in` (intervening `{`)
|
||||
- capture lists: `... { [weak self in` (intervening `{` + `[`)
|
||||
- tuple destructure: `let (a, b) = ...` (intervening `(`)
|
||||
- compound bindings: `let x = 5, y` (intervening `,`)
|
||||
- argument labels: `foo(arg` (no binding kw)
|
||||
- catch patterns: `} catch let err as Foo` (pattern position)
|
||||
- case patterns: `case let .foo(x)` (pattern position)
|
||||
|
||||
Accepts the canonical forms `let x`, `var y`, `for i`, including
|
||||
when the binding lives inside `if let` / `guard let`.
|
||||
"""
|
||||
prefix = line[:col]
|
||||
m = _BINDING_SUFFIX_RE.search(prefix)
|
||||
if m is None:
|
||||
return False
|
||||
# Pattern-context check: the matched `let|var|for` must not be preceded
|
||||
# on the same line by `case` or `catch` (those introduce pattern-binding
|
||||
# syntax where `: Type` is not accepted inline).
|
||||
if _PATTERN_CONTEXT_RE.search(prefix[: m.start(1)]):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def apply_edits(text: str, edits: list[InlayEdit]) -> tuple[str, int]:
|
||||
"""Apply InlayEdits to `text`. LSP positions are UTF-16 code-units; for
|
||||
ASCII source this matches Python char positions. Sources with non-BMP
|
||||
characters would need conversion, but Lyrebird source is ASCII-clean.
|
||||
Returns (new_text, applied_count) — applied_count may be less than
|
||||
len(edits) if some were filtered as unsafe (tuple-pattern / signature)."""
|
||||
if not edits:
|
||||
return text, 0
|
||||
lines = text.split("\n")
|
||||
applied = 0
|
||||
# Sort tail-to-head so earlier offsets stay valid as we mutate.
|
||||
edits = sorted(edits, key=lambda e: (e.line, e.character), reverse=True)
|
||||
for e in edits:
|
||||
if e.line < 0 or e.line >= len(lines):
|
||||
continue
|
||||
line = lines[e.line]
|
||||
col = min(e.character, len(line))
|
||||
if not _has_binding_keyword_before(line, col):
|
||||
continue
|
||||
if _is_in_tuple_pattern(line, col):
|
||||
continue
|
||||
if _is_function_signature_context(line, col):
|
||||
continue
|
||||
lines[e.line] = line[:col] + e.new_text + line[col:]
|
||||
applied += 1
|
||||
return "\n".join(lines), applied
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Driver
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def iter_swift_files(paths: list[Path]) -> Iterator[Path]:
|
||||
for p in paths:
|
||||
if p.is_file() and p.suffix == ".swift":
|
||||
yield p
|
||||
elif p.is_dir():
|
||||
for root, dirs, files in os.walk(p):
|
||||
dirs[:] = [d for d in dirs if d not in SKIP_DIR_NAMES]
|
||||
for f in files:
|
||||
if f.endswith(".swift"):
|
||||
yield Path(root) / f
|
||||
|
||||
|
||||
def process_file(client: LSPClient, file_path: Path, dry_run: bool) -> tuple[int, bool]:
|
||||
"""Return (#applied_edits, was_modified)."""
|
||||
text = file_path.read_text()
|
||||
line_count = text.count("\n")
|
||||
client.did_open(file_path, text)
|
||||
time.sleep(DIDOPEN_WARMUP_SECONDS)
|
||||
try:
|
||||
hints = client.inlay_hints(file_path, line_count)
|
||||
finally:
|
||||
client.did_close(file_path)
|
||||
edits = collect_edits(hints)
|
||||
if not edits:
|
||||
return (0, False)
|
||||
new_text, applied = apply_edits(text, edits)
|
||||
if applied == 0 or new_text == text:
|
||||
return (0, False)
|
||||
if not dry_run:
|
||||
file_path.write_text(new_text)
|
||||
return (applied, True)
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("paths", nargs="+", help="files or dirs to process")
|
||||
ap.add_argument("--dry-run", action="store_true",
|
||||
help="report what would change without writing files")
|
||||
ap.add_argument("--limit", type=int, default=0,
|
||||
help="stop after N modified files (0 = no limit)")
|
||||
ap.add_argument("--repo-root", type=Path, default=REPO_ROOT)
|
||||
ns = ap.parse_args(argv)
|
||||
|
||||
paths = [Path(p).resolve() for p in ns.paths]
|
||||
files = list(iter_swift_files(paths))
|
||||
if not files:
|
||||
print("no .swift files found", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print(f"Found {len(files)} Swift file(s) to process.", file=sys.stderr)
|
||||
|
||||
client = LSPClient(ns.repo_root)
|
||||
try:
|
||||
print("Initializing LSP ...", file=sys.stderr)
|
||||
client.initialize()
|
||||
print("LSP ready.", file=sys.stderr)
|
||||
total_edits = 0
|
||||
modified_count = 0
|
||||
for i, f in enumerate(files, 1):
|
||||
try:
|
||||
n_edits, modified = process_file(client, f, ns.dry_run)
|
||||
except Exception as exc:
|
||||
print(f" [{i}/{len(files)}] ERROR {f}: {exc}", file=sys.stderr)
|
||||
continue
|
||||
total_edits += n_edits
|
||||
if modified:
|
||||
modified_count += 1
|
||||
print(f" [{i}/{len(files)}] {n_edits:4d} edits {f.relative_to(ns.repo_root)}", file=sys.stderr)
|
||||
if ns.limit > 0 and modified_count >= ns.limit:
|
||||
print(f"--limit {ns.limit} reached; stopping.", file=sys.stderr)
|
||||
break
|
||||
print(f"\nTotal: {modified_count} files modified, {total_edits} annotations applied.", file=sys.stderr)
|
||||
return 0
|
||||
finally:
|
||||
client.shutdown()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
Reference in New Issue
Block a user