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,134 @@
// ArtifactStagingTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import Foundation
import LyrebirdSynth
@testable import LyrebirdLiveCompile
/// Verifies that a staged artifacts directory is a self-contained, working
/// compile root: a snippet compiled against the staged `-I` / `-L` / rpath
/// succeeds without reaching back into the original build tree.
@Suite("LiveSession artifact staging")
struct ArtifactStagingTests {
/// The dev SPM build dir the tests run from — the staging source.
private func buildDir() -> URL? {
LiveSession.currentBuildDir()
}
@Test func umbrellaHeaderPathParses() {
let map: String = """
module LyrebirdC {
umbrella header "/abs/path/Sources/LyrebirdC/include/LyrebirdC.h"
export *
}
"""
#expect(LiveSession.umbrellaHeaderPath(in: map) == "/abs/path/Sources/LyrebirdC/include/LyrebirdC.h")
}
@Test func umbrellaHeaderPathNilWhenAbsent() {
#expect(LiveSession.umbrellaHeaderPath(in: "module Foo { export * }") == nil)
}
@Test func stageProducesPopulatedRootWithStagedModuleMap() throws {
guard let src: URL = buildDir() else {
// No build dir discoverable (unusual for a test run) — nothing to stage.
return
}
let dest: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
defer { try? FileManager.default.removeItem(at: dest) }
let staged: URL? = LiveSession.stageArtifacts(from: src, to: dest)
#expect(staged == dest)
#expect(LiveSession.isArtifactsDirPopulated(dest))
// The staged C module map must point at the staged header copy, not the
// original absolute path under the source tree.
let stagedMap: URL = dest
.appendingPathComponent("LyrebirdC.build", isDirectory: true)
.appendingPathComponent("module.modulemap", isDirectory: false)
if FileManager.default.fileExists(atPath: stagedMap.path) {
let text: String = try String(contentsOf: stagedMap, encoding: .utf8)
#expect(text.contains("\(dest.path)/LyrebirdC.headers"))
#expect(!text.contains("/Sources/LyrebirdC/include"))
}
}
@Test func refusesToClobberNonStagingDir() throws {
guard let src: URL = buildDir() else { return }
let dest: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: dest, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: dest) }
// A pre-existing file that does NOT look like a staging root.
let precious: URL = dest.appendingPathComponent("precious.txt", isDirectory: false)
try "keep me".write(to: precious, atomically: true, encoding: .utf8)
let staged: URL? = LiveSession.stageArtifacts(from: src, to: dest)
#expect(staged == nil) // refused
#expect(FileManager.default.fileExists(atPath: precious.path)) // untouched
}
@Test func idempotentSecondStageKeepsRoot() throws {
guard let src: URL = buildDir() else { return }
let dest: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
defer { try? FileManager.default.removeItem(at: dest) }
#expect(LiveSession.stageArtifacts(from: src, to: dest) == dest)
// Second call with an unchanged source: still a valid, current root.
#expect(LiveSession.stageArtifacts(from: src, to: dest) == dest)
#expect(LiveSession.isArtifactsDirPopulated(dest))
#expect(LiveSession.stagedDirIsCurrent(dest))
}
@Test func snippetCompilesFromStagedRoot() async throws {
guard let src: URL = buildDir() else { return }
guard LiveSession.hasLyrebirdDylib(in: src) else {
// Xcode-SPM layout (no dylib) — the staged-link path under test needs
// the bare-SPM dylib present; skip when absent.
return
}
let dest: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
defer { try? FileManager.default.removeItem(at: dest) }
guard let staged: URL = LiveSession.stageArtifacts(from: src, to: dest) else {
Issue.record("staging produced no root")
return
}
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
// Point the session ONLY at the staged root — no original build dir.
let session: LiveSession = await LiveSession(
engine: engine,
attachScope: false,
importPaths: [staged, staged.appendingPathComponent("Modules")],
librarySearchPaths: [staged],
libraries: ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
rpaths: [staged]
)
// A trivial snippet that touches the LyrebirdSynth API proves the module
// resolves from the staged root.
try await session.compileAndRunAsync("context.play { OscSin.Audio(freq: 440) * 0.1 }")
await session.clearTracked()
}
}
#endif
@@ -15,8 +15,11 @@ struct DiagnosticParserTests {
@Test
func parsesSingleErrorAtUserBodyLine() throws {
// Wrapped snippet preamble is 8 lines; user body starts at line 9.
// swiftc reports an error on wrapped line 10 → maps to user line 2.
// Representative offset: for a preamble whose user body starts at line 9,
// a swiftc error on wrapped line 10 maps to user line 2. (This tests the
// parser's arithmetic directly; the actual harness offset — which shifts
// when the preamble changes — is exercised by
// `endToEndOffsetMatchesSnippetHarness` below.)
let stderr: String = "/tmp/Snippet.swift:10:14: error: cannot find 'foo' in scope"
let diagnostics: [Diagnostic] = DiagnosticParser.parse(stderr: stderr, userBodyLineOffset: 9)
try #require(diagnostics.count == 1)
@@ -16,6 +16,9 @@ struct SnippetHarnessTests {
@Test
func wrappedSourceContainsPreambleAndUserBody() {
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: "context.reportMessage(\"hello\")")
// Foundation so snippets can use `pow`, `sin`, `Date`, … without an import
// (a snippet can't declare one — its body is inside the entry function).
#expect(wrapped.source.contains("import Foundation"))
#expect(wrapped.source.contains("import LyrebirdSynth"))
#expect(wrapped.source.contains("import LyrebirdLiveCompile"))
#expect(wrapped.source.contains("@_cdecl(\"lyrebird_snippet_entry\")"))
@@ -15,6 +15,34 @@ import LyrebirdSynth
@Suite("Snippet scheduled loop")
struct SnippetScheduledLoopTests {
@Test func snippetCanUseFoundationMath() throws {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
controlBlockSize: 64,
sampleRate: 44_100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
let session: LiveSession = LiveSession(engine: engine, attachScope: false)
try engine.start()
// `pow` / `sin` come from Foundation, which the harness preamble imports —
// a snippet can't add the import itself. This would fail to compile
// ("cannot find 'pow' in scope") without it.
let snippet: String = """
let semitone: Double = pow(2.0, 1.0 / 12.0)
let freq: Double = 440.0 * semitone
context.play { OscSin.Audio(freq: freq) * (0.1 * sin(0.0) + 0.1) }
context.reportMessage("math ok \\(freq)")
"""
try session.compileAndRun(snippet)
#expect(session.lastSnippetMessage?.hasPrefix("math ok") == true)
session.clearTracked()
}
@Test func loopSchedulesTenSelfFreeingTones() throws {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
@@ -0,0 +1,52 @@
// SwiftFormatterTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import Foundation
@testable import LyrebirdLiveCompile
@Suite("SwiftFormatter")
struct SwiftFormatterTests {
@Test func formatsMessySource() throws {
guard SwiftFormatter.isAvailable else { return } // no toolchain formatter — skip
let messy: String = "let x=1\nstruct Foo{let a:Int}\n"
let formatted: String = try SwiftFormatter.format(source: messy)
// Canonical spacing appears; the mangled originals are gone.
#expect(formatted.contains("let x = 1"))
#expect(!formatted.contains("let x=1"))
#expect(!formatted.contains("struct Foo"))
}
@Test func alreadyFormattedIsStable() throws {
guard SwiftFormatter.isAvailable else { return }
let clean: String = "let x = 1\n"
let once: String = try SwiftFormatter.format(source: clean)
let twice: String = try SwiftFormatter.format(source: once)
#expect(once == twice) // idempotent
}
@Test func parseErrorThrowsFormatFailed() {
guard SwiftFormatter.isAvailable else { return }
// Unbalanced brace — swift-format should exit non-zero.
let broken: String = "func f( {\n"
var caught: SwiftFormatterError?
do {
_ = try SwiftFormatter.format(source: broken)
} catch let error as SwiftFormatterError {
caught = error
} catch {
Issue.record("unexpected error type: \(error)")
}
guard case .formatFailed = caught else {
Issue.record("expected .formatFailed, got \(String(describing: caught))")
return
}
}
}
#endif
@@ -0,0 +1,48 @@
// ScratchModelFormatTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@testable import LyrebirdLiveCompileUI
@Suite("LyrebirdScratchModel formatting")
@MainActor
struct ScratchModelFormatTests {
private func makeModel(text: String) -> LyrebirdScratchModel {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
return LyrebirdScratchModel(session: LiveSession(engine: engine, attachScope: false), initialText: text)
}
@Test func formatRewritesMessyBufferAndLogs() async {
guard SwiftFormatter.isAvailable else { return } // no toolchain formatter — skip
let model: LyrebirdScratchModel = makeModel(text: "let x=1\n")
await model.formatBuffer()
#expect(model.text.contains("let x = 1"))
#expect(model.consoleEntries.contains { $0.kind == .info })
}
@Test func formatBlankBufferIsNoOp() async {
let model: LyrebirdScratchModel = makeModel(text: " \n")
let before: String = model.text
await model.formatBuffer()
#expect(model.text == before)
}
}
#endif
@@ -0,0 +1,98 @@
// ScratchModelRenderTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import Foundation
import AudioToolbox
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@testable import LyrebirdLiveCompileUI
@Suite("LyrebirdScratchModel render-to-file")
@MainActor
struct ScratchModelRenderTests {
private func makeModel(text: String) -> LyrebirdScratchModel {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
return LyrebirdScratchModel(session: LiveSession(engine: engine, attachScope: false), initialText: text)
}
@Test func rendersWholeBufferToCAF() async throws {
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
defer { try? FileManager.default.removeItem(at: url) }
let duration: Double = 0.25
let ok: Bool = await model.renderToFile(url: url, duration: duration)
#expect(ok)
#expect(FileManager.default.fileExists(atPath: url.path))
#expect(model.consoleEntries.contains { $0.kind == .info })
// The CAF should hold roughly `duration` seconds at the engine's rate.
var fileRef: ExtAudioFileRef?
#expect(ExtAudioFileOpenURL(url as CFURL, &fileRef) == noErr)
guard let fileRef: ExtAudioFileRef = fileRef else {
Issue.record("could not open rendered CAF")
return
}
defer { ExtAudioFileDispose(fileRef) }
var frames: Int64 = 0
var size: UInt32 = UInt32(MemoryLayout<Int64>.size)
#expect(ExtAudioFileGetProperty(fileRef, kExtAudioFileProperty_FileLengthFrames, &size, &frames) == noErr)
// Allow a block of slack either way.
let expected: Double = duration * 48_000
#expect(Double(frames) > expected - 128 && Double(frames) < expected + 512)
}
@Test func rendersSelectionWhenPresent() async {
// Whole buffer has two statements; select only the first and render it.
let model: LyrebirdScratchModel = makeModel(
text: "context.play { OscSin.Audio(freq: 440) * 0.1 }\ncontext.play { OscSin.Audio(freq: 880) * 0.1 }")
model.updateSelection("context.play { OscSin.Audio(freq: 440) * 0.1 }")
#expect(model.hasSelection)
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
defer { try? FileManager.default.removeItem(at: url) }
let ok: Bool = await model.renderToFile(url: url, duration: 0.1)
#expect(ok)
#expect(FileManager.default.fileExists(atPath: url.path))
}
@Test func nonPositiveDurationFails() async {
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
defer { try? FileManager.default.removeItem(at: url) }
let ok: Bool = await model.renderToFile(url: url, duration: 0)
#expect(!ok)
#expect(!FileManager.default.fileExists(atPath: url.path))
#expect(model.consoleEntries.contains { $0.kind == .error })
}
@Test func blankBufferRendersNothing() async {
let model: LyrebirdScratchModel = makeModel(text: " \n")
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
defer { try? FileManager.default.removeItem(at: url) }
let ok: Bool = await model.renderToFile(url: url, duration: 0.1)
#expect(!ok)
#expect(!FileManager.default.fileExists(atPath: url.path))
}
}
#endif