// SnippetCompletionService.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT // LyrebirdLiveCompile // // Bridges the live-coding editor to `sourcekit-lsp` (via ``SourceKitLSPClient``) // so the user gets real Swift code completion — the same symbols the snippet // would see at compile time (`context`, `LyrebirdSynth` generators, …). // // It maintains a small on-disk workspace: the snippet is written WRAPPED in the // same `SnippetHarness` preamble the compiler uses, next to a // `compile_commands.json` carrying the module-resolution flags derived from the // host `LiveSession`. sourcekit-lsp's compilation-database build system reads // that file, which is what lets `import LyrebirdSynth` and the injected // `context: SnippetContext` resolve for an otherwise free-standing file. // // macOS only. #if os(macOS) import Foundation /// Provides code completion for a live-coding editor buffer. public actor SnippetCompletionService { private let _client: SourceKitLSPClient private let _session: LiveSession private let _workspace: URL private let _fileURL: URL private let _fileURI: String // Version counter for `didChange`, and the offset (from the last wrap) that // maps a user-body line to its line in the wrapped document. private var _version: Int = 1 private var _userBodyLineOffset: Int = 1 private var _started: Bool = false /// - Parameters: /// - session: Host session whose `importPaths` / `librarySearchPaths` / /// `libraries` are reused verbatim, so completion sees exactly the /// modules the real compile links. /// - client: LSP client to drive (injectable for tests). public init( session: LiveSession, client: SourceKitLSPClient = SourceKitLSPClient() ) { self._client = client self._session = session // URL computation only — no filesystem or subprocess I/O here, so the // synchronous init never blocks its caller (the @MainActor model). self._workspace = FileManager.default.temporaryDirectory .appendingPathComponent("lyrebird-completion-" + UUID().uuidString, isDirectory: true) self._fileURL = _workspace.appendingPathComponent("snippet.swift") self._fileURI = "file://" + _fileURL.path } /// Create the workspace directory, a seed snippet file, and the /// `compile_commands.json` describing how to compile it. Runs on the actor /// executor (off the main thread) — it shells out to `xcrun` for the SDK /// path, which must not block the UI. private func _writeWorkspace() { try? FileManager.default.createDirectory(at: _workspace, withIntermediateDirectories: true) let seed: WrappedSnippet = SnippetHarness.wrap(userBody: "\n") try? seed.source.write(to: _fileURL, atomically: true, encoding: .utf8) let arguments: [String] = SnippetCompletionService.compileArguments( session: _session, file: _fileURL.path) let entry: [String: Any] = [ "directory": _workspace.path, "file": _fileURL.path, "arguments": arguments ] if let data: Data = try? JSONSerialization.data(withJSONObject: [entry], options: [.prettyPrinted]) { try? data.write(to: _workspace.appendingPathComponent("compile_commands.json")) } } /// Build the swiftc invocation for the compilation database: the `-I` /// module paths, C-target module maps, and link flags from `session`, plus /// the explicit `-sdk` / `-target` sourcekit-lsp needs for a free-standing /// file (swiftc infers those during a normal build, but the LSP does not). static func compileArguments(session: LiveSession, file: String) -> [String] { var args: [String] = ["swiftc", file] for path: URL in session.importPaths { args += ["-I", path.path] } for url: URL in LiveSession.discoverClangModuleMaps(in: session.importPaths) { args += ["-Xcc", "-fmodule-map-file=\(url.path)"] } for url: URL in LiveSession.discoverSPMModuleMaps(in: session.importPaths) { args += ["-Xcc", "-fmodule-map-file=\(url.path)"] } for path: URL in session.librarySearchPaths { args += ["-L", path.path] } for lib: String in session.libraries { args += ["-l\(lib)"] } if let sdk: String = sdkPath() { args += ["-sdk", sdk] } args += ["-target", targetTriple()] return args } private static func sdkPath() -> String? { let p: Process = Process() p.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") p.arguments = ["--show-sdk-path", "--sdk", "macosx"] let out: Pipe = Pipe() p.standardOutput = out p.standardError = Pipe() try? p.run() p.waitUntilExit() let data: Data = out.fileHandleForReading.readDataToEndOfFile() let path: String? = String(data: data, encoding: .utf8)? .trimmingCharacters(in: .whitespacesAndNewlines) return (path?.isEmpty == false) ? path : nil } /// Minimum-deployment target triple. Arch matches the running process; /// the OS floor matches the package's `macOS 15` minimum. private static func targetTriple() -> String { #if arch(arm64) let arch: String = "arm64" #else let arch: String = "x86_64" #endif return "\(arch)-apple-macosx15.0" } /// Launch sourcekit-lsp and open the (empty) document. Call once before the /// first ``completions(userBody:line:character:)``. Idempotent. public func start() async throws { guard !_started else { return } // Build the workspace (SDK lookup + file writes) here, on the actor // executor, so the blocking `xcrun` call never lands on the main thread. _writeWorkspace() try await _client.start(rootURI: "file://" + _workspace.path) let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: "\n") _userBodyLineOffset = wrapped.userBodyLineOffset _client.didOpen(uri: _fileURI, text: wrapped.source, version: _version) _started = true } /// Request completions for `userBody` at the user-space `line` / `character` /// (both zero-based, in the user's own text — not the wrapped document). /// /// The body is re-synced to the server first, then the cursor is mapped /// through the harness offset into the wrapped document. public func completions(userBody: String, line: Int, character: Int) async throws -> [LSPCompletionItem] { if !_started { try await start() } let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: userBody) _userBodyLineOffset = wrapped.userBodyLineOffset _version += 1 _client.didChange(uri: _fileURI, text: wrapped.source, version: _version) // User line 0 sits at wrapped line `userBodyLineOffset - 1` (0-based); // the column is unchanged (the preamble adds only whole lines). let wrappedLine: Int = line + (_userBodyLineOffset - 1) return try await _client.completion(uri: _fileURI, line: wrappedLine, character: character) } /// Shut down the server and remove the workspace. Safe to call more than once. public func stop() { shutdownSynchronously() _started = false } /// Synchronous teardown usable from `deinit` and non-async contexts (a test /// `defer`): terminate the LSP client and delete the temp workspace. Touches /// only `let` members, so it is safe to run `nonisolated`. Idempotent. public nonisolated func shutdownSynchronously() { _client.shutdown() try? FileManager.default.removeItem(at: _workspace) } deinit { shutdownSynchronously() } } #endif