327 lines
14 KiB
Swift
327 lines
14 KiB
Swift
// 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<name>`.
|
|
public let libraries: [String]
|
|
|
|
/// `-Xlinker -rpath -Xlinker <path>` entries baked into the snippet dylib
|
|
/// so `dlopen` resolves dependent dylibs (`libLyrebird.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] = ["Lyrebird", "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=<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)"]
|
|
}
|
|
// 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
|
|
}
|
|
|
|
// MARK: - Build-dir discovery
|
|
|
|
/// Best-effort discovery of the SPM `.build/<triple>/<config>` directory
|
|
/// that contains `libLyrebird.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: the product/dylib is named `Lyrebird` (libLyrebird.dylib); the
|
|
// module/target is named `LyrebirdSynth` (LyrebirdSynth.swiftmodule).
|
|
let markers: [String] = ["libLyrebird.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 `libLyrebird.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("libLyrebird.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
|