// LiveSession.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT // LyrebirdLiveCompile — Phase 143 // // `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:)`. public final class LiveSession { 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`. public let libraries: [String] /// `-Xlinker -rpath -Xlinker ` 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] /// 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] = [] public init( engine: SynthesisEngine, importPaths: [URL] = LiveSession.defaultImportPaths(), librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(), libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompile"], 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. @discardableResult 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`; the snippet entry then /// executes on the caller's actor (typically the main actor, so snippets /// can touch UI-side state). Lets `LyrebirdScratchView`'s editor stay /// responsive during the compile. /// /// - 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() } 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 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: - swiftc flag construction private func makeSwiftcArgs() -> [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=` 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)"] } // When a Lyrebird dylib exists in any -L path, link against it // (-l) 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 = Set() for start: URL in importPaths { var cur: URL = start for _ in 0../` 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 `libLyrebirdLiveCompile.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.. 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