733 lines
34 KiB
Swift
733 lines
34 KiB
Swift
// LiveSession.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
// LyrebirdLiveCompile
|
||
//
|
||
// `LiveSession` owns the `SynthesisEngine` and tracks every `Synthesizer` that
|
||
// each snippet `play(_:)`s, so the next non-additive re-evaluation can
|
||
// `engine.remove(_:)` them before running fresh user code. Also caches every
|
||
// `CompiledSnippet` so the dylibs stay mapped — see the leak-by-design note in
|
||
// `CompiledSnippet.swift`.
|
||
|
||
#if os(macOS)
|
||
import Foundation
|
||
import LyrebirdSynth
|
||
|
||
/// Host-side owner of one live-coding session.
|
||
///
|
||
/// Holds the `SynthesisEngine` that snippets target, the swiftc flags used to
|
||
/// compile snippets, and the tracking lists needed for re-evaluation cleanup.
|
||
/// Snippets receive a `SnippetContext` bound to this session through
|
||
/// `compileAndRun(_:additive:)`.
|
||
///
|
||
/// `@unchecked Sendable`: a `LiveSession` is shared between its `@MainActor`
|
||
/// owner (`LyrebirdScratchModel`) and the `nonisolated` `compileAndRunAsync` it calls, so
|
||
/// 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 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
|
||
/// after it completes — no concurrent access in practice.
|
||
public final class LiveSession: @unchecked Sendable {
|
||
|
||
public let engine: SynthesisEngine
|
||
|
||
/// `-I` paths threaded to `swiftc` for module discovery.
|
||
public let importPaths: [URL]
|
||
|
||
/// `-L` paths threaded to `swiftc` for library search.
|
||
public let librarySearchPaths: [URL]
|
||
|
||
/// Bare library names threaded to `swiftc` as `-l<name>`.
|
||
public let libraries: [String]
|
||
|
||
/// `-Xlinker -rpath -Xlinker <path>` entries baked into the snippet dylib
|
||
/// so `dlopen` resolves dependent dylibs (`libLyrebirdDynamic.dylib` etc.) at
|
||
/// 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?
|
||
|
||
/// Side-channel for snippet `context.reportMessage(_:)` calls. Tests read
|
||
/// via `@testable import`; not part of the public API.
|
||
internal var lastSnippetMessage: String?
|
||
|
||
// Tracked state — all access guarded by `trackingLock`.
|
||
private let trackingLock: NSLock = NSLock()
|
||
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(),
|
||
librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(),
|
||
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
|
||
rpaths: [URL] = LiveSession.defaultRpaths()
|
||
) {
|
||
self.engine = engine
|
||
self.importPaths = importPaths
|
||
self.librarySearchPaths = librarySearchPaths
|
||
self.libraries = libraries
|
||
self.rpaths = rpaths
|
||
}
|
||
|
||
/// Wrap `userBody` in the standard harness, compile, and call the snippet's
|
||
/// `lyrebird_snippet_entry` with a `SnippetContext` bound to this session.
|
||
///
|
||
/// - Parameters:
|
||
/// - userBody: Swift code that runs inside the snippet entry. Has access
|
||
/// to a local `context: SnippetContext`.
|
||
/// - additive: When `false` (default), removes every previously tracked
|
||
/// synth before running. When `true`, leaves prior synths in place
|
||
/// (⌘⇧↩ semantics in the future `LyrebirdScratchView` editor).
|
||
/// - Returns: The compiled snippet handle. Retained internally so the dylib
|
||
/// stays mapped; callers can ignore it.
|
||
/// `@MainActor`: runs the snippet entry — and thus the user body's
|
||
/// `MainActor.assumeIsolated { … }` and any `context.play(_:)` → `engine.add` — on the
|
||
/// main thread, synchronously (swiftc compile included). The async variant
|
||
/// ``compileAndRunAsync(_:additive:)`` keeps the compile off-main.
|
||
@discardableResult
|
||
@MainActor
|
||
public func compileAndRun(_ userBody: String, additive: Bool = false) throws -> CompiledSnippet {
|
||
if !additive {
|
||
clearTracked()
|
||
}
|
||
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: userBody)
|
||
let snippet: CompiledSnippet = try compileWrapped(wrapped)
|
||
runEntry(of: snippet)
|
||
return snippet
|
||
}
|
||
|
||
/// Asynchronous variant of ``compileAndRun(_:additive:)``. The swiftc compile runs on a
|
||
/// background `Task.detached` so `LyrebirdScratchView`'s editor stays responsive; the
|
||
/// engine-touching steps (`clearTracked()` and the snippet entry via `runEntry`) then run
|
||
/// on the **main actor**.
|
||
///
|
||
/// Running the entry on the main actor matters: the snippet's
|
||
/// `context.play(_:)` calls `engine.add(_:)`, which is `@MainActor` and
|
||
/// mutates `engine.nodeTreeMirror` — state observed by SwiftUI on the main thread. A
|
||
/// `nonisolated async` method resumes on the generic executor, NOT the caller's actor, so
|
||
/// the hop is explicit here rather than assumed.
|
||
///
|
||
/// - Precondition: only one in-flight invocation at a time per `LiveSession`.
|
||
/// Concurrent calls can interleave `clearTracked()` with the prior call's
|
||
/// not-yet-completed `runEntry`, silently dropping tracked synths. The
|
||
/// built-in caller `LyrebirdScratchModel` serialises through its
|
||
/// `isCompiling` flag; out-of-tree callers must enforce the same.
|
||
///
|
||
/// - Parameters:
|
||
/// - userBody: Same as the synchronous variant.
|
||
/// - additive: Same as the synchronous variant.
|
||
/// - Returns: The compiled snippet handle. Retained internally.
|
||
@discardableResult
|
||
public func compileAndRunAsync(_ userBody: String, additive: Bool = false) async throws -> CompiledSnippet {
|
||
if !additive {
|
||
// `clearTracked()` calls `engine.remove` (touches `nodeTreeMirror`) — main only.
|
||
await MainActor.run { clearTracked() }
|
||
}
|
||
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: userBody)
|
||
let args: [String] = makeSwiftcArgs()
|
||
let snippet: CompiledSnippet = try await Task.detached(priority: .userInitiated) {
|
||
try LiveSession.compileBlocking(wrapped: wrapped, extraArgs: args)
|
||
}.value
|
||
// Snippet entry runs the user's `context.play(_:)` → `engine.add` (@MainActor).
|
||
await MainActor.run { runEntry(of: snippet) }
|
||
return snippet
|
||
}
|
||
|
||
// Synchronous compile body used by both `compileAndRun` and the detached
|
||
// background `Task` inside `compileAndRunAsync`. Wraps the
|
||
// `LiveCompileError` → `LiveSessionError` translation in one place.
|
||
private static func compileBlocking(wrapped: WrappedSnippet, extraArgs: [String]) throws -> CompiledSnippet {
|
||
do {
|
||
return try LiveCompiler.compile(
|
||
source: wrapped.source,
|
||
extraSwiftcArgs: extraArgs
|
||
)
|
||
} catch let error as LiveCompileError {
|
||
if case .compileFailed(_, let stderr) = error {
|
||
let diagnostics: [Diagnostic] = DiagnosticParser.parse(
|
||
stderr: stderr,
|
||
userBodyLineOffset: wrapped.userBodyLineOffset
|
||
)
|
||
throw LiveSessionError.snippetCompileFailed(
|
||
diagnostics: diagnostics,
|
||
underlying: error
|
||
)
|
||
}
|
||
throw LiveSessionError.compilerError(error)
|
||
}
|
||
}
|
||
|
||
private func compileWrapped(_ wrapped: WrappedSnippet) throws -> CompiledSnippet {
|
||
try LiveSession.compileBlocking(wrapped: wrapped, extraArgs: makeSwiftcArgs())
|
||
}
|
||
|
||
private func runEntry(of snippet: CompiledSnippet) {
|
||
let context: SnippetContext = SnippetContext(session: self)
|
||
withExtendedLifetime(context) {
|
||
let opaque: UnsafeMutableRawPointer = Unmanaged.passUnretained(context).toOpaque()
|
||
snippet.entry(opaque)
|
||
}
|
||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||
loadedSnippets.append(snippet)
|
||
}
|
||
|
||
/// Currently tracked synth count. Thread-safe.
|
||
public var trackedSynthCount: Int {
|
||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||
return trackedSynths.count
|
||
}
|
||
|
||
/// Remove every tracked synth from the engine and clear the tracking list.
|
||
/// Called automatically by `compileAndRun(_:additive: false)`.
|
||
public func clearTracked() {
|
||
let snapshot: [any Synthesizer]
|
||
do {
|
||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||
snapshot = trackedSynths
|
||
trackedSynths.removeAll()
|
||
}
|
||
for synth: any Synthesizer in snapshot {
|
||
_ = engine.remove(synth)
|
||
}
|
||
}
|
||
|
||
/// Internal hook for `SnippetContext.play(_:)`. Thread-safe.
|
||
func track(_ synth: any Synthesizer) {
|
||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||
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
|
||
|
||
/// 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]
|
||
}
|
||
// Clang module maps (e.g. `LyrebirdC.modulemap`) generated by Xcode for
|
||
// SPM C targets — surface each as `-Xcc -fmodule-map-file=<path>` so
|
||
// swiftc's embedded clang can resolve the underlying C module declared
|
||
// in a Swift module's dependency record.
|
||
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
|
||
// `-undefined dynamic_lookup` so the snippet's dylib defers symbol
|
||
// resolution to runtime, where dyld finds Lyrebird's symbols in the
|
||
// already-loaded host process.
|
||
let hasDylib: Bool = librarySearchPaths.contains { url in
|
||
LiveSession.hasLyrebirdDylib(in: url)
|
||
}
|
||
if hasDylib {
|
||
for path: URL in librarySearchPaths {
|
||
args += ["-L", path.path]
|
||
}
|
||
for lib: String in libraries {
|
||
args += ["-l\(lib)"]
|
||
}
|
||
for path: URL in rpaths {
|
||
args += ["-Xlinker", "-rpath", "-Xlinker", path.path]
|
||
}
|
||
} else {
|
||
args += ["-Xlinker", "-undefined", "-Xlinker", "dynamic_lookup"]
|
||
}
|
||
return args
|
||
}
|
||
|
||
/// Walk up from each import path looking for Xcode's
|
||
/// `Build/Intermediates.noindex/GeneratedModuleMaps/` directory and return
|
||
/// every `*.modulemap` it contains. Empty on `swift build` SPM layouts
|
||
/// (where C modules use the package's own `include/module.modulemap`).
|
||
static func discoverClangModuleMaps(in importPaths: [URL]) -> [URL] {
|
||
let maxWalk: Int = 6
|
||
var found: [URL] = []
|
||
var visited: Set<String> = Set<String>()
|
||
for start: URL in importPaths {
|
||
var cur: URL = start
|
||
for _ in 0..<maxWalk {
|
||
let probe: URL = cur
|
||
.appendingPathComponent("Build")
|
||
.appendingPathComponent("Intermediates.noindex")
|
||
.appendingPathComponent("GeneratedModuleMaps")
|
||
if FileManager.default.fileExists(atPath: probe.path),
|
||
!visited.contains(probe.path) {
|
||
visited.insert(probe.path)
|
||
if let entries: [URL] = try? FileManager.default.contentsOfDirectory(at: probe, includingPropertiesForKeys: nil) {
|
||
for entry: URL in entries where entry.pathExtension == "modulemap" {
|
||
found.append(entry)
|
||
}
|
||
}
|
||
}
|
||
let parent: URL = cur.deletingLastPathComponent()
|
||
if parent == cur { break }
|
||
cur = parent
|
||
}
|
||
}
|
||
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
|
||
/// that contains `libLyrebirdDynamic.dylib` and the swiftmodule directories. Used
|
||
/// as the default for `importPaths`/`librarySearchPaths`/`rpaths`. Hosts can
|
||
/// override by passing explicit URLs.
|
||
///
|
||
/// Searches, in order:
|
||
/// 1. Walks up from `Bundle(for: LiveSession.self).bundleURL` — this resolves
|
||
/// to the directory holding `libLyrebirdLiveCompileDynamic.dylib` at runtime,
|
||
/// which is the SPM debug/release dir.
|
||
/// 2. Walks up from `Bundle.main.executableURL` — fallback for the case
|
||
/// where the host bundles the dylibs into an `.app`.
|
||
public static func currentBuildDir() -> URL? {
|
||
let maxWalk: Int = 6
|
||
let candidates: [URL] = [
|
||
Bundle(for: LiveSession.self).bundleURL,
|
||
Bundle.main.executableURL ?? Bundle.main.bundleURL,
|
||
]
|
||
// Accept either an SPM-produced .dylib (swift build) or just the
|
||
// LyrebirdSynth.swiftmodule (Xcode SPM static-linked into the host app).
|
||
// The swiftmodule alone is enough for `-I` module resolution; linking
|
||
// falls back to `-undefined dynamic_lookup` when no dylib is found.
|
||
// Note: LiveCompile depends on the internal `LyrebirdDynamic` product
|
||
// (→ libLyrebirdDynamic.dylib); the module/target is `LyrebirdSynth`
|
||
// (LyrebirdSynth.swiftmodule). The consumer-facing `Lyrebird` product
|
||
// is static and produces no dylib, so it is not a marker here.
|
||
let markers: [String] = ["libLyrebirdDynamic.dylib", "LyrebirdSynth.swiftmodule"]
|
||
for start: URL in candidates {
|
||
var cur: URL = start
|
||
for _ in 0..<maxWalk {
|
||
for marker: String in markers {
|
||
let probe: URL = cur.appendingPathComponent(marker)
|
||
if FileManager.default.fileExists(atPath: probe.path) {
|
||
return cur
|
||
}
|
||
}
|
||
let parent: URL = cur.deletingLastPathComponent()
|
||
if parent == cur { break }
|
||
cur = parent
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
/// `true` when a `libLyrebirdDynamic.dylib` actually exists in `buildDir`.
|
||
/// Used to decide whether to link against the dylib at compile time or fall
|
||
/// back to `-undefined dynamic_lookup` so the snippet binds to symbols
|
||
/// already resolved in the running process.
|
||
public static func hasLyrebirdDylib(in buildDir: URL) -> Bool {
|
||
FileManager.default.fileExists(
|
||
atPath: buildDir.appendingPathComponent("libLyrebirdDynamic.dylib").path
|
||
)
|
||
}
|
||
|
||
public static func defaultImportPaths() -> [URL] {
|
||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
||
return [buildDir, buildDir.appendingPathComponent("Modules")]
|
||
}
|
||
|
||
public static func defaultLibrarySearchPaths() -> [URL] {
|
||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
||
return [buildDir]
|
||
}
|
||
|
||
public static func defaultRpaths() -> [URL] {
|
||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
||
return [buildDir]
|
||
}
|
||
}
|
||
|
||
#endif
|