Files
Lyrebird/LiveCompile/Sources/LyrebirdLiveCompile/SnippetCompletionService.swift
T
josh ec72bd3a4c v2.4.1 release: scratchpad polish + demo cleanup
Maintenance release, no framework API changes.

Scratchpad: Kill All Sound (⌘K) rename, mode-switch desync fix,
code-completion prefix filtering restored (⌃Space Show Completions).
Demos: GUIDemo voices + CLI EventPattern BlipVoice moved into
Synthesizers/, EventPattern demo split into makeLead/makeBass, GUIDemo
doc drift fixed (conductor default). LyrebirdScratch gains a SwiftPM
package so the workspace shows it like GUIDemo (.xcodeproj kept for
distribution). Linux live-coding scratchpad documented.
2026-12-03 11:39:40 -08:00

279 lines
13 KiB
Swift

// 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/Linux only.
#if os(macOS) || os(Linux)
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)"]
}
#if os(Linux)
// CALSA's system-library module map is source-only (see LiveSession);
// completion needs it too, or `import LyrebirdSynth` fails to resolve.
for url: URL in LiveSession.discoverSourceSystemModuleMaps(in: session.importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
#endif
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? {
// Linux needs no `-sdk`, and `xcrun` does not exist there. Crucially,
// guard the spawn: on Linux, `Process.run()` throws when the launch path
// is missing, and a subsequent `waitUntilExit()` on a process that never
// started BLOCKS FOREVER (it is a no-op on macOS) — the completion hang.
// The macOS xcrun helpers in LiveCompiler avoid this by checking
// `isExecutableFile(atPath:)` first; do the same here.
let xcrunPath: String = "/usr/bin/xcrun"
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
let p: Process = Process()
p.executableURL = URL(fileURLWithPath: xcrunPath)
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 os(macOS)
#if arch(arm64)
return "arm64-apple-macosx15.0"
#else
return "x86_64-apple-macosx15.0"
#endif
#else
// Linux GNU triple; the Swift/LLVM spelling of arm64 is `aarch64`.
#if arch(arm64)
return "aarch64-unknown-linux-gnu"
#else
return "x86_64-unknown-linux-gnu"
#endif
#endif
}
/// 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)
let items: [LSPCompletionItem] = try await _client.completion(
uri: _fileURI, line: wrappedLine, character: character)
// sourcekit-lsp returns a bare-identifier completion as the *whole*
// visible-symbol universe (hundreds of SDK/stdlib globals), unsorted and
// unfiltered — LSP expects the client to narrow it by the typed prefix.
// Member completion (after `.`) is already server-scoped, so its prefix
// is empty and this leaves it untouched. Without this, typing `OscS` and
// asking for completion floods the window with Darwin/IOKit globals and
// buries (or truncates away) the real `Osc*` types.
let prefix: String = SnippetCompletionService.partialWord(
in: userBody, line: line, character: character)
return SnippetCompletionService.filterAndRank(items, prefix: prefix)
}
/// The identifier fragment immediately before the caret — letters, digits and
/// underscores — on the user-body `line` up to `character` (zero-based,
/// UTF-16). Empty when the character before the caret is not an identifier
/// character (e.g. a `.` member completion, or start of line).
static func partialWord(in userBody: String, line: Int, character: Int) -> String {
let lines: [Substring] = userBody.split(separator: "\n", omittingEmptySubsequences: false)
guard line >= 0, line < lines.count else { return "" }
let units: [UInt16] = Array(lines[line].utf16)
let end: Int = min(character, units.count)
var start: Int = end
while start > 0, isIdentifierUTF16(units[start - 1]) {
start -= 1
}
guard start < end else { return "" }
return String(decoding: units[start..<end], as: UTF16.self)
}
/// ASCII letter / digit / underscore — the same identifier class the editor's
/// `rangeForUserCompletion` uses to pick the word the completion replaces.
private static func isIdentifierUTF16(_ u: UInt16) -> Bool {
let underscore: UInt16 = 95
let zero: UInt16 = 48, nine: UInt16 = 57
let upperA: UInt16 = 65, upperZ: UInt16 = 90
let lowerA: UInt16 = 97, lowerZ: UInt16 = 122
return u == underscore
|| (u >= zero && u <= nine)
|| (u >= upperA && u <= upperZ)
|| (u >= lowerA && u <= lowerZ)
}
/// Narrow `items` to those matching `prefix` (case-insensitive, by `label`)
/// and order best-first. An empty `prefix` keeps every item (member
/// completion is already scoped by the server) and only sorts it. With a
/// prefix, exact case-insensitive prefix matches come first, then anything
/// that merely contains the fragment (so a mistyped case or an internal match
/// still surfaces), each group ordered by the server's `sortText` then label.
static func filterAndRank(_ items: [LSPCompletionItem], prefix: String) -> [LSPCompletionItem] {
func ordered(_ group: [LSPCompletionItem]) -> [LSPCompletionItem] {
group.sorted { a, b in
let ka: String = a.sortText ?? a.label
let kb: String = b.sortText ?? b.label
if ka != kb { return ka < kb }
return a.label < b.label
}
}
guard !prefix.isEmpty else { return ordered(items) }
let needle: String = prefix.lowercased()
var prefixed: [LSPCompletionItem] = []
var contained: [LSPCompletionItem] = []
for item: LSPCompletionItem in items {
let hay: String = item.label.lowercased()
if hay.hasPrefix(needle) {
prefixed.append(item)
} else if hay.contains(needle) {
contained.append(item)
}
}
return ordered(prefixed) + ordered(contained)
}
/// 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