v1.4.0 release: live-coding scratch editor, interpreted Graph DSL, ClosureSynthesizer + SampleLoop
This commit is contained in:
@@ -0,0 +1,413 @@
|
||||
// SourceKitLSPClient.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// A minimal LSP JSON-RPC client that drives the toolchain's `sourcekit-lsp`
|
||||
// executable over stdio to provide Swift code completion for the live-coding
|
||||
// editor. Only the handful of requests the editor needs are implemented:
|
||||
// `initialize` / `initialized`, `textDocument/didOpen` / `didChange`, and
|
||||
// `textDocument/completion`.
|
||||
//
|
||||
// macOS only — the whole live-compile surface shells out to the toolchain.
|
||||
|
||||
#if os(macOS)
|
||||
import Foundation
|
||||
|
||||
/// Nanoseconds in one second — for `Task.sleep`.
|
||||
private let nanosecondsPerSecond: Double = 1_000_000_000
|
||||
|
||||
/// Drives `sourcekit-lsp` over stdio.
|
||||
///
|
||||
/// `@unchecked Sendable`: the process handles and the pending-request table are
|
||||
/// guarded by `_lock`; a dedicated background reader thread parses framed
|
||||
/// messages and completes the continuations stored under that lock. Public
|
||||
/// methods are `async` and safe to call from any task.
|
||||
public final class SourceKitLSPClient: @unchecked Sendable {
|
||||
|
||||
private let _process: Process = Process()
|
||||
private let _stdin: Pipe = Pipe()
|
||||
private let _stdout: Pipe = Pipe()
|
||||
|
||||
private let _lock: NSLock = NSLock()
|
||||
private var _nextID: Int = 1
|
||||
// Response continuations keyed by request id, completed by the reader thread.
|
||||
// The payload is the raw response-body `Data` (Sendable); callers parse it.
|
||||
private var _pending: [Int: CheckedContinuation<Data, Error>] = [:]
|
||||
private var _running: Bool = false
|
||||
// Accumulates stdout bytes until a full `Content-Length`-framed message is available.
|
||||
private var _readBuffer: Data = Data()
|
||||
|
||||
/// Default request timeout in seconds. Completion should be well under this;
|
||||
/// the ceiling guards against a wedged server.
|
||||
public static let defaultRequestTimeout: TimeInterval = 15.0
|
||||
|
||||
// `nil` = resolve from the toolchain lazily in `start()`. Kept lazy so the
|
||||
// synchronous `init` — evaluated in the caller's isolation, often the main
|
||||
// actor via `SnippetCompletionService`'s default argument — never shells out
|
||||
// to `xcrun`.
|
||||
private let _explicitExecutableURL: URL?
|
||||
private let _launchArguments: [String]
|
||||
private let _requestTimeout: TimeInterval
|
||||
|
||||
/// - Parameters:
|
||||
/// - executableURL: Path to `sourcekit-lsp`. When `nil` (default) it is
|
||||
/// resolved from the toolchain via `xcrun` inside `start()` — not in
|
||||
/// `init`, so construction never blocks its caller.
|
||||
/// - arguments: Launch arguments for the executable (default none).
|
||||
/// - requestTimeout: Per-request ceiling in seconds before ``request`` fails
|
||||
/// with ``SourceKitLSPError/timedOut(method:)``.
|
||||
public init(
|
||||
executableURL: URL? = nil,
|
||||
arguments: [String] = [],
|
||||
requestTimeout: TimeInterval = SourceKitLSPClient.defaultRequestTimeout
|
||||
) {
|
||||
self._explicitExecutableURL = executableURL
|
||||
self._launchArguments = arguments
|
||||
self._requestTimeout = requestTimeout
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Safety net: a client dropped without an explicit `shutdown()` would
|
||||
// otherwise orphan the `sourcekit-lsp` subprocess and leave the reader
|
||||
// thread blocked in `availableData`. `shutdown()` is idempotent.
|
||||
shutdown()
|
||||
}
|
||||
|
||||
/// Resolve `sourcekit-lsp` from the active toolchain via `xcrun`, falling
|
||||
/// back to the conventional Xcode path.
|
||||
private static func resolveExecutable() -> URL {
|
||||
let xcrun: Process = Process()
|
||||
xcrun.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
|
||||
xcrun.arguments = ["--find", "sourcekit-lsp"]
|
||||
let out: Pipe = Pipe()
|
||||
xcrun.standardOutput = out
|
||||
xcrun.standardError = Pipe()
|
||||
try? xcrun.run()
|
||||
xcrun.waitUntilExit()
|
||||
let data: Data = out.fileHandleForReading.readDataToEndOfFile()
|
||||
if let path: String = String(data: data, encoding: .utf8)?
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines), !path.isEmpty {
|
||||
return URL(fileURLWithPath: path)
|
||||
}
|
||||
return URL(fileURLWithPath:
|
||||
"/usr/bin/sourcekit-lsp") // last resort; run(...) will surface a launch error
|
||||
}
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
/// Launch the server, run the `initialize` handshake against `rootURI`, and
|
||||
/// send `initialized`. Call once per client — the caller (e.g.
|
||||
/// ``SnippetCompletionService``) guards against a second call; a repeat call
|
||||
/// here would re-`run()` the process. Resolving the executable (an `xcrun`
|
||||
/// lookup when no explicit path was given) happens here, off the constructing
|
||||
/// caller's thread.
|
||||
public func start(rootURI: String) async throws {
|
||||
_process.executableURL = _explicitExecutableURL ?? SourceKitLSPClient.resolveExecutable()
|
||||
_process.arguments = _launchArguments
|
||||
_process.standardInput = _stdin
|
||||
_process.standardOutput = _stdout
|
||||
_process.standardError = Pipe() // discard server logging
|
||||
do {
|
||||
try _process.run()
|
||||
} catch {
|
||||
throw SourceKitLSPError.launchFailed("\(error)")
|
||||
}
|
||||
_setRunning(true)
|
||||
_startReader()
|
||||
|
||||
let params: [String: Any] = [
|
||||
"processId": Int(ProcessInfo.processInfo.processIdentifier),
|
||||
"rootUri": rootURI,
|
||||
"capabilities": [
|
||||
"textDocument": [
|
||||
"completion": [
|
||||
"completionItem": ["snippetSupport": false]
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
_ = try await request(method: "initialize", params: params)
|
||||
notify(method: "initialized", params: [:])
|
||||
}
|
||||
|
||||
/// Terminate the server. Safe to call multiple times.
|
||||
public func shutdown() {
|
||||
_lock.lock()
|
||||
let wasRunning: Bool = _running
|
||||
_lock.unlock()
|
||||
_failAllPending(with: SourceKitLSPError.notRunning)
|
||||
guard wasRunning else { return }
|
||||
// Send the graceful `exit` while still marked running (`_send` gates on
|
||||
// `_running`), then flip the flag and terminate.
|
||||
notify(method: "exit", params: [:])
|
||||
_setRunning(false)
|
||||
_process.terminate()
|
||||
}
|
||||
|
||||
/// Remove and fail every in-flight request continuation with `error`.
|
||||
/// Under `_lock`, so it never double-resumes against the reader's dispatch.
|
||||
private func _failAllPending(with error: Error) {
|
||||
_lock.lock()
|
||||
let pending: [Int: CheckedContinuation<Data, Error>] = _pending
|
||||
_pending.removeAll()
|
||||
_lock.unlock()
|
||||
for (_, cont): (Int, CheckedContinuation<Data, Error>) in pending {
|
||||
cont.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Document sync
|
||||
|
||||
/// Open `text` as a Swift document at `uri`.
|
||||
public func didOpen(uri: String, text: String, version: Int = 1) {
|
||||
notify(method: "textDocument/didOpen", params: [
|
||||
"textDocument": [
|
||||
"uri": uri, "languageId": "swift", "version": version, "text": text
|
||||
]
|
||||
])
|
||||
}
|
||||
|
||||
/// Replace the full contents of `uri` with `text` (whole-document sync).
|
||||
public func didChange(uri: String, text: String, version: Int) {
|
||||
notify(method: "textDocument/didChange", params: [
|
||||
"textDocument": ["uri": uri, "version": version],
|
||||
"contentChanges": [["text": text]]
|
||||
])
|
||||
}
|
||||
|
||||
// MARK: - Completion
|
||||
|
||||
/// Request completions at a zero-based `line` / `character` in `uri`.
|
||||
/// Returns the parsed items (possibly empty).
|
||||
public func completion(uri: String, line: Int, character: Int) async throws -> [LSPCompletionItem] {
|
||||
let body: Data = try await request(method: "textDocument/completion", params: [
|
||||
"textDocument": ["uri": uri],
|
||||
"position": ["line": line, "character": character]
|
||||
])
|
||||
let message: [String: Any] = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]
|
||||
// The result is either a CompletionList ({ items: [...] }) or a bare
|
||||
// CompletionItem[].
|
||||
let rawItems: [Any]
|
||||
if let dict: [String: Any] = message["result"] as? [String: Any],
|
||||
let items: [Any] = dict["items"] as? [Any] {
|
||||
rawItems = items
|
||||
} else if let arr: [Any] = message["result"] as? [Any] {
|
||||
rawItems = arr
|
||||
} else {
|
||||
return []
|
||||
}
|
||||
var out: [LSPCompletionItem] = []
|
||||
out.reserveCapacity(rawItems.count)
|
||||
for case let item as [String: Any] in rawItems {
|
||||
guard let label: String = item["label"] as? String else { continue }
|
||||
let detail: String? = item["detail"] as? String
|
||||
let insert: String = (item["insertText"] as? String)
|
||||
?? (item["filterText"] as? String)
|
||||
?? label
|
||||
let kind: Int? = item["kind"] as? Int
|
||||
let sortText: String? = item["sortText"] as? String
|
||||
out.append(LSPCompletionItem(
|
||||
label: label, detail: detail, insertText: insert, kind: kind, sortText: sortText))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// MARK: - JSON-RPC plumbing
|
||||
|
||||
// Lock-protected mutations, factored into sync helpers so no `NSLock` call
|
||||
// happens inside an `async` function (forbidden under Swift 6).
|
||||
|
||||
private func _setRunning(_ value: Bool) {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
_running = value
|
||||
}
|
||||
|
||||
private func _isRunning() -> Bool {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
return _running
|
||||
}
|
||||
|
||||
private func _claimRequestID() -> Int? {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
guard _running else { return nil }
|
||||
let id: Int = _nextID; _nextID += 1
|
||||
return id
|
||||
}
|
||||
|
||||
private func _storePending(_ id: Int, _ cont: CheckedContinuation<Data, Error>) {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
_pending[id] = cont
|
||||
}
|
||||
|
||||
/// Remove a pending request AND resume its continuation with `error`.
|
||||
/// Resuming is essential: a task-group child suspended on
|
||||
/// `withCheckedThrowingContinuation` is not woken by `cancelAll()`, so
|
||||
/// merely dropping the entry would leave `request(...)`'s group awaiting a
|
||||
/// child that never completes — a deadlock. `removeValue` under `_lock` means
|
||||
/// only one side (this drop, or the reader's dispatch) ever holds the
|
||||
/// continuation, so there is no double-resume.
|
||||
private func _dropPending(_ id: Int, resumingWith error: Error) {
|
||||
_lock.lock()
|
||||
let cont: CheckedContinuation<Data, Error>? = _pending.removeValue(forKey: id)
|
||||
_lock.unlock()
|
||||
cont?.resume(throwing: error)
|
||||
}
|
||||
|
||||
/// Send a request and await its response body (`Data`). Times out per
|
||||
/// ``requestTimeout``.
|
||||
private func request(method: String, params: [String: Any]) async throws -> Data {
|
||||
guard let id: Int = _claimRequestID() else { throw SourceKitLSPError.notRunning }
|
||||
// Frame the message to `Data` synchronously here so the child task
|
||||
// captures only Sendable state (`framed`, `id`), never the non-Sendable
|
||||
// `[String: Any]` params.
|
||||
guard let framed: Data = _frame(id: id, method: method, params: params) else {
|
||||
throw SourceKitLSPError.serverError(code: -1, message: "could not encode \(method)")
|
||||
}
|
||||
let timeoutSeconds: TimeInterval = _requestTimeout
|
||||
return try await withThrowingTaskGroup(of: Data.self) { group in
|
||||
group.addTask { [weak self] in
|
||||
guard let self: SourceKitLSPClient else { throw SourceKitLSPError.notRunning }
|
||||
return try await withCheckedThrowingContinuation { cont in
|
||||
self._storePending(id, cont)
|
||||
// Close the store-vs-EOF window: if the server died between
|
||||
// `_claimRequestID` and here, the reader already drained the
|
||||
// pending table, so fail this one now instead of waiting for
|
||||
// the timeout. `_dropPending` removes under the lock, so it
|
||||
// can't double-resume against a concurrent reader/shutdown.
|
||||
guard self._isRunning() else {
|
||||
self._dropPending(id, resumingWith: SourceKitLSPError.notRunning)
|
||||
return
|
||||
}
|
||||
self._send(framed)
|
||||
}
|
||||
}
|
||||
group.addTask {
|
||||
try await Task.sleep(nanoseconds: UInt64(timeoutSeconds * nanosecondsPerSecond))
|
||||
throw SourceKitLSPError.timedOut(method: method)
|
||||
}
|
||||
defer { group.cancelAll() }
|
||||
do {
|
||||
guard let first: Data = try await group.next() else {
|
||||
throw SourceKitLSPError.timedOut(method: method)
|
||||
}
|
||||
return first
|
||||
} catch {
|
||||
// On timeout / failure, resume and drop the still-pending request
|
||||
// continuation so its child task completes (cancelAll() alone does
|
||||
// not wake a suspended continuation) and the group can return.
|
||||
_dropPending(id, resumingWith: error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func notify(method: String, params: [String: Any]) {
|
||||
if let framed: Data = _frame(id: nil, method: method, params: params) {
|
||||
_send(framed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a `Content-Length`-framed JSON-RPC message. Pure; no shared state.
|
||||
private func _frame(id: Int?, method: String, params: [String: Any]) -> Data? {
|
||||
var payload: [String: Any] = ["jsonrpc": "2.0", "method": method, "params": params]
|
||||
if let id: Int = id { payload["id"] = id }
|
||||
guard let body: Data = try? JSONSerialization.data(withJSONObject: payload) else { return nil }
|
||||
var framed: Data = Data("Content-Length: \(body.count)\r\n\r\n".utf8)
|
||||
framed.append(body)
|
||||
return framed
|
||||
}
|
||||
|
||||
/// Write a pre-framed message to the server's stdin, unless shut down.
|
||||
private func _send(_ framed: Data) {
|
||||
_lock.lock()
|
||||
let running: Bool = _running
|
||||
_lock.unlock()
|
||||
guard running else { return }
|
||||
_stdin.fileHandleForWriting.write(framed)
|
||||
}
|
||||
|
||||
// MARK: - Reader
|
||||
|
||||
private func _startReader() {
|
||||
let handle: FileHandle = _stdout.fileHandleForReading
|
||||
let thread: Thread = Thread { [weak self] in
|
||||
while true {
|
||||
guard let self: SourceKitLSPClient else { return }
|
||||
self._lock.lock(); let running: Bool = self._running; self._lock.unlock()
|
||||
guard running else { return }
|
||||
let chunk: Data = handle.availableData
|
||||
if chunk.isEmpty {
|
||||
// EOF — the server exited. Mark not-running so later `_send`s
|
||||
// don't write to a dead pipe (EPIPE/SIGPIPE), and fail any
|
||||
// in-flight requests instead of letting them hang to timeout.
|
||||
self._setRunning(false)
|
||||
self._failAllPending(with: SourceKitLSPError.notRunning)
|
||||
return
|
||||
}
|
||||
self._lock.lock()
|
||||
self._readBuffer.append(chunk)
|
||||
let bodies: [Data] = self._drainMessagesLocked()
|
||||
self._lock.unlock()
|
||||
for body: Data in bodies {
|
||||
self._dispatch(body)
|
||||
}
|
||||
}
|
||||
}
|
||||
thread.name = "lyrebird.sourcekit-lsp.reader"
|
||||
thread.start()
|
||||
}
|
||||
|
||||
/// Slice out as many complete `Content-Length`-framed message bodies as are
|
||||
/// buffered, returning each raw JSON body. Caller holds `_lock`.
|
||||
private func _drainMessagesLocked() -> [Data] {
|
||||
var out: [Data] = []
|
||||
let headerTerminator: Data = Data("\r\n\r\n".utf8)
|
||||
while true {
|
||||
guard let headerEnd: Range<Data.Index> = _readBuffer.range(of: headerTerminator) else { break }
|
||||
let header: String = String(data: _readBuffer[_readBuffer.startIndex..<headerEnd.lowerBound],
|
||||
encoding: .utf8) ?? ""
|
||||
var contentLength: Int = 0
|
||||
for line: Substring in header.split(separator: "\r\n") {
|
||||
let parts: [Substring] = line.split(separator: ":", maxSplits: 1)
|
||||
if parts.count == 2, parts[0].trimmingCharacters(in: .whitespaces) == "Content-Length" {
|
||||
contentLength = Int(parts[1].trimmingCharacters(in: .whitespaces)) ?? 0
|
||||
}
|
||||
}
|
||||
let bodyStart: Data.Index = headerEnd.upperBound
|
||||
let available: Int = _readBuffer.distance(from: bodyStart, to: _readBuffer.endIndex)
|
||||
guard available >= contentLength else { break } // wait for more bytes
|
||||
let bodyEnd: Data.Index = _readBuffer.index(bodyStart, offsetBy: contentLength)
|
||||
out.append(Data(_readBuffer[bodyStart..<bodyEnd]))
|
||||
_readBuffer.removeSubrange(_readBuffer.startIndex..<bodyEnd)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private func _dispatch(_ body: Data) {
|
||||
guard let message: [String: Any] = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any]
|
||||
else { return }
|
||||
// Only responses (carrying our request id) are of interest; server
|
||||
// notifications (diagnostics, logging) and server→client requests are
|
||||
// ignored. sourcekit-lsp tolerates unanswered server requests here.
|
||||
guard let id: Int = message["id"] as? Int else { return }
|
||||
_lock.lock()
|
||||
let cont: CheckedContinuation<Data, Error>? = _pending.removeValue(forKey: id)
|
||||
_lock.unlock()
|
||||
guard let cont: CheckedContinuation<Data, Error> = cont else { return }
|
||||
|
||||
if let error: [String: Any] = message["error"] as? [String: Any] {
|
||||
let code: Int = error["code"] as? Int ?? 0
|
||||
let msg: String = error["message"] as? String ?? "unknown"
|
||||
cont.resume(throwing: SourceKitLSPError.serverError(code: code, message: msg))
|
||||
return
|
||||
}
|
||||
// Hand the raw body back; the caller parses `result` for its own shape.
|
||||
cont.resume(returning: body)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user