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

259 lines
11 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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 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. `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).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 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