v1.5.0 release: LyrebirdRandom + Live Scratch editor

LyrebirdRandom scalar distribution sampling (seedable value type + shared
Random) with DistributionKind.sample dispatcher. Live Scratch editor: rename to
LyrebirdScratch, App Support artifact staging, Format Code (⌥⌘F), Render to File
(⌥⌘R offline CAF), line-number gutter, manual completion, Foundation in snippets,
scroll-jump fix, scheduling/NRT docs.
This commit is contained in:
2026-07-22 07:53:12 -07:00
parent 8519cabe42
commit 62b2f5dbec
43 changed files with 2249 additions and 376 deletions
@@ -0,0 +1,16 @@
// ArtifactStagingError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
/// Errors raised while staging compile artifacts into Application Support.
enum ArtifactStagingError: Error {
/// The staging destination already exists, is non-empty, and does not look
/// like a prior staging root — refused rather than clobbered.
case destinationNotAStagingRoot(String)
}
#endif
@@ -809,19 +809,36 @@ public final class LiveSession: @unchecked Sendable {
)
}
/// Prefer a populated staged artifacts dir (App Support, ungated) over the
/// SPM build dir (which lives under `~/Documents` in a dev checkout). Hosts
/// that want staging call ``stageArtifacts(from:to:)`` before constructing
/// the session; these defaults then resolve to the staged copy.
private static func resolvedArtifactsDir() -> URL? {
// Prefer the staged dir only when it is populated AND current relative to
// the live build dir — so a stale copy left by a different build (or a
// partial stage) never masquerades as the resolved artifacts for a host
// that did not itself stage.
if let staged: URL = stagedArtifactsDir(),
isArtifactsDirPopulated(staged),
stagedDirIsCurrent(staged) {
return staged
}
return currentBuildDir()
}
public static func defaultImportPaths() -> [URL] {
guard let buildDir: URL = currentBuildDir() else { return [] }
return [buildDir, buildDir.appendingPathComponent("Modules")]
guard let dir: URL = resolvedArtifactsDir() else { return [] }
return [dir, dir.appendingPathComponent("Modules")]
}
public static func defaultLibrarySearchPaths() -> [URL] {
guard let buildDir: URL = currentBuildDir() else { return [] }
return [buildDir]
guard let dir: URL = resolvedArtifactsDir() else { return [] }
return [dir]
}
public static func defaultRpaths() -> [URL] {
guard let buildDir: URL = currentBuildDir() else { return [] }
return [buildDir]
guard let dir: URL = resolvedArtifactsDir() else { return [] }
return [dir]
}
}
@@ -0,0 +1,321 @@
// LiveSessionArtifactStaging.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Snippet compilation needs the Lyrebird module artifacts (swiftmodules, the
// Lyrebird dylibs, and the C-shim Clang module map + its umbrella header). In a
// dev checkout those live in the SPM build dir under `~/Documents`, so a
// non-sandboxed host reading them — and the `swiftc` it spawns reading them —
// trips the macOS "wants to access your Documents folder" TCC gate.
//
// Staging copies the minimal artifact set into
// `~/Library/Application Support/LyrebirdScratch/LiveCompile/`, an ungated
// location, and rewrites the C module map's absolute umbrella-header path to the
// staged copy. The default `-I` / `-L` / rpath resolution then prefers the
// staged dir, so a shipped app compiles snippets without ever touching a
// permission-gated folder.
import Foundation
#if os(macOS)
extension LiveSession {
/// Name of the artifacts subdirectory a host may ship inside its app bundle
/// (`<App>.app/Contents/Resources/<name>`). Staging prefers this over the
/// dev build dir when present, so a shipped app never reads outside its
/// bundle or App Support.
public static let bundledArtifactsDirName: String = "LyrebirdArtifacts"
/// `~/Library/Application Support/LyrebirdScratch/LiveCompile` — the ungated
/// destination for staged compile artifacts. `nil` only if the Application
/// Support directory can't be resolved.
public static func stagedArtifactsDir() -> URL? {
guard let base: URL = FileManager.default.urls(
for: .applicationSupportDirectory,
in: .userDomainMask
).first else { return nil }
return base
.appendingPathComponent("LyrebirdScratch", isDirectory: true)
.appendingPathComponent("LiveCompile", isDirectory: true)
}
/// Whether `dir` is a usable compile root: it has a `Modules/` directory
/// holding at least one `.swiftmodule`.
public static func isArtifactsDirPopulated(_ dir: URL) -> Bool {
let modules: URL = dir.appendingPathComponent("Modules", isDirectory: true)
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
at: modules,
includingPropertiesForKeys: nil
) else { return false }
return entries.contains { $0.pathExtension == "swiftmodule" }
}
/// Where to stage FROM. Prefers a `LyrebirdArtifacts` directory shipped in
/// the app bundle's `Resources` (self-contained, never under a gated
/// folder); falls back to the dev SPM build dir.
public static func artifactSourceDir() -> URL? {
if let resources: URL = Bundle.main.resourceURL {
let bundled: URL = resources.appendingPathComponent(
bundledArtifactsDirName,
isDirectory: true
)
if isArtifactsDirPopulated(bundled) { return bundled }
}
return currentBuildDir()
}
/// Copy the minimal artifact set from `source` (default: ``artifactSourceDir()``)
/// into `destination` (default: ``stagedArtifactsDir()``), rewriting the C
/// module map to point at a staged copy of its umbrella header. Idempotent:
/// skips the copy when the destination is already newer than the source.
/// Best-effort — returns the staged dir on success, `nil` on any failure or
/// when no source/destination could be resolved.
///
/// - Note: In a dev checkout the source is the build dir under `~/Documents`,
/// so the one-time copy still reads that gated folder; every subsequent
/// launch reuses the staged copy and reads only App Support. A shipped app
/// whose `Resources/LyrebirdArtifacts` is populated never reads a gated
/// folder at all.
@discardableResult
public static func stageArtifacts(
from source: URL? = nil,
to destination: URL? = nil
) -> URL? {
guard let dest: URL = destination ?? stagedArtifactsDir() else { return nil }
guard let src: URL = source ?? artifactSourceDir() else { return nil }
do {
try stageArtifactsThrowing(from: src, to: dest)
} catch {
return nil
}
return isArtifactsDirPopulated(dest) ? dest : nil
}
// MARK: - Implementation
static let stageReceiptName: String = ".stage-receipt"
/// Slack in the receipt-vs-source stamp comparison. A `Date` stores seconds
/// since 2001; the receipt records `timeIntervalSince1970`, so reconstructing
/// it adds then subtracts the ~978-million-second epoch offset — floating-
/// point arithmetic at that magnitude perturbs the sub-second fraction, so a
/// bit-exact `>=` can spuriously read "stale" (the string encoding itself is
/// exact; the loss is in the epoch conversion, not the receipt). mtime
/// staleness needs no sub-second resolution — a rebuild moves mtimes by far
/// more than a second.
private static let stageStampToleranceSeconds: TimeInterval = 1.0
/// Whether a staged dir at `dest` is current relative to the artifact source
/// it would stage from. When no source is discoverable (a shipped app with no
/// build dir and no bundled artifacts), any populated staged dir is trusted.
/// Otherwise the receipt must be at or after the source's newest artifact —
/// so a staged copy left by a *different* build (or a partial stage that never
/// wrote a receipt) is ignored and the resolver falls back to the build dir.
/// Compared against ``artifactSourceDir()`` (not the build dir directly) so
/// the base matches what ``stageArtifacts(from:to:)`` actually copies from.
static func stagedDirIsCurrent(_ dest: URL) -> Bool {
guard let source: URL = artifactSourceDir() else { return true }
guard let prior: Date = stageReceiptDate(dest.appendingPathComponent(stageReceiptName, isDirectory: false))
else { return false }
return prior.timeIntervalSince1970 >= sourceArtifactStamp(source).timeIntervalSince1970 - stageStampToleranceSeconds
}
private static func stageArtifactsThrowing(from src: URL, to dest: URL) throws {
let fm: FileManager = FileManager.default
let srcStamp: Date = sourceArtifactStamp(src)
// Up to date? A populated dest whose receipt is at or after the source's
// newest artifact mtime needs no re-copy.
if isArtifactsDirPopulated(dest),
let prior: Date = stageReceiptDate(dest.appendingPathComponent(stageReceiptName, isDirectory: false)),
prior.timeIntervalSince1970 >= srcStamp.timeIntervalSince1970 - stageStampToleranceSeconds {
return
}
// Refuse to clobber a directory we did not create: an existing, non-empty
// `dest` must look like a prior staging root (a receipt or a `Modules/`
// dir) before we replace it. Guards a typo'd `to:` from wiping real data.
if fm.fileExists(atPath: dest.path), !isReplaceableStagingDest(dest) {
throw ArtifactStagingError.destinationNotAStagingRoot(dest.path)
}
// Build everything in a private sibling temp dir, then atomically swap it
// over `dest`. `dest` is therefore only ever fully-complete or absent — a
// failed/partial stage never leaves a dir that *looks* valid, and two
// stagers racing the same `dest` can't observe a half-written tree.
let staging: URL = dest.deletingLastPathComponent()
.appendingPathComponent(".\(dest.lastPathComponent).staging-\(UUID().uuidString)", isDirectory: true)
try fm.createDirectory(at: staging, withIntermediateDirectories: true)
defer { try? fm.removeItem(at: staging) }
// 1. Swift modules.
let srcModules: URL = src.appendingPathComponent("Modules", isDirectory: true)
if fm.fileExists(atPath: srcModules.path) {
try fm.copyItem(at: srcModules, to: staging.appendingPathComponent("Modules", isDirectory: true))
}
// 2. Lyrebird dylibs (the snippet links these and bakes an rpath here;
// at dlopen dyld matches the already-loaded install name, so the copy is
// a link-time search target, not a second loaded image).
for dylib: URL in lyrebirdDylibs(in: src) {
try? fm.copyItem(at: dylib, to: staging.appendingPathComponent(dylib.lastPathComponent))
}
// 3. C module maps + their umbrella headers. Files are written under the
// temp `staging` dir, but the umbrella path baked into each map must
// reference the FINAL `dest` (where they land after the atomic swap) —
// the temp dir is deleted.
stageClangModuleMaps(from: src, writeInto: staging, finalRoot: dest)
// Receipt: store the source stamp so the next call can skip an unchanged
// source.
let stampText: String = String(srcStamp.timeIntervalSince1970)
try stampText.write(
to: staging.appendingPathComponent(stageReceiptName, isDirectory: false),
atomically: true,
encoding: .utf8
)
// Re-check the clobber guard immediately before the swap: the copy phase
// above is a window in which something could have materialized a
// non-staging directory at `dest`. Holding the guard across the whole
// operation, not just at entry, keeps `replaceItemAt` from silently
// wiping a dir we would have refused.
if fm.fileExists(atPath: dest.path), !isReplaceableStagingDest(dest) {
throw ArtifactStagingError.destinationNotAStagingRoot(dest.path)
}
// Atomic swap into place.
if fm.fileExists(atPath: dest.path) {
_ = try fm.replaceItemAt(dest, withItemAt: staging)
} else {
try fm.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true)
do {
try fm.moveItem(at: staging, to: dest)
} catch {
// A concurrent stager may have created `dest` between the check
// and the move; if it is now a valid root, treat as success.
guard isArtifactsDirPopulated(dest) else { throw error }
}
}
}
/// The Lyrebird dylibs present at the top level of `src`.
private static func lyrebirdDylibs(in src: URL) -> [URL] {
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
at: src,
includingPropertiesForKeys: nil
) else { return [] }
return entries.filter {
$0.pathExtension == "dylib" && $0.lastPathComponent.hasPrefix("libLyrebird")
}
}
/// A `dest` is safe to replace when it doesn't exist, is empty, or looks like
/// a prior staging root (has a receipt or a `Modules/` dir).
private static func isReplaceableStagingDest(_ dest: URL) -> Bool {
let fm: FileManager = FileManager.default
guard fm.fileExists(atPath: dest.path) else { return true }
if fm.fileExists(atPath: dest.appendingPathComponent(stageReceiptName).path) { return true }
if fm.fileExists(atPath: dest.appendingPathComponent("Modules").path) { return true }
let contents: [URL] = (try? fm.contentsOfDirectory(at: dest, includingPropertiesForKeys: nil)) ?? []
return contents.isEmpty
}
/// For each `<Module>.build/module.modulemap` under `src` whose umbrella
/// header exists, copy the header's `include` directory into
/// `writeInto/<Module>.headers` and write a staged map whose umbrella path
/// points at `finalRoot/<Module>.headers/<header>` — the location those files
/// occupy after the caller's atomic swap of `writeInto` onto `finalRoot`.
/// Best-effort per map: a map with no resolvable umbrella header, or one that
/// fails to copy, is skipped without aborting the rest.
private static func stageClangModuleMaps(from src: URL, writeInto staging: URL, finalRoot dest: URL) {
let fm: FileManager = FileManager.default
guard let entries: [URL] = try? fm.contentsOfDirectory(
at: src,
includingPropertiesForKeys: nil
) else { return }
for buildDir: URL in entries where buildDir.pathExtension == "build" {
let map: URL = buildDir.appendingPathComponent("module.modulemap", isDirectory: false)
guard fm.fileExists(atPath: map.path),
let text: String = try? String(contentsOf: map, encoding: .utf8),
let umbrella: String = umbrellaHeaderPath(in: text)
else { continue }
let headerURL: URL = URL(fileURLWithPath: umbrella)
guard fm.fileExists(atPath: headerURL.path) else { continue }
let includeDir: URL = headerURL.deletingLastPathComponent()
let moduleName: String = buildDir.deletingPathExtension().lastPathComponent
let headerName: String = headerURL.lastPathComponent
// Files go under the temp staging dir…
let stagedHeaders: URL = staging.appendingPathComponent("\(moduleName).headers", isDirectory: true)
let stagedMapDir: URL = staging.appendingPathComponent(buildDir.lastPathComponent, isDirectory: true)
// …but the baked umbrella path names their final resting place.
let finalHeader: URL = dest
.appendingPathComponent("\(moduleName).headers", isDirectory: true)
.appendingPathComponent(headerName, isDirectory: false)
let rewritten: String = text.replacingOccurrences(of: umbrella, with: finalHeader.path)
do {
try? fm.removeItem(at: stagedHeaders)
try fm.copyItem(at: includeDir, to: stagedHeaders)
try fm.createDirectory(at: stagedMapDir, withIntermediateDirectories: true)
try rewritten.write(
to: stagedMapDir.appendingPathComponent("module.modulemap", isDirectory: false),
atomically: true,
encoding: .utf8
)
} catch {
continue
}
}
}
/// Extract the path inside `umbrella header "..."` from a Clang module map.
static func umbrellaHeaderPath(in modulemap: String) -> String? {
guard let marker: Range<String.Index> = modulemap.range(of: "umbrella header") else { return nil }
let after: Substring = modulemap[marker.upperBound...]
guard let open: String.Index = after.firstIndex(of: "\"") else { return nil }
let afterOpen: Substring = after[after.index(after: open)...]
guard let close: String.Index = afterOpen.firstIndex(of: "\"") else { return nil }
return String(afterOpen[..<close])
}
/// Newest modification date among the artifacts we actually copy — a cheap
/// staleness proxy that avoids walking the whole build tree. Derives the
/// dylib set from the same wildcard scan the copy step uses, so a new/renamed
/// Lyrebird dylib can't slip past the freshness check.
///
/// It does not probe the C module map or its umbrella header directly: a
/// header edit forces `swift build` to rebuild the downstream swiftmodules
/// too, which moves `Modules/`'s mtime — so a header change is caught
/// transitively. (A hand-edited header with no rebuild would not re-stage,
/// but that state never occurs from a normal build.)
private static func sourceArtifactStamp(_ src: URL) -> Date {
let fm: FileManager = FileManager.default
var newest: Date = Date.distantPast
var probes: [URL] = [src.appendingPathComponent("Modules", isDirectory: true)]
probes += lyrebirdDylibs(in: src)
for probe: URL in probes {
if let attrs: [FileAttributeKey: Any] = try? fm.attributesOfItem(atPath: probe.path),
let date: Date = attrs[.modificationDate] as? Date,
date > newest {
newest = date
}
}
return newest
}
private static func stageReceiptDate(_ receipt: URL) -> Date? {
guard let text: String = try? String(contentsOf: receipt, encoding: .utf8),
let interval: TimeInterval = TimeInterval(text.trimmingCharacters(in: .whitespacesAndNewlines))
else { return nil }
return Date(timeIntervalSince1970: interval)
}
}
#endif
@@ -27,6 +27,7 @@ public enum SnippetHarness {
/// `compileAndRun` is `@MainActor`).
public static func wrap(userBody: String) -> WrappedSnippet {
let preamble: String = """
import Foundation
import LyrebirdSynth
import LyrebirdLiveCompile
@@ -0,0 +1,140 @@
// SwiftFormatter.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — snippet source formatting.
//
// Shells out to the toolchain's `swift-format` (the same way `LiveCompiler`
// shells to `swiftc`) to pretty-print a snippet. macOS only — iOS cannot exec
// subprocesses. Writes the source to a temp file and runs `swift-format format
// <file>`, capturing stdout — avoids the write-stdin/read-stdout pipe deadlock
// a streaming approach risks on large output.
import Foundation
#if os(macOS)
/// Stateless `swift-format` wrapper.
public enum SwiftFormatter {
/// Format `source` and return the pretty-printed result. Runs synchronously
/// (spawns `swift-format`); call off the main thread.
///
/// - Parameter source: Swift source to format. Top-level snippet code is
/// accepted — `swift-format` formats whatever parses.
/// - Returns: The formatted source.
/// - Throws: ``SwiftFormatterError`` for a missing tool, a non-zero exit
/// (typically a parse error), or an I/O failure.
public static func format(source: String) throws -> String {
let tool: String = try findSwiftFormat()
let id: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
let workDir: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LyrebirdSwiftFormat-\(id)", isDirectory: true)
let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path
do {
try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true)
} catch {
throw SwiftFormatterError.ioFailed("\(error)")
}
// Register cleanup as soon as the dir exists, so a later write failure
// doesn't leak it.
defer { try? FileManager.default.removeItem(at: workDir) }
do {
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
} catch {
throw SwiftFormatterError.ioFailed("\(error)")
}
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: tool)
process.arguments = ["format", sourcePath]
let stdoutPipe: Pipe = Pipe()
let stderrPipe: Pipe = Pipe()
process.standardOutput = stdoutPipe
process.standardError = stderrPipe
do {
try process.run()
} catch {
throw SwiftFormatterError.ioFailed("swift-format launch failed: \(error)")
}
// Drain stdout AND stderr concurrently before waiting. `swift-format` can
// emit both a large formatted buffer and (on a broken snippet) a large
// diagnostic stream; reading them sequentially would deadlock if the
// stream we aren't reading yet fills its OS pipe buffer while the child
// blocks writing to it.
let outHandle: FileHandle = stdoutPipe.fileHandleForReading
let errHandle: FileHandle = stderrPipe.fileHandleForReading
let group: DispatchGroup = DispatchGroup()
let drainQueue: DispatchQueue = DispatchQueue(
label: "net.realizedsound.lyrebird.swift-format-drain",
attributes: .concurrent
)
var outData: Data = Data()
var errData: Data = Data()
group.enter()
drainQueue.async { outData = outHandle.readDataToEndOfFile(); group.leave() }
group.enter()
drainQueue.async { errData = errHandle.readDataToEndOfFile(); group.leave() }
group.wait()
process.waitUntilExit()
guard process.terminationStatus == 0 else {
let stderr: String = String(data: errData, encoding: .utf8) ?? ""
throw SwiftFormatterError.formatFailed(exitCode: process.terminationStatus, stderr: stderr)
}
guard let formatted: String = String(data: outData, encoding: .utf8) else {
throw SwiftFormatterError.ioFailed("swift-format produced non-UTF8 output")
}
return formatted
}
/// Whether a `swift-format` executable is available on this machine.
public static var isAvailable: Bool {
(try? findSwiftFormat()) != nil
}
// MARK: - Tool resolution
/// First-success search: `xcrun -f swift-format`, then hard-coded paths.
static func findSwiftFormat() throws -> String {
if let viaXcrun: String = swiftFormatViaXcrun() {
return viaXcrun
}
let candidates: [String] = [
"/usr/bin/swift-format",
"/usr/local/bin/swift-format",
"/opt/homebrew/bin/swift-format",
]
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
return path
}
throw SwiftFormatterError.toolNotFound
}
private static func swiftFormatViaXcrun() -> 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", "swift-format"]
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
}
}
#endif
@@ -0,0 +1,20 @@
// SwiftFormatterError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
/// Errors raised while formatting snippet source with `swift-format`.
public enum SwiftFormatterError: Error {
/// No `swift-format` executable could be located (no Xcode / toolchain, or
/// an older toolchain that predates the bundled formatter).
case toolNotFound
/// `swift-format` exited non-zero — usually a parse error in the source.
case formatFailed(exitCode: Int32, stderr: String)
/// A filesystem or process I/O failure.
case ioFailed(String)
}
#endif