v1.4.0 release: live-coding scratch editor, interpreted Graph DSL, ClosureSynthesizer + SampleLoop
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
// GraphDSLDiagnosticMapper.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// Turns a thrown `DSLParseError` / `DSLBuildError` into the same `[Diagnostic]`
|
||||
// the swiftc path produces, so `LyrebirdScratchView`'s gutter renders DSL
|
||||
// failures with no special-casing. Parse errors carry a source span → a real
|
||||
// (line, column); build errors carry no span → `line: nil` with the message
|
||||
// alone.
|
||||
|
||||
#if os(macOS)
|
||||
import LyrebirdGraphDSLEmbedded
|
||||
|
||||
/// Maps interpreted-graph-DSL errors to editor diagnostics.
|
||||
enum GraphDSLDiagnosticMapper {
|
||||
|
||||
/// Convert `error` (a `DSLParseError`, a `DSLBuildError`, or anything else)
|
||||
/// into one or more ``Diagnostic``s, resolving parse-error spans against
|
||||
/// `source` for a 1-based line/column.
|
||||
static func diagnostics(for error: Error, source: String) -> [Diagnostic] {
|
||||
if let parse: DSLParseError = error as? DSLParseError {
|
||||
let (line, column): (Int, Int) = lineColumn(of: parse.span.start, in: source)
|
||||
return [Diagnostic(
|
||||
line: line,
|
||||
column: column,
|
||||
severity: .error,
|
||||
message: parse.description,
|
||||
rawLine: line
|
||||
)]
|
||||
}
|
||||
if let build: DSLBuildError = error as? DSLBuildError {
|
||||
// Build errors carry no span; report at file scope.
|
||||
return [Diagnostic(
|
||||
line: nil,
|
||||
column: 0,
|
||||
severity: .error,
|
||||
message: build.description,
|
||||
rawLine: 0
|
||||
)]
|
||||
}
|
||||
return [Diagnostic(
|
||||
line: nil,
|
||||
column: 0,
|
||||
severity: .error,
|
||||
message: "\(error)",
|
||||
rawLine: 0
|
||||
)]
|
||||
}
|
||||
|
||||
/// Map a character `offset` into `source` to a 1-based (line, column).
|
||||
/// An offset past the end clamps to the final position.
|
||||
private static func lineColumn(of offset: Int, in source: String) -> (line: Int, column: Int) {
|
||||
var line: Int = 1
|
||||
var column: Int = 1
|
||||
var seen: Int = 0
|
||||
for character: Character in source {
|
||||
if seen >= offset { break }
|
||||
if character == "\n" {
|
||||
line += 1
|
||||
column = 1
|
||||
} else {
|
||||
column += 1
|
||||
}
|
||||
seen += 1
|
||||
}
|
||||
return (line, column)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,42 @@
|
||||
// LSPCompletionItem.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// One parsed code-completion candidate from `sourcekit-lsp`. macOS only.
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// One code-completion candidate returned by sourcekit-lsp.
|
||||
public struct LSPCompletionItem: Sendable, Equatable {
|
||||
/// Display label (e.g. `Audio`).
|
||||
public let label: String
|
||||
/// Type / signature detail (e.g. `OscSin.Audio`), if provided.
|
||||
public let detail: String?
|
||||
/// Text to insert when chosen. Falls back to `label` when the server gives
|
||||
/// no explicit insert text.
|
||||
public let insertText: String
|
||||
/// LSP `CompletionItemKind` raw value, or `nil`. Lets the UI pick an icon.
|
||||
public let kind: Int?
|
||||
/// Server-provided sort key; the UI orders by this then by `label`.
|
||||
public let sortText: String?
|
||||
|
||||
public init(
|
||||
label: String,
|
||||
detail: String?,
|
||||
insertText: String,
|
||||
kind: Int?,
|
||||
sortText: String?
|
||||
) {
|
||||
self.label = label
|
||||
self.detail = detail
|
||||
self.insertText = insertText
|
||||
self.kind = kind
|
||||
self.sortText = sortText
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -190,10 +190,11 @@ public enum LiveCompiler {
|
||||
process.arguments = arguments
|
||||
let stderrPipe: Pipe = Pipe()
|
||||
process.standardError = stderrPipe
|
||||
// stdout discarded — swiftc emits no useful output in -emit-library mode.
|
||||
// Use FileHandle.nullDevice (not Pipe()) so the OS drops the bytes itself;
|
||||
// an undrained Pipe deadlocks against the blocking stderr read below if
|
||||
// swiftc ever writes more than the pipe buffer (~64 KB) to stdout.
|
||||
// stdout discarded — swiftc emits no useful output in the modes used
|
||||
// here (-emit-library and -typecheck). Use FileHandle.nullDevice (not
|
||||
// Pipe()) so the OS drops the bytes itself; an undrained Pipe deadlocks
|
||||
// against the blocking stderr read below if swiftc ever writes more than
|
||||
// the pipe buffer (~64 KB) to stdout.
|
||||
process.standardOutput = FileHandle.nullDevice
|
||||
do {
|
||||
try process.run()
|
||||
@@ -205,6 +206,53 @@ public enum LiveCompiler {
|
||||
let stderrString: String = String(data: stderrData, encoding: .utf8) ?? ""
|
||||
return SwiftcResult(exitCode: process.terminationStatus, stderr: stderrString)
|
||||
}
|
||||
|
||||
// MARK: - Module-cache prewarm
|
||||
|
||||
/// Build the Clang/Swift module cache (the precompiled `.pcm` for the large
|
||||
/// `LyrebirdSynth` interface and its dependencies) by **type-checking** a
|
||||
/// trivial source that imports the same modules a real snippet does.
|
||||
///
|
||||
/// The cold cache build costs ~2–3 s and otherwise lands on the user's first
|
||||
/// ⌘↩; running this once at session start (off-main) moves that cost into the
|
||||
/// background, so the first real ``compile(source:extraSwiftcArgs:)`` hits a
|
||||
/// warm cache (~0.1 s). `-typecheck` is enough — the `.pcm`s are produced
|
||||
/// during import resolution, before codegen/link — and avoids emitting or
|
||||
/// `dlopen`ing a dylib.
|
||||
///
|
||||
/// - Parameter extraSwiftcArgs: The module-resolution flags (`-I`,
|
||||
/// `-Xcc -fmodule-map-file=…`) that point at the same modules the real
|
||||
/// compile uses, so both warm the same (default) module cache.
|
||||
/// `LiveSession` supplies these via its module-resolution args.
|
||||
/// - Throws: `LiveCompileError` for a missing toolchain, IO failure, or a
|
||||
/// non-zero type-check exit.
|
||||
public static func prewarm(extraSwiftcArgs: [String]) throws {
|
||||
let swiftc: String = try findSwiftc()
|
||||
let id: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
|
||||
let workDir: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LyrebirdLiveCompile-prewarm-\(id)", isDirectory: true)
|
||||
let sourcePath: String = workDir.appendingPathComponent("Prewarm.swift").path
|
||||
let source: String = "import LyrebirdSynth\nimport LyrebirdLiveCompile\n"
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true)
|
||||
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
|
||||
} catch {
|
||||
throw LiveCompileError.ioFailed(underlying: "\(error)")
|
||||
}
|
||||
defer { try? FileManager.default.removeItem(at: workDir) }
|
||||
|
||||
var arguments: [String] = ["-typecheck", "-module-name", "LBPrewarm_\(id)"]
|
||||
if let sdkPath: String = sdkPathViaXcrun() {
|
||||
arguments.append(contentsOf: ["-sdk", sdkPath])
|
||||
}
|
||||
arguments += extraSwiftcArgs
|
||||
arguments.append(sourcePath)
|
||||
|
||||
let result: LiveCompiler.SwiftcResult = try runSwiftc(executable: swiftc, arguments: arguments)
|
||||
guard result.exitCode == 0 else {
|
||||
throw LiveCompileError.compileFailed(exitCode: result.exitCode, stderr: result.stderr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -28,9 +28,10 @@ import LyrebirdSynth
|
||||
/// Swift 6 requires it to be `Sendable`. The conformance is sound by construction:
|
||||
///
|
||||
/// - `engine` and all `-I` / `-L` / `-l` / `rpath` configuration are immutable `let`.
|
||||
/// - The only mutable graph state — `trackedSynths` and `loadedSnippets` — is accessed
|
||||
/// exclusively under `trackingLock` (`track`, `clearTracked`, `trackedSynthCount`,
|
||||
/// `runEntry`).
|
||||
/// - The mutable graph state — `trackedSynths`, `loadedSnippets`, and the named-slot map
|
||||
/// `slottedSynths` — is accessed exclusively under `trackingLock` (`track`,
|
||||
/// `clearTracked`, `trackedSynthCount`, `runEntry`, `assignSlot`, `clearSlot`,
|
||||
/// `clearSlots`, `slotCount`, `slotNames`).
|
||||
/// - `reportedSampleRate` / `lastSnippetMessage` are test-only side channels (`@testable`),
|
||||
/// written by the single in-flight snippet entry under the documented
|
||||
/// one-invocation-at-a-time precondition (see `compileAndRunAsync`) and read by tests
|
||||
@@ -53,6 +54,12 @@ public final class LiveSession: @unchecked Sendable {
|
||||
/// runtime without `DYLD_LIBRARY_PATH` ceremony.
|
||||
public let rpaths: [URL]
|
||||
|
||||
// Prewarm lifecycle — guarded by `trackingLock`. `_prewarmed` flips true
|
||||
// when a prewarm completes; `_prewarming` guards a call in flight so
|
||||
// repeat calls (e.g. a view re-appearing) don't spawn a second swiftc.
|
||||
private var _prewarmed: Bool = false
|
||||
private var _prewarming: Bool = false
|
||||
|
||||
/// Side-channel for snippet `context.reportSampleRate(_:)` calls. Tests read
|
||||
/// via `@testable import`; not part of the public API.
|
||||
internal var reportedSampleRate: Double?
|
||||
@@ -66,6 +73,33 @@ public final class LiveSession: @unchecked Sendable {
|
||||
private var trackedSynths: [any Synthesizer] = []
|
||||
private var loadedSnippets: [CompiledSnippet] = []
|
||||
|
||||
// A named-slot occupant plus the sample time its add was scheduled at.
|
||||
// The add time lets a later teardown schedule the occupant's removal no
|
||||
// earlier than its own add, so a still-pending *scheduled* voice (quantized
|
||||
// swap not yet fired) is never orphaned by an immediate clear or an earlier
|
||||
// re-swap. See `removeSlotOccupant`.
|
||||
private struct SlotEntry {
|
||||
let synth: any Synthesizer
|
||||
let addTime: SampleTime
|
||||
}
|
||||
|
||||
// Named slots — `Pdef`-style persistent voices, keyed by name. Kept
|
||||
// separate from the anonymous `trackedSynths` so they SURVIVE a
|
||||
// non-additive re-evaluation: re-running a `context.play(slot: "bass") { … }`
|
||||
// definition replaces just that voice in place (via `assignSlot`) instead of
|
||||
// being cleared with the anonymous synths. Guarded by `trackingLock`.
|
||||
private var slottedSynths: [String: SlotEntry] = [:]
|
||||
|
||||
// Swap-quantization config + pending-swap signal — all guarded by
|
||||
// `trackingLock`. When `_swapClock` is set and `_swapQuantize` is not
|
||||
// `.immediate`, a slot swap schedules the new voice's add and the old
|
||||
// voice's removal at the next musical boundary instead of taking effect at
|
||||
// once (latency masking). `_pendingSwapBeat` is the latest target beat of a
|
||||
// not-yet-fired scheduled swap, surfaced via ``pendingSwapBeat``.
|
||||
private var _swapClock: LyrebirdClock?
|
||||
private var _swapQuantize: SwapQuantize = .immediate
|
||||
private var _pendingSwapBeat: Double?
|
||||
|
||||
public init(
|
||||
engine: SynthesisEngine,
|
||||
importPaths: [URL] = LiveSession.defaultImportPaths(),
|
||||
@@ -208,9 +242,314 @@ public final class LiveSession: @unchecked Sendable {
|
||||
trackedSynths.append(synth)
|
||||
}
|
||||
|
||||
// MARK: - Named slots
|
||||
|
||||
/// Number of named slots currently holding a synth. Thread-safe.
|
||||
public var slotCount: Int {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
return slottedSynths.count
|
||||
}
|
||||
|
||||
/// Names of the currently-populated slots. Thread-safe.
|
||||
public var slotNames: [String] {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
return Array(slottedSynths.keys)
|
||||
}
|
||||
|
||||
/// Install `synth` into the named `slot` immediately, replacing any synth
|
||||
/// previously held there.
|
||||
///
|
||||
/// Internal hook for the immediate path of ``swapSlot(_:synth:)``. **Call
|
||||
/// after `engine.add(synth)` has succeeded** — the new voice is live before
|
||||
/// the old one is torn down, so a slot replacement is a brief overlap rather
|
||||
/// than a silent gap. The previous occupant is removed via
|
||||
/// ``removeSlotOccupant(_:desired:)`` (scheduled no earlier than its own
|
||||
/// add, so a still-pending scheduled voice is never orphaned). Thread-safe;
|
||||
/// `engine.remove` runs outside the lock.
|
||||
func assignSlot(_ name: String, synth: any Synthesizer) {
|
||||
let now: SampleTime = engine.currentTime
|
||||
let previous: SlotEntry?
|
||||
do {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
previous = slottedSynths[name]
|
||||
slottedSynths[name] = SlotEntry(synth: synth, addTime: now)
|
||||
}
|
||||
if let previous: SlotEntry = previous {
|
||||
removeSlotOccupant(previous, desired: now)
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove every named-slot synth from the engine and clear all slots.
|
||||
/// Anonymous tracked synths are untouched — pair with ``clearTracked()``
|
||||
/// for a full reset.
|
||||
public func clearSlots() {
|
||||
let now: SampleTime = engine.currentTime
|
||||
let snapshot: [SlotEntry]
|
||||
do {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
snapshot = Array(slottedSynths.values)
|
||||
slottedSynths.removeAll()
|
||||
}
|
||||
for entry: SlotEntry in snapshot {
|
||||
removeSlotOccupant(entry, desired: now)
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the synth in the named `slot` (if any) from the engine and clear
|
||||
/// the slot. No-op when the slot is empty. Returns `true` if a synth was
|
||||
/// removed.
|
||||
@discardableResult
|
||||
public func clearSlot(_ name: String) -> Bool {
|
||||
let now: SampleTime = engine.currentTime
|
||||
let previous: SlotEntry?
|
||||
do {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
previous = slottedSynths.removeValue(forKey: name)
|
||||
}
|
||||
if let previous: SlotEntry = previous {
|
||||
removeSlotOccupant(previous, desired: now)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// Remove a slot occupant, scheduling the removal no earlier than the
|
||||
/// occupant's own add time (`max(desired, addTime)`) so a still-pending
|
||||
/// scheduled add is never orphaned. `desired` is the caller's intended
|
||||
/// removal time — a swap boundary, or the current time for an immediate
|
||||
/// teardown. Because the occupant's add is always enqueued before this
|
||||
/// removal and the engine's per-block event sort is stable at equal times,
|
||||
/// an add and removal landing on the same sample apply add-then-removal, so
|
||||
/// the voice is always cleaned up. Runs outside `trackingLock`.
|
||||
@discardableResult
|
||||
private func removeSlotOccupant(_ entry: SlotEntry, desired: SampleTime) -> Bool {
|
||||
let removeAt: SampleTime = max(desired, entry.addTime)
|
||||
return engine.remove(entry.synth, at: removeAt)
|
||||
}
|
||||
|
||||
// MARK: - Session reset + snippet accounting
|
||||
|
||||
/// Panic / clear-everything valve: remove every snippet-played synth — both
|
||||
/// the anonymous tracked ones (``clearTracked()``) and every named slot
|
||||
/// (``clearSlots()``) — from the engine, and clear the pending-swap signal.
|
||||
/// Stops all snippet audio and gives a clean slate without tearing down the
|
||||
/// engine.
|
||||
///
|
||||
/// It does **not** reclaim the compiled snippet dylibs — see
|
||||
/// ``loadedSnippetCount``. Reclaiming that memory would require `dlclose`,
|
||||
/// which is unsafe for these Swift dylibs: `dlopen` registers their type
|
||||
/// metadata and protocol-conformance records into process-global runtime
|
||||
/// caches that `dlclose` does not deregister, so unmapping the dylib leaves
|
||||
/// those caches dangling. Mapped snippet memory is therefore reclaimed only
|
||||
/// by restarting the process. (The interpreted-graph path on the roadmap
|
||||
/// avoids dylibs entirely and is the structural fix.)
|
||||
///
|
||||
/// - Precondition: same one-invocation-at-a-time caveat as
|
||||
/// ``compileAndRunAsync(_:additive:)``. Calling this concurrently with an
|
||||
/// in-flight compile can interleave the internal `clearTracked()` with a
|
||||
/// not-yet-completed `runEntry`, missing a just-added synth (which then
|
||||
/// leaks until process restart). The built-in ``LyrebirdScratchModel``
|
||||
/// serialises through its `isCompiling` flag. This is also not a single
|
||||
/// atomic critical section — the synth removal and the pending-swap clear
|
||||
/// take `trackingLock` separately — which is acceptable for a panic valve.
|
||||
public func resetAll() {
|
||||
clearTracked()
|
||||
clearSlots()
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
_pendingSwapBeat = nil
|
||||
}
|
||||
|
||||
/// Number of compiled snippet dylibs currently mapped into the process.
|
||||
///
|
||||
/// Each ⌘↩ compiles a new dylib that stays mapped for the process's lifetime
|
||||
/// (unloading is unsafe — see ``resetAll()``), so within a session this only
|
||||
/// grows. Exposed for host observability, e.g. a "restart to reclaim memory"
|
||||
/// nudge after a very long session. Thread-safe.
|
||||
public var loadedSnippetCount: Int {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
return loadedSnippets.count
|
||||
}
|
||||
|
||||
// MARK: - Swap quantization (on-beat latency masking)
|
||||
|
||||
/// Clock that slot swaps quantize against. When `nil` (default), swaps are
|
||||
/// always immediate regardless of ``swapQuantize``. Setting it clears any
|
||||
/// pending-swap signal (``pendingSwapBeat``). Thread-safe.
|
||||
public var swapClock: LyrebirdClock? {
|
||||
get { trackingLock.lock(); defer { trackingLock.unlock() }; return _swapClock }
|
||||
set {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
_swapClock = newValue
|
||||
_pendingSwapBeat = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// When a named-slot swap becomes audible. Defaults to ``SwapQuantize/immediate``.
|
||||
/// Only takes effect when ``swapClock`` is also set. Setting it clears any
|
||||
/// pending-swap signal (``pendingSwapBeat``). Thread-safe.
|
||||
public var swapQuantize: SwapQuantize {
|
||||
get { trackingLock.lock(); defer { trackingLock.unlock() }; return _swapQuantize }
|
||||
set {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
_swapQuantize = newValue
|
||||
_pendingSwapBeat = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Target beat of the latest scheduled-but-not-yet-fired slot swap, or `nil`
|
||||
/// when none is pending (immediate mode, the boundary has already passed, or
|
||||
/// the swap config changed). Self-clearing: returns `nil` once the clock
|
||||
/// reaches the target beat. Drives the editor's `.queued` readiness state.
|
||||
///
|
||||
/// When several slots have swaps pending at different beats this reports the
|
||||
/// latest of them — treat it as "some swap is still outstanding", not "this
|
||||
/// specific run's swap". Thread-safe, but not atomic against a concurrent
|
||||
/// swap: the `_swapClock` snapshot and the `clock.currentBeat` read happen in
|
||||
/// separate critical sections, so a swap scheduled between them may not yet
|
||||
/// be reflected. Fine for the main-actor UI that consumes it.
|
||||
public var pendingSwapBeat: Double? {
|
||||
let target: Double?
|
||||
let clock: LyrebirdClock?
|
||||
do {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
target = _pendingSwapBeat
|
||||
clock = _swapClock
|
||||
}
|
||||
guard let target: Double = target, let clock: LyrebirdClock = clock else { return nil }
|
||||
return clock.currentBeat < target ? target : nil
|
||||
}
|
||||
|
||||
/// Install `synth` into the named `slot`, quantizing the swap per
|
||||
/// ``swapQuantize`` / ``swapClock``.
|
||||
///
|
||||
/// Immediate mode (`.immediate` or no clock): adds `synth` now and removes
|
||||
/// the previous slot synth now (via ``assignSlot(_:synth:)``). Quantized
|
||||
/// mode: schedules `synth`'s add and the previous synth's removal at the same
|
||||
/// upcoming boundary sample time, so the swap is glitch-free and on-grid,
|
||||
/// and records the target beat for ``pendingSwapBeat``.
|
||||
///
|
||||
/// Backs ``SnippetContext/play(slot:_:)``. `@MainActor` because it touches
|
||||
/// the engine's node tree (`add`/`schedule`/`remove`).
|
||||
///
|
||||
/// - Throws: `EngineAddError` if the engine rejects the add/schedule; the
|
||||
/// prior slot synth is left in place on throw.
|
||||
@MainActor
|
||||
func swapSlot(_ name: String, synth: any Synthesizer) throws {
|
||||
let clock: LyrebirdClock?
|
||||
let quantize: SwapQuantize
|
||||
do {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
clock = _swapClock
|
||||
quantize = _swapQuantize
|
||||
}
|
||||
if let clock: LyrebirdClock = clock, let beat: Double = quantize.targetBeat(clock: clock) {
|
||||
let time: SampleTime = clock.sampleTime(beat: beat)
|
||||
try engine.schedule(synth, at: time)
|
||||
scheduleSlotReplace(name, newSynth: synth, at: time, targetBeat: beat)
|
||||
} else {
|
||||
try engine.add(synth)
|
||||
assignSlot(name, synth: synth)
|
||||
}
|
||||
}
|
||||
|
||||
/// Commit a scheduled slot replacement: swap the dictionary entry, schedule
|
||||
/// removal of the previous synth at the boundary `time` (no earlier than its
|
||||
/// own add), and record the pending target beat. Call only after
|
||||
/// `engine.schedule(new, at: time)` succeeded. `engine.remove` runs outside
|
||||
/// the lock; a dropped removal (pending queue full) is surfaced via
|
||||
/// `lastSnippetMessage` rather than silently leaving an overlap.
|
||||
private func scheduleSlotReplace(
|
||||
_ name: String,
|
||||
newSynth: any Synthesizer,
|
||||
at time: SampleTime,
|
||||
targetBeat: Double
|
||||
) {
|
||||
let previous: SlotEntry?
|
||||
do {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
previous = slottedSynths[name]
|
||||
slottedSynths[name] = SlotEntry(synth: newSynth, addTime: time)
|
||||
_pendingSwapBeat = max(_pendingSwapBeat ?? targetBeat, targetBeat)
|
||||
}
|
||||
if let previous: SlotEntry = previous {
|
||||
let removed: Bool = removeSlotOccupant(previous, desired: time)
|
||||
if !removed {
|
||||
lastSnippetMessage =
|
||||
"slot '\(name)': previous voice removal dropped (pending queue full) — voices may overlap"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Prewarm
|
||||
|
||||
/// `true` once a ``prewarm()`` has **succeeded** for this session. A prewarm
|
||||
/// that failed (e.g. missing toolchain) leaves this `false` so a later call
|
||||
/// retries. Thread-safe.
|
||||
public var isPrewarmed: Bool {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
return _prewarmed
|
||||
}
|
||||
|
||||
/// Warm the module cache in the background so the first real ⌘↩ is fast.
|
||||
///
|
||||
/// The cold `LyrebirdSynth` `.pcm` build costs ~2–3 s; without a prewarm it
|
||||
/// lands on the user's first compile. This kicks a detached, `.utility`
|
||||
/// type-check of a trivial import-only snippet (via
|
||||
/// ``LiveCompiler/prewarm(extraSwiftcArgs:)``) that warms swiftc's default
|
||||
/// module cache, so the first `compileAndRunAsync` hits a warm cache
|
||||
/// (~0.1 s). All the work — including the filesystem walk that builds the
|
||||
/// compiler flags — runs on the detached task, not the caller's thread.
|
||||
///
|
||||
/// Idempotent: a call while a prewarm has already succeeded or is in flight
|
||||
/// is a no-op. A *failed* prewarm leaves ``isPrewarmed`` `false` (a later
|
||||
/// call retries); the real compile then simply pays the build itself, so the
|
||||
/// failure is non-fatal and intentionally not thrown.
|
||||
///
|
||||
/// - Returns: The detached `Task`, so callers/tests can `await` its `value`.
|
||||
/// The no-op case returns an already-scheduled empty task.
|
||||
@discardableResult
|
||||
public func prewarm() -> Task<Void, Never> {
|
||||
let shouldRun: Bool
|
||||
do {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
shouldRun = !_prewarmed && !_prewarming
|
||||
if shouldRun { _prewarming = true }
|
||||
}
|
||||
guard shouldRun else { return Task {} }
|
||||
return Task.detached(priority: .utility) { [weak self] in
|
||||
guard let self: LiveSession = self else { return }
|
||||
// Off-main: build the flags (a small filesystem walk) here rather
|
||||
// than on the caller (this method is a synchronous `nonisolated`
|
||||
// call, so anything before the detached task runs on the caller).
|
||||
let args: [String] = self.makeModuleResolutionArgs()
|
||||
do {
|
||||
try LiveCompiler.prewarm(extraSwiftcArgs: args)
|
||||
self.finishPrewarm(succeeded: true)
|
||||
} catch {
|
||||
self.finishPrewarm(succeeded: false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Record a ``prewarm()`` outcome: clear the in-flight flag, and mark warmed
|
||||
/// only on success so a failed attempt can retry.
|
||||
private func finishPrewarm(succeeded: Bool) {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
_prewarming = false
|
||||
if succeeded { _prewarmed = true }
|
||||
}
|
||||
|
||||
// MARK: - swiftc flag construction
|
||||
|
||||
private func makeSwiftcArgs() -> [String] {
|
||||
/// Module-resolution flags shared by the real compile and the prewarm:
|
||||
/// `-I` import paths plus the Xcode + bare-SPM Clang module maps. No linker
|
||||
/// flags — a `-typecheck` prewarm needs none. Deliberately does **not** pin
|
||||
/// `-module-cache-path`: prewarm and the real compile both use swiftc's
|
||||
/// default cache, so the prewarm warms exactly the cache the compile reads.
|
||||
/// (Pinning a dedicated cache built fresh diverges its module metadata from
|
||||
/// the already-loaded `libLyrebirdLiveCompileDynamic`, which turns the test
|
||||
/// bundle's benign ObjC class-duplication warning into a hard cast crash.)
|
||||
private func makeModuleResolutionArgs() -> [String] {
|
||||
var args: [String] = []
|
||||
for path: URL in importPaths {
|
||||
args += ["-I", path.path]
|
||||
@@ -222,6 +561,19 @@ public final class LiveSession: @unchecked Sendable {
|
||||
for url: URL in LiveSession.discoverClangModuleMaps(in: importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
// Bare-SPM (`swift build` / `swift test`) layout: C-target module maps
|
||||
// live at `<buildDir>/<CTarget>.build/module.modulemap`, which the Xcode
|
||||
// discovery above does not cover. Surface them so a snippet's
|
||||
// `import LyrebirdSynth` can resolve the underlying `LyrebirdC` clang
|
||||
// module outside Xcode too.
|
||||
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
private func makeSwiftcArgs() -> [String] {
|
||||
var args: [String] = makeModuleResolutionArgs()
|
||||
// When a Lyrebird dylib exists in any -L path, link against it
|
||||
// (-l<name>) and bake an rpath. When no dylib is found (Xcode SPM
|
||||
// case — modules statically linked into the host app), use
|
||||
@@ -279,6 +631,33 @@ public final class LiveSession: @unchecked Sendable {
|
||||
return found
|
||||
}
|
||||
|
||||
/// Locate SPM-generated Clang module maps for a `swift build` / `swift test`
|
||||
/// layout. Each C target's map is emitted at
|
||||
/// `<buildDir>/<CTarget>.build/module.modulemap`; the umbrella header path
|
||||
/// inside is absolute, so the map alone is enough to resolve the module (no
|
||||
/// extra `-I` needed). Empty under an Xcode SPM layout, where
|
||||
/// `discoverClangModuleMaps` handles the `GeneratedModuleMaps` location
|
||||
/// instead.
|
||||
static func discoverSPMModuleMaps(in importPaths: [URL]) -> [URL] {
|
||||
var found: [URL] = []
|
||||
var visited: Set<String> = Set<String>()
|
||||
for base: URL in importPaths {
|
||||
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
|
||||
at: base,
|
||||
includingPropertiesForKeys: nil
|
||||
) else { continue }
|
||||
for entry: URL in entries where entry.pathExtension == "build" {
|
||||
let probe: URL = entry.appendingPathComponent("module.modulemap")
|
||||
if FileManager.default.fileExists(atPath: probe.path),
|
||||
!visited.contains(probe.path) {
|
||||
visited.insert(probe.path)
|
||||
found.append(probe)
|
||||
}
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
// MARK: - Build-dir discovery
|
||||
|
||||
/// Best-effort discovery of the SPM `.build/<triple>/<config>` directory
|
||||
|
||||
@@ -23,6 +23,12 @@ public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
|
||||
/// missing entry symbol, IO failure.
|
||||
case compilerError(LiveCompileError)
|
||||
|
||||
/// The interpreted graph-DSL failed to lex/parse/build or its graphs were
|
||||
/// rejected by the engine. `diagnostics` are already mapped to user-source
|
||||
/// coordinates (a parse error resolves to a line/column; a build error has
|
||||
/// `line: nil`). No swiftc is involved — this is the instant DSL path.
|
||||
case graphDSLFailed(diagnostics: [Diagnostic], underlying: Error)
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .snippetCompileFailed(let diagnostics, let underlying):
|
||||
@@ -36,6 +42,15 @@ public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
|
||||
return "snippet compile failed:\n\(summary)"
|
||||
case .compilerError(let underlying):
|
||||
return "live compile error: \(underlying)"
|
||||
case .graphDSLFailed(let diagnostics, let underlying):
|
||||
if diagnostics.isEmpty {
|
||||
return "graph DSL failed:\n\(underlying)"
|
||||
}
|
||||
let summary: String = diagnostics.map { diag -> String in
|
||||
let location: String = diag.line.map { "\($0):\(diag.column)" } ?? "?"
|
||||
return "\(location) \(diag.severity.rawValue): \(diag.message)"
|
||||
}.joined(separator: "\n")
|
||||
return "graph DSL failed:\n\(summary)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
// LiveSessionGraphDSL.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// The editor's instant, no-swiftc evaluation path. `runGraphDSL` lexes, parses,
|
||||
// and builds interpreted graph-DSL source into `ClosureSynthesizer`s and plays
|
||||
// them through the SAME tracking + named-slot machinery `compileAndRun` uses, so
|
||||
// non-additive re-evaluation, slot hot-swap, and `resetAll()` behave identically
|
||||
// across the Swift and DSL paths. The only difference is speed: a graph edit
|
||||
// re-evaluates in microseconds instead of a swiftc round-trip.
|
||||
|
||||
#if os(macOS)
|
||||
import LyrebirdSynth
|
||||
import LyrebirdGraphDSLEmbedded
|
||||
|
||||
extension LiveSession {
|
||||
|
||||
/// Evaluate interpreted graph-DSL `source` and play each statement.
|
||||
///
|
||||
/// Mirrors ``compileAndRun(_:additive:)`` but with no compiler: the source is
|
||||
/// interpreted in-process. Each statement becomes one output —
|
||||
///
|
||||
/// - an anonymous statement (`OscSin(freq: 440) * 0.1`) is added to the
|
||||
/// engine and tracked, so a later non-additive run removes it;
|
||||
/// - a named statement (`bass = OscSawtooth(freq: 55) * 0.2`) is installed into
|
||||
/// the matching named slot via ``swapSlot(_:synth:)`` — a persistent,
|
||||
/// hot-swappable voice that survives a non-additive re-evaluation and is
|
||||
/// replaced in place on the next run.
|
||||
///
|
||||
/// The whole program is lexed/parsed/built **before** any engine mutation, so
|
||||
/// a syntax or build error leaves the currently-playing graph untouched — a
|
||||
/// *malformed* edit never drops audio. Once the program is valid, playback is
|
||||
/// best-effort per statement: an engine-level rejection of one statement
|
||||
/// (e.g. `.pendingQueueFull`) is collected and surfaced but does not abort
|
||||
/// the others, matching ``SnippetContext/play(_:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - source: DSL program text (one statement per line).
|
||||
/// - additive: When `false` (default), removes every previously tracked
|
||||
/// anonymous synth before playing (named slots persist). When `true`,
|
||||
/// leaves prior synths in place.
|
||||
/// - resources: Host resource table resolving bare-identifier references
|
||||
/// (e.g. buffers). Defaults to an empty table.
|
||||
/// - Throws: ``LiveSessionError/graphDSLFailed(diagnostics:underlying:)`` with
|
||||
/// editor-ready diagnostics for a lex/parse/build failure (before any
|
||||
/// mutation), or for one or more per-statement engine rejections (after the
|
||||
/// surviving statements have gone live).
|
||||
@MainActor
|
||||
public func runGraphDSL(
|
||||
_ source: String,
|
||||
additive: Bool = false,
|
||||
resources: DSLResourceResolver = DSLEmptyResources()
|
||||
) throws {
|
||||
// Build everything first — no engine mutation until we know the whole
|
||||
// program is valid.
|
||||
let outputs: [DSLOutput]
|
||||
do {
|
||||
outputs = try DSLInterpreter.evaluate(source, resources: resources)
|
||||
} catch {
|
||||
throw LiveSessionError.graphDSLFailed(
|
||||
diagnostics: GraphDSLDiagnosticMapper.diagnostics(for: error, source: source),
|
||||
underlying: error
|
||||
)
|
||||
}
|
||||
|
||||
if !additive { clearTracked() }
|
||||
|
||||
// Play every statement. An engine-level rejection of ONE statement
|
||||
// (e.g. `.pendingQueueFull`) must not abort the rest — the others still
|
||||
// go live, mirroring `SnippetContext.play`'s per-statement best-effort
|
||||
// behavior. Failures are collected and surfaced together; the graphs
|
||||
// that added successfully keep playing.
|
||||
var failures: [Diagnostic] = []
|
||||
var firstError: Error?
|
||||
for output: DSLOutput in outputs {
|
||||
let synth: ClosureSynthesizer = ClosureSynthesizer {
|
||||
// The graph is already built (eagerly, by the interpreter); the
|
||||
// closure just hands it to `build()`. Each `DSLOutput.graph` is
|
||||
// owned by exactly one synth, so this never shares a graph.
|
||||
output.graph
|
||||
}
|
||||
do {
|
||||
if let slot: String = output.slot {
|
||||
try swapSlot(slot, synth: synth)
|
||||
} else {
|
||||
try engine.add(synth)
|
||||
track(synth)
|
||||
}
|
||||
} catch {
|
||||
if firstError == nil { firstError = error }
|
||||
failures.append(contentsOf: GraphDSLDiagnosticMapper.diagnostics(for: error, source: source))
|
||||
}
|
||||
}
|
||||
if let firstError: Error = firstError {
|
||||
throw LiveSessionError.graphDSLFailed(diagnostics: failures, underlying: firstError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,184 @@
|
||||
// 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
|
||||
@@ -48,6 +48,94 @@ public final class SnippetContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// Play `synth` into a **named slot**, replacing whatever synth was there
|
||||
/// before — the `Pdef`-style hot-swap primitive.
|
||||
///
|
||||
/// Unlike ``play(_:)``, a slotted synth is *not* torn down by the next
|
||||
/// non-additive re-evaluation. Re-running a `play(slot:)` for the same name
|
||||
/// swaps that one voice in place (the new voice starts before the old is
|
||||
/// removed — a brief overlap, no gap), while other slots keep playing.
|
||||
/// This lets you mutate one voice at a time, live.
|
||||
///
|
||||
/// ```swift
|
||||
/// context.play(slot: "bass") { OscSaw.Audio(freq: 55, mul: 0.2) }
|
||||
/// ```
|
||||
///
|
||||
/// Clear a slot with `context.session.clearSlot("bass")`, or all slots with
|
||||
/// `context.session.clearSlots()`.
|
||||
///
|
||||
/// The swap is immediate by default, or quantized to the next beat/bar when
|
||||
/// the session has a ``LiveSession/swapClock`` and a non-`.immediate`
|
||||
/// ``LiveSession/swapQuantize`` — see ``LiveSession/swapSlot(_:synth:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: Slot identifier. Re-using a name replaces that slot's synth.
|
||||
/// - synth: The `Synthesizer` to install.
|
||||
/// - Returns: `true` if the engine accepted the add/schedule; `false` if it
|
||||
/// threw (in which case the prior slot synth is left in place).
|
||||
@discardableResult
|
||||
@MainActor public func play(slot name: String, _ synth: any Synthesizer) -> Bool {
|
||||
do {
|
||||
try session.swapSlot(name, synth: synth)
|
||||
return true
|
||||
} catch {
|
||||
session.lastSnippetMessage = "play(slot: \"\(name)\") failed: \(error)"
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Play a bare generator graph into a **named slot** — the `Pdef`-style
|
||||
/// hot-swap primitive with no `SynthesizerBase` subclass to declare.
|
||||
///
|
||||
/// See ``play(slot:_:)`` for the slot semantics.
|
||||
///
|
||||
/// ```swift
|
||||
/// context.play(slot: "lead") { Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0) }
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: Slot identifier. Re-using a name replaces that slot's synth.
|
||||
/// - bus: Output bus the graph is written to (multi-channel sources
|
||||
/// continue into following buses). Defaults to `0`.
|
||||
/// - make: Builds and returns the output graph. Called once, inside the
|
||||
/// synthesizer's `build()`.
|
||||
/// - Returns: `true` if the engine accepted the enqueue; `false` otherwise.
|
||||
@discardableResult
|
||||
@MainActor public func play(
|
||||
slot name: String,
|
||||
bus: any ValidBus = 0,
|
||||
_ make: @escaping () -> any ValidGeneratorInput
|
||||
) -> Bool {
|
||||
play(slot: name, ClosureSynthesizer(bus: bus, make))
|
||||
}
|
||||
|
||||
/// Add a bare generator graph to the engine — the fastest path to sound in
|
||||
/// a snippet, with no `SynthesizerBase` subclass to declare.
|
||||
///
|
||||
/// ```swift
|
||||
/// context.play { OscSin.Audio(freq: 440, mul: 0.1) }
|
||||
/// context.play(bus: 0) { Pan2(input: saw, pan: 0) }
|
||||
/// ```
|
||||
///
|
||||
/// Wraps `make` in a ``ClosureSynthesizer`` and forwards to ``play(_:)`` —
|
||||
/// the synth is tracked for cleanup on the next non-additive re-evaluation
|
||||
/// just like any other. Construct the generators inside the closure.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bus: Output bus the graph is written to (multi-channel sources
|
||||
/// continue into following buses). Defaults to `0`.
|
||||
/// - make: Builds and returns the output graph. Called once, inside the
|
||||
/// synthesizer's `build()`.
|
||||
/// - Returns: `true` if the engine accepted the enqueue; `false` if
|
||||
/// `engine.add` threw.
|
||||
@discardableResult
|
||||
@MainActor public func play(
|
||||
bus: any ValidBus = 0,
|
||||
_ make: @escaping () -> any ValidGeneratorInput
|
||||
) -> Bool {
|
||||
play(ClosureSynthesizer(bus: bus, make))
|
||||
}
|
||||
|
||||
/// Snippet-side hook for test verification: report the engine's sample rate
|
||||
/// back through the session so tests can confirm the `context.engine`
|
||||
/// linkage compiled and called correctly.
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,39 @@
|
||||
// SourceKitLSPError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// Errors surfaced by ``SourceKitLSPClient``. macOS only.
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// A failure from the `sourcekit-lsp` client.
|
||||
public enum SourceKitLSPError: Error, CustomStringConvertible {
|
||||
/// The `sourcekit-lsp` executable could not be launched (bad path, missing
|
||||
/// toolchain, spawn failure). Thrown from ``SourceKitLSPClient/start(rootURI:)``.
|
||||
case launchFailed(String)
|
||||
/// A request was made against a client that was never started or has been
|
||||
/// shut down (or the server exited). Also used to fail in-flight requests
|
||||
/// when the server dies.
|
||||
case notRunning
|
||||
/// A request exceeded the client's per-request timeout. Guards against a
|
||||
/// wedged server; carries the LSP method that timed out.
|
||||
case timedOut(method: String)
|
||||
/// The server returned a JSON-RPC error response, carrying its code and
|
||||
/// message.
|
||||
case serverError(code: Int, message: String)
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .launchFailed(let m): return "sourcekit-lsp failed to launch: \(m)"
|
||||
case .notRunning: return "sourcekit-lsp is not running"
|
||||
case .timedOut(let m): return "sourcekit-lsp timed out on \(m)"
|
||||
case .serverError(let c, let m): return "sourcekit-lsp error \(c): \(m)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,56 @@
|
||||
// SwapQuantize.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `SwapQuantize` chooses when a named-slot swap becomes audible: immediately, or
|
||||
// aligned to the next beat / bar of a `LyrebirdClock`. Quantizing the swap to a
|
||||
// musical boundary is what masks compile latency — the `swiftc` build finishes a
|
||||
// few hundred ms after ⌘↩, then the swap lands exactly on the downbeat rather
|
||||
// than whenever the compile happened to finish.
|
||||
|
||||
#if os(macOS)
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
/// When a ``LiveSession`` named-slot swap becomes audible.
|
||||
///
|
||||
/// Set on ``LiveSession/swapQuantize`` together with a ``LiveSession/swapClock``.
|
||||
/// With no clock, or `.immediate`, a swap takes effect right away. `.nextBeat` /
|
||||
/// `.nextBar` schedule the new voice's add and the old voice's removal at the
|
||||
/// same upcoming boundary sample time, so the swap is glitch-free and on-grid.
|
||||
public enum SwapQuantize: Sendable, Equatable {
|
||||
|
||||
/// Swap immediately, as soon as the snippet runs.
|
||||
case immediate
|
||||
|
||||
/// Swap on the next whole beat boundary.
|
||||
case nextBeat
|
||||
|
||||
/// Swap on the next bar boundary, where a bar is `beatsPerBar` beats.
|
||||
case nextBar(beatsPerBar: Int)
|
||||
|
||||
/// The absolute clock beat this quantization targets from *now*, or `nil`
|
||||
/// for `.immediate`. `.nextBeat` returns the next whole beat; `.nextBar`
|
||||
/// returns the next multiple of `beatsPerBar` beats.
|
||||
///
|
||||
/// Reads `clock.currentBeat` once; the returned beat is strictly in the
|
||||
/// future for a running clock (a whole-numbered current beat rounds up to
|
||||
/// the following boundary, matching `LyrebirdClock.nextBeat`).
|
||||
public func targetBeat(clock: LyrebirdClock) -> Double? {
|
||||
switch self {
|
||||
case .immediate:
|
||||
return nil
|
||||
case .nextBeat:
|
||||
return floor(clock.currentBeat) + 1.0
|
||||
case .nextBar(let beatsPerBar):
|
||||
let bar: Double = Double(max(1, beatsPerBar))
|
||||
return (floor(clock.currentBeat / bar) + 1.0) * bar
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user