b6fdee8bfc
Consolidated release: the cross-platform Linux port (engine, generators, CLI, REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive. See RELEASES.md and LINUX_README.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
299 lines
13 KiB
Swift
299 lines
13 KiB
Swift
// LiveCompiler.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
// LyrebirdLiveCompile — 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 are handled by the harness and session
|
||
// layers). macOS/Linux only — iOS cannot exec swiftc.
|
||
|
||
import Foundation
|
||
#if canImport(Darwin)
|
||
import Darwin // dlopen / dlsym / dlerror
|
||
#elseif canImport(Glibc)
|
||
import Glibc // dlopen / dlsym / dlerror on Linux
|
||
#endif
|
||
|
||
#if os(macOS) || os(Linux)
|
||
|
||
/// 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"
|
||
|
||
/// Platform shared-library extension: `dylib` (Mach-O) on macOS, `so` (ELF) on
|
||
/// Linux. A snippet is `swiftc -emit-library`'d to `lib<name>.<ext>`, and the
|
||
/// resident Lyrebird library is `libLyrebirdDynamic.<ext>`.
|
||
#if os(macOS)
|
||
let livecompileSharedLibraryExtension: String = "dylib"
|
||
#else
|
||
let livecompileSharedLibraryExtension: String = "so"
|
||
#endif
|
||
|
||
/// Search `$PATH` for an executable named `name`, returning the first hit or
|
||
/// `nil`. Covers toolchains installed outside the hard-coded locations — most
|
||
/// notably a swiftly install (`~/.local/share/swiftly/bin`) on Linux, which puts
|
||
/// both `swiftc` and `sourcekit-lsp` on `$PATH` but not in `/usr/bin`.
|
||
func livecompileExecutableOnPath(_ name: String) -> String? {
|
||
guard let pathEnv: String = ProcessInfo.processInfo.environment["PATH"] else { return nil }
|
||
for dir: Substring in pathEnv.split(separator: ":") where !dir.isEmpty {
|
||
let base: String = String(dir)
|
||
let candidate: String = base.hasSuffix("/") ? base + name : base + "/" + name
|
||
if FileManager.default.isExecutableFile(atPath: candidate) {
|
||
return candidate
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
/// One-shot snippet compiler. Stateless — every `compile(source:)` allocates a
|
||
/// fresh temp dir, shared-library name, and `dlopen` handle.
|
||
public enum LiveCompiler {
|
||
|
||
static var sharedLibraryExtension: String { livecompileSharedLibraryExtension }
|
||
|
||
/// Compile `source` to a dylib and resolve the snippet entry symbol.
|
||
///
|
||
/// - Parameters:
|
||
/// - source: Full Swift source, including the `@_cdecl("lyrebird_snippet_entry")`
|
||
/// entry. `SnippetHarness` wraps user input in a preamble that provides
|
||
/// this; direct 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).\(sharedLibraryExtension)").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. An executable `swiftc` on `$PATH` — covers a swiftly install
|
||
/// (`~/.local/share/swiftly/bin`) and any Linux toolchain layout that
|
||
/// isn't in the hard-coded list.
|
||
/// 3. Hard-coded toolchain paths.
|
||
static func findSwiftc() throws -> String {
|
||
if let xcrun: String = swiftcViaXcrun() {
|
||
return xcrun
|
||
}
|
||
if let onPath: String = swiftcOnPath() {
|
||
return onPath
|
||
}
|
||
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
|
||
}
|
||
|
||
/// Search `$PATH` for an executable `swiftc`. Returns the first hit, or `nil`.
|
||
static func swiftcOnPath() -> String? {
|
||
livecompileExecutableOnPath("swiftc")
|
||
}
|
||
|
||
/// `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 the modes used
|
||
// here (-emit-library and -typecheck). 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)
|
||
}
|
||
|
||
// MARK: - Module-cache prewarm
|
||
|
||
/// Build the Clang/Swift module cache (the precompiled `.pcm` for the large
|
||
/// `LyrebirdSynth` interface and its dependencies) by **type-checking** a
|
||
/// trivial source that imports the same modules a real snippet does.
|
||
///
|
||
/// The cold cache build costs ~2–3 s and otherwise lands on the user's first
|
||
/// ⌘↩; running this once at session start (off-main) moves that cost into the
|
||
/// background, so the first real ``compile(source:extraSwiftcArgs:)`` hits a
|
||
/// warm cache (~0.1 s). `-typecheck` is enough — the `.pcm`s are produced
|
||
/// during import resolution, before codegen/link — and avoids emitting or
|
||
/// `dlopen`ing a dylib.
|
||
///
|
||
/// - Parameter extraSwiftcArgs: The module-resolution flags (`-I`,
|
||
/// `-Xcc -fmodule-map-file=…`) that point at the same modules the real
|
||
/// compile uses, so both warm the same (default) module cache.
|
||
/// `LiveSession` supplies these via its module-resolution args.
|
||
/// - Throws: `LiveCompileError` for a missing toolchain, IO failure, or a
|
||
/// non-zero type-check exit.
|
||
public static func prewarm(extraSwiftcArgs: [String]) throws {
|
||
let swiftc: String = try findSwiftc()
|
||
let id: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
|
||
let workDir: URL = FileManager.default.temporaryDirectory
|
||
.appendingPathComponent("LyrebirdLiveCompile-prewarm-\(id)", isDirectory: true)
|
||
let sourcePath: String = workDir.appendingPathComponent("Prewarm.swift").path
|
||
let source: String = "import LyrebirdSynth\nimport LyrebirdLiveCompile\n"
|
||
do {
|
||
try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true)
|
||
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
|
||
} catch {
|
||
throw LiveCompileError.ioFailed(underlying: "\(error)")
|
||
}
|
||
defer { try? FileManager.default.removeItem(at: workDir) }
|
||
|
||
var arguments: [String] = ["-typecheck", "-module-name", "LBPrewarm_\(id)"]
|
||
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)
|
||
}
|
||
}
|
||
}
|
||
|
||
#endif
|