Files
Lyrebird/LiveCompile/Sources/LyrebirdLiveCompile/LiveSession.swift
T

354 lines
16 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 only mutable graph state — `trackedSynths` and `loadedSnippets` — is accessed
/// exclusively under `trackingLock` (`track`, `clearTracked`, `trackedSynthCount`,
/// `runEntry`).
/// - `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]
/// 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", "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: - 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 `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