1.0.0 release

This commit is contained in:
2026-06-01 18:27:40 -07:00
parent b1ab0f102c
commit 1f20fcab20
1151 changed files with 230703 additions and 14 deletions
@@ -0,0 +1,57 @@
// CompiledSnippet.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core
//
// `CompiledSnippet` owns the `dlopen` handle and the resolved entry function
// pointer for one snippet's dylib. Held by the live session for the lifetime of
// the process — dylib unload is unsafe while live `Synth` instances may still
// reference types defined in the dylib. (See plan in
// `memory/project_live_compile_phases.md` non-goals.)
import Foundation
#if os(macOS)
/// Handle to one successfully compiled and loaded snippet.
///
/// Intentionally a `final class` (not a `struct`): owning the `dlopen` handle
/// via reference identity means moves / copies cannot duplicate or accidentally
/// drop ownership. There is no `deinit` that calls `dlclose` — see the file
/// header.
///
/// `@unchecked Sendable`: every stored field is `let`; the `dlopen` handle and
/// the resolved entry pointer are both thread-safe to hold and read after the
/// compile completes (the loader serialises symbol resolution). Allows
/// `LiveSession.compileAndRunAsync` to return one across a `Task.detached`
/// boundary.
public final class CompiledSnippet: @unchecked Sendable {
/// Module name passed to `swiftc -module-name`; useful for diagnostics.
public let moduleName: String
/// Path to the dylib that was `dlopen`'d.
public let dylibPath: String
/// Resolved entry function pointer. Calling this is Phase 143's job.
public let entry: SnippetEntry
/// Raw `dlopen` handle. Kept so the OS keeps the dylib mapped.
public let handle: UnsafeMutableRawPointer
init(
moduleName: String,
dylibPath: String,
entry: SnippetEntry,
handle: UnsafeMutableRawPointer
) {
self.moduleName = moduleName
self.dylibPath = dylibPath
self.entry = entry
self.handle = handle
}
}
#endif
@@ -0,0 +1,52 @@
// Diagnostic.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
//
// One parsed `swiftc` diagnostic, with `line` already mapped from the wrapped-
// snippet coordinate space back to the user's snippet coordinate space (via the
// `userBodyLineOffset` from `SnippetHarness.wrap(userBody:)`).
//
// The editor in Phase 145 (`LyrebirdScratchView`) renders diagnostics in its
// margin gutter using `(line, column)` directly.
#if os(macOS)
public struct Diagnostic: Equatable, Sendable {
/// 1-based line number in the **user's** snippet body. May be `nil` when the
/// diagnostic landed inside the harness preamble (i.e. the wrapped line
/// number is less than `userBodyLineOffset`) — that almost always points at
/// the user importing a missing module or otherwise breaking the preamble.
public let line: Int?
/// 1-based column number. swiftc emits the same column for preamble and
/// user-body lines, so no translation is needed.
public let column: Int
public let severity: DiagnosticSeverity
public let message: String
/// 1-based line number swiftc actually reported, before user-coordinate
/// translation. Useful for debugging the parser; not surfaced to end users.
public let rawLine: Int
public init(
line: Int?,
column: Int,
severity: DiagnosticSeverity,
message: String,
rawLine: Int
) {
self.line = line
self.column = column
self.severity = severity
self.message = message
self.rawLine = rawLine
}
}
#endif
@@ -0,0 +1,101 @@
// DiagnosticParser.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
//
// `DiagnosticParser.parse(stderr:userBodyLineOffset:)` walks the swiftc stderr
// stream line by line, extracts diagnostics matching the standard
// `<path>:<line>:<column>: <severity>: <message>` shape, and re-maps line
// numbers from wrapped-snippet coordinates back to user-snippet coordinates.
//
// swiftc stderr format (one diagnostic):
//
// /tmp/.../Snippet.swift:7:14: error: cannot convert value of type 'String' to 'Int'
// 7 | let x: Int = "nope"
// | `- error: cannot convert value of type 'String' to 'Int'
//
// We pick up the first line (the location/severity/message header) and ignore
// the source-context lines that follow.
import Foundation
#if os(macOS)
public enum DiagnosticParser {
/// Compiled once at first access. Pattern matches the standard swiftc
/// header line: `<path>:<line>:<column>: <severity>: <message>`.
/// `try!` is safe — the pattern is a compile-time literal that cannot fail
/// `NSRegularExpression`'s validator.
private static let _headerRegex: NSRegularExpression = {
// swiftlint:disable:next force_try
try! NSRegularExpression(
pattern: #"^(.+?):(\d+):(\d+):\s+(error|warning|note):\s+(.*)$"#
)
}()
/// Parse swiftc stderr into a list of structured diagnostics, with line
/// numbers translated to user-snippet coordinates.
///
/// - Parameters:
/// - stderr: Raw swiftc stderr text. May be empty.
/// - userBodyLineOffset: 1-based line on which the user's body starts in
/// the wrapped source — typically `SnippetHarness.wrap(userBody:).userBodyLineOffset`.
/// Diagnostics on `rawLine >= userBodyLineOffset` are mapped to
/// `rawLine - (userBodyLineOffset - 1)`; diagnostics on earlier lines
/// keep `line = nil` to signal "in the harness preamble".
/// - Returns: One `Diagnostic` per matched header line, in stderr order.
public static func parse(stderr: String, userBodyLineOffset: Int) -> [Diagnostic] {
var result: [Diagnostic] = []
for rawLine: String.SubSequence in stderr.split(separator: "\n", omittingEmptySubsequences: false) {
guard let diag: Diagnostic = parseLine(String(rawLine), userBodyLineOffset: userBodyLineOffset) else {
continue
}
result.append(diag)
}
return result
}
/// Parse one stderr line. Returns `nil` for non-header lines (source-context
/// rows, caret markers, blank lines).
static func parseLine(_ rawLine: String, userBodyLineOffset: Int) -> Diagnostic? {
// Pattern (anchored):
// <path>:<line>:<column>: <severity>: <message>
// Where <path> contains no colon-space combos, and <severity> ∈ {error, warning, note}.
//
// The path may legally contain `:` on macOS (filesystem allows it), so use a
// greedy-then-validate approach: scan from the right for the third-from-last
// `:` and split on that. Cheaper: regex with a non-greedy path segment.
let range: NSRange = NSRange(rawLine.startIndex..<rawLine.endIndex, in: rawLine)
guard let match: NSTextCheckingResult = _headerRegex.firstMatch(in: rawLine, range: range),
match.numberOfRanges == 6,
let lineRange: Range<String.Index> = Range(match.range(at: 2), in: rawLine),
let colRange: Range<String.Index> = Range(match.range(at: 3), in: rawLine),
let severityRange: Range<String.Index> = Range(match.range(at: 4), in: rawLine),
let messageRange: Range<String.Index> = Range(match.range(at: 5), in: rawLine),
let rawLineNumber: Int = Int(rawLine[lineRange]),
let column: Int = Int(rawLine[colRange]),
let severity: DiagnosticSeverity = DiagnosticSeverity(rawValue: String(rawLine[severityRange]))
else { return nil }
let userLine: Int?
if rawLineNumber >= userBodyLineOffset {
userLine = rawLineNumber - (userBodyLineOffset - 1)
} else {
userLine = nil
}
return Diagnostic(
line: userLine,
column: column,
severity: severity,
message: String(rawLine[messageRange]),
rawLine: rawLineNumber
)
}
}
#endif
@@ -0,0 +1,19 @@
// DiagnosticSeverity.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
//
// Severity classifier for a parsed swiftc diagnostic line.
#if os(macOS)
public enum DiagnosticSeverity: String, Equatable, Sendable {
case error
case warning
case note
}
#endif
@@ -0,0 +1,51 @@
// LiveCompileError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core
//
// Errors raised by `LiveCompiler.compile(source:)`. RT path never sees these:
// compilation is a main-thread (or background-queue) operation that runs long
// before any audio block.
import Foundation
#if os(macOS)
public enum LiveCompileError: Error, CustomStringConvertible, Equatable, Sendable {
/// `xcrun -f swiftc` and the fallback paths all failed.
case swiftcNotFound
/// `swiftc` exited non-zero. `stderr` carries the raw compiler output; Phase
/// 144 parses it into structured diagnostics.
case compileFailed(exitCode: Int32, stderr: String)
/// `dlopen(dylibPath, RTLD_NOW)` returned `nil`. `message` is the `dlerror()`
/// string at the time of the failure.
case dlopenFailed(path: String, message: String)
/// The dylib opened but did not export the expected entry symbol.
case entrySymbolMissing(symbol: String, message: String)
/// A temp-dir / write step failed before `swiftc` was invoked.
case ioFailed(underlying: String)
public var description: String {
switch self {
case .swiftcNotFound:
return "swiftc binary not found in xcrun or standard toolchain paths"
case .compileFailed(let code, let stderr):
return "swiftc exited \(code):\n\(stderr)"
case .dlopenFailed(let path, let message):
return "dlopen failed for \(path): \(message)"
case .entrySymbolMissing(let symbol, let message):
return "missing snippet entry symbol \(symbol): \(message)"
case .ioFailed(let underlying):
return "IO step failed: \(underlying)"
}
}
}
#endif
@@ -0,0 +1,210 @@
// LiveCompiler.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core
//
// `LiveCompiler.compile(source:)` shells out to `swiftc -emit-library`, then
// `dlopen`s the resulting dylib and resolves the snippet entry symbol. No UI,
// no `SynthesisEngine` binding (those land in phases 143–146). macOS only —
// iOS cannot exec swiftc.
import Foundation
#if os(macOS)
import Darwin
#endif
#if os(macOS)
/// Symbol the snippet preamble must export. Snippets declare:
///
/// ```swift
/// @_cdecl("lyrebird_snippet_entry")
/// public func entry(_ ctx: UnsafeMutableRawPointer?) { /* ... */ }
/// ```
public let lyrebirdSnippetEntrySymbol: String = "lyrebird_snippet_entry"
/// One-shot snippet compiler. Stateless — every `compile(source:)` allocates a
/// fresh temp dir, dylib name, and `dlopen` handle.
public enum LiveCompiler {
/// Compile `source` to a dylib and resolve the snippet entry symbol.
///
/// - Parameters:
/// - source: Full Swift source, including the `@_cdecl("lyrebird_snippet_entry")`
/// entry. Phase 143's `SnippetHarness` will wrap user input in a preamble that
/// provides this; Phase 142 callers (incl. tests) write the full file.
/// - extraSwiftcArgs: Extra args appended to the `swiftc` invocation. Tests use
/// this for `-suppress-warnings` etc. Production callers leave empty.
/// - Returns: `CompiledSnippet` holding the dlopen handle and entry pointer.
/// - Throws: `LiveCompileError` cases for missing toolchain, compile failure,
/// `dlopen` failure, or missing entry symbol.
public static func compile(
source: String,
extraSwiftcArgs: [String] = []
) throws -> CompiledSnippet {
let swiftc: String = try findSwiftc()
let snippetID: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
let moduleName: String = "LBSnippet_\(snippetID)"
let workDir: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LyrebirdLiveCompile-\(snippetID)", isDirectory: true)
let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path
let dylibPath: String = workDir.appendingPathComponent("lib\(moduleName).dylib").path
do {
try FileManager.default.createDirectory(
at: workDir,
withIntermediateDirectories: true
)
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
} catch {
throw LiveCompileError.ioFailed(underlying: "\(error)")
}
var arguments: [String] = [
"-emit-library",
"-module-name", moduleName,
"-o", dylibPath,
]
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
)
}
guard let handle: UnsafeMutableRawPointer = dlopen(dylibPath, RTLD_NOW) else {
let message: String = dlerror().map { String(cString: $0) } ?? "unknown dlopen error"
throw LiveCompileError.dlopenFailed(path: dylibPath, message: message)
}
guard let symbol: UnsafeMutableRawPointer = dlsym(handle, lyrebirdSnippetEntrySymbol) else {
let message: String = dlerror().map { String(cString: $0) } ?? "unknown dlsym error"
// Leave the dylib mapped — closing it after a successful open would
// unmap its types if anything is already referencing them. The
// failure is post-load, so the safe action is to leak.
throw LiveCompileError.entrySymbolMissing(
symbol: lyrebirdSnippetEntrySymbol,
message: message
)
}
let entry: SnippetEntry = unsafeBitCast(symbol, to: SnippetEntry.self)
return CompiledSnippet(
moduleName: moduleName,
dylibPath: dylibPath,
entry: entry,
handle: handle
)
}
// MARK: - swiftc resolution
/// First-success search:
/// 1. `xcrun -f swiftc` (honours `DEVELOPER_DIR` and the user's active Xcode).
/// 2. Hard-coded toolchain paths.
static func findSwiftc() throws -> String {
if let xcrun: String = swiftcViaXcrun() {
return xcrun
}
let candidates: [String] = [
"/usr/bin/swiftc",
"/usr/local/bin/swiftc",
"/opt/homebrew/bin/swiftc",
]
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
return path
}
throw LiveCompileError.swiftcNotFound
}
/// `xcrun --show-sdk-path` — returns the macOS SDK path used by the user's
/// active Xcode. `nil` when xcrun is missing or returns non-zero.
static func sdkPathViaXcrun() -> String? {
let xcrunPath: String = "/usr/bin/xcrun"
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: xcrunPath)
process.arguments = ["--show-sdk-path"]
let stdout: Pipe = Pipe()
process.standardOutput = stdout
process.standardError = FileHandle.nullDevice
do {
try process.run()
process.waitUntilExit()
} catch {
return nil
}
guard process.terminationStatus == 0 else { return nil }
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
}
private static func swiftcViaXcrun() -> String? {
let xcrunPath: String = "/usr/bin/xcrun"
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: xcrunPath)
process.arguments = ["-f", "swiftc"]
let stdout: Pipe = Pipe()
process.standardOutput = stdout
// xcrun's stderr is short, but attaching a Pipe without draining it could
// deadlock if it ever filled the OS pipe buffer (~64 KB) while we block on
// stdout. Route to /dev/null at the OS level.
process.standardError = FileHandle.nullDevice
do {
try process.run()
process.waitUntilExit()
} catch {
return nil
}
guard process.terminationStatus == 0 else { return nil }
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
}
// MARK: - swiftc invocation
struct SwiftcResult {
let exitCode: Int32
let stderr: String
}
private static func runSwiftc(executable: String, arguments: [String]) throws -> SwiftcResult {
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: executable)
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.
process.standardOutput = FileHandle.nullDevice
do {
try process.run()
} catch {
throw LiveCompileError.ioFailed(underlying: "swiftc launch failed: \(error)")
}
let stderrData: Data = stderrPipe.fileHandleForReading.readDataToEndOfFile()
process.waitUntilExit()
let stderrString: String = String(data: stderrData, encoding: .utf8) ?? ""
return SwiftcResult(exitCode: process.terminationStatus, stderr: stderrString)
}
}
#endif
@@ -0,0 +1,326 @@
// 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
@@ -0,0 +1,43 @@
// LiveSessionError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
//
// `LiveSession.compileAndRun(_:additive:)` throws this richer error so callers
// see diagnostics pre-mapped to user-snippet coordinates. Other `LiveCompileError`
// cases (toolchain missing, dlopen failure, etc.) pass through under
// `.compilerError`.
#if os(macOS)
public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
/// Snippet failed to compile. `diagnostics` are already line-mapped via the
/// active `SnippetHarness` offset; `underlying` is the raw `swiftc` failure
/// the diagnostics were parsed from.
case snippetCompileFailed(diagnostics: [Diagnostic], underlying: LiveCompileError)
/// Any other `LiveCompileError` case — toolchain missing, dlopen failure,
/// missing entry symbol, IO failure.
case compilerError(LiveCompileError)
public var description: String {
switch self {
case .snippetCompileFailed(let diagnostics, let underlying):
if diagnostics.isEmpty {
return "snippet compile failed:\n\(underlying)"
}
let summary: String = diagnostics.map { diag -> String in
let location: String = diag.line.map { "\($0):\(diag.column)" } ?? "preamble:\(diag.rawLine):\(diag.column)"
return "\(location) \(diag.severity.rawValue): \(diag.message)"
}.joined(separator: "\n")
return "snippet compile failed:\n\(summary)"
case .compilerError(let underlying):
return "live compile error: \(underlying)"
}
}
}
#endif
@@ -0,0 +1,65 @@
// SnippetContext.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
//
// `SnippetContext` is the public API surface the user's snippet talks to. The
// host (via `LiveSession.compileAndRun`) constructs one of these, passes the
// opaque pointer to the snippet's `lyrebird_snippet_entry`, and the preamble
// hands the snippet a typed `context: SnippetContext` reference.
//
// Surface is intentionally minimal for v1 (open question 4 in the plan). Snippets
// read `context.engine` for `SynthesisEngine`, call `context.play(_:)` to add a
// synth that the host will track for re-evaluation cleanup, and report back via
// the test-friendly `reportSampleRate(_:)` / `reportMessage(_:)` helpers.
#if os(macOS)
import LyrebirdSynth
public final class SnippetContext {
/// Owning session. `unowned` because the host guarantees the session
/// outlives the snippet `entry` call (entry is invoked synchronously inside
/// `LiveSession.compileAndRun` under a `withExtendedLifetime` on `self`).
public unowned let session: LiveSession
/// Convenience accessor — same as `session.engine`.
public var engine: SynthesisEngine { session.engine }
init(session: LiveSession) {
self.session = session
}
/// Add `synth` to the engine and track it so the next non-additive
/// re-evaluation (`LiveSession.compileAndRun(_:additive: false)`) removes it.
/// - Returns: `true` if the engine accepted the enqueue; `false` if
/// `engine.add` threw (e.g. cross-engine binding, double-add, queue full).
@discardableResult
public func play(_ synth: any Synthesizer) -> Bool {
do {
try session.engine.add(synth)
session.track(synth)
return true
} catch {
session.lastSnippetMessage = "engine.add failed: \(error)"
return false
}
}
/// 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.
public func reportSampleRate(_ rate: Double) {
session.reportedSampleRate = rate
}
/// Snippet-side hook for test verification: record an arbitrary message
/// back on the session. Lets tests confirm the snippet body executed.
public func reportMessage(_ message: String) {
session.lastSnippetMessage = message
}
}
#endif
@@ -0,0 +1,19 @@
// SnippetEntry.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core
//
// C ABI signature of the snippet's exported entry point.
#if os(macOS)
/// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. Phase
/// 143 will pass a pointer to a `LiveSession` (or harness context) here;
/// Phase 142 only requires that snippets can declare a function matching this
/// signature.
public typealias SnippetEntry = @convention(c) (UnsafeMutableRawPointer?) -> Void
#endif
@@ -0,0 +1,43 @@
// SnippetHarness.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
//
// `SnippetHarness.wrap(userBody:)` produces the full Swift source that
// `LiveCompiler.compile(source:)` feeds to swiftc. The preamble imports the
// modules the snippet needs, declares the C ABI entry, and binds `context: SnippetContext`
// from the opaque pointer the host hands in. The user's body is dropped in as
// the function body.
#if os(macOS)
public enum SnippetHarness {
/// Wraps `userBody` in the standard preamble.
public static func wrap(userBody: String) -> WrappedSnippet {
let preamble: String = """
import LyrebirdSynth
import LyrebirdLiveCompile
@_cdecl("lyrebird_snippet_entry")
public func lyrebird_snippet_entry(_ ctx: UnsafeMutableRawPointer?) {
guard let ctx else { return }
let context = Unmanaged<SnippetContext>.fromOpaque(ctx).takeUnretainedValue()
_ = context
"""
// Count newlines in the preamble: the user's body starts on the next line.
// `components(separatedBy: "\n")` over a string ending in "\n" yields N+1
// elements (the last is empty); offset = count of those elements = lines
// before the user body + 1 (the line on which the body starts).
let lineOffset: Int = preamble.components(separatedBy: "\n").count
let suffix: String = "\n}\n"
let source: String = preamble + userBody + suffix
return WrappedSnippet(source: source, userBodyLineOffset: lineOffset)
}
}
#endif
@@ -0,0 +1,22 @@
// WrappedSnippet.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
//
// Output of `SnippetHarness.wrap(userBody:)`. Carries the full Swift source
// that `swiftc` will compile, plus the 1-based line number on which the user's
// body begins. Phase 144's diagnostic parser subtracts `userBodyLineOffset - 1`
// from each swiftc-reported line so error rows point back at the row the user
// typed.
#if os(macOS)
public struct WrappedSnippet: Equatable {
public let source: String
public let userBodyLineOffset: Int
}
#endif