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

211 lines
8.5 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 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 -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