1.0.0 release

This commit is contained in:
2026-06-01 18:27:40 -07:00
parent b1ab0f102c
commit 1f20fcab20
1151 changed files with 230703 additions and 14 deletions
@@ -0,0 +1,105 @@
// DiagnosticParserTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdLiveCompile
#if os(macOS)
@Suite("DiagnosticParser")
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.
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)
let d: Diagnostic = diagnostics[0]
#expect(d.line == 2)
#expect(d.column == 14)
#expect(d.severity == .error)
#expect(d.message == "cannot find 'foo' in scope")
#expect(d.rawLine == 10)
}
@Test
func diagnosticOnPreambleLineHasNilUserLine() throws {
let stderr: String = "/tmp/Snippet.swift:1:8: error: no such module 'Lyrebird'"
let diagnostics: [Diagnostic] = DiagnosticParser.parse(stderr: stderr, userBodyLineOffset: 9)
try #require(diagnostics.count == 1)
#expect(diagnostics[0].line == nil)
#expect(diagnostics[0].rawLine == 1)
#expect(diagnostics[0].column == 8)
}
@Test
func parsesMultipleDiagnosticsInOrder() throws {
let stderr: String = """
/tmp/Snippet.swift:10:1: warning: result of call to 'foo()' is unused
/tmp/Snippet.swift:11:5: error: cannot convert value of type 'String' to expected argument type 'Int'
/tmp/Snippet.swift:11:5: note: change type to fix
"""
let diagnostics: [Diagnostic] = DiagnosticParser.parse(stderr: stderr, userBodyLineOffset: 9)
try #require(diagnostics.count == 3)
#expect(diagnostics[0].severity == .warning)
#expect(diagnostics[1].severity == .error)
#expect(diagnostics[2].severity == .note)
#expect(diagnostics[0].line == 2)
#expect(diagnostics[1].line == 3)
}
@Test
func ignoresSourceContextAndCaretLines() {
// Real swiftc emits header line then a source-context line then a caret line.
// Only the header should parse.
let stderr: String = """
/tmp/Snippet.swift:10:14: error: cannot find 'foo' in scope
10 | foo()
| `- error: cannot find 'foo' in scope
"""
let diagnostics: [Diagnostic] = DiagnosticParser.parse(stderr: stderr, userBodyLineOffset: 9)
#expect(diagnostics.count == 1)
#expect(diagnostics[0].message == "cannot find 'foo' in scope")
}
@Test
func emptyStderrYieldsEmptyArray() {
#expect(DiagnosticParser.parse(stderr: "", userBodyLineOffset: 9) == [])
}
@Test
func malformedLinesAreIgnored() throws {
let stderr: String = """
this is not a diagnostic
/tmp/Snippet.swift:NOT_A_NUMBER:5: error: bogus
/tmp/Snippet.swift:10:14: error: real error
another junk line
"""
let diagnostics: [Diagnostic] = DiagnosticParser.parse(stderr: stderr, userBodyLineOffset: 9)
try #require(diagnostics.count == 1)
#expect(diagnostics[0].message == "real error")
}
@Test
func endToEndOffsetMatchesSnippetHarness() throws {
// Use the actual harness offset and confirm a fabricated swiftc line that
// points at "line 1 of the user body" maps to user line 1.
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: "let x = 1")
let userBodyLine: Int = wrapped.userBodyLineOffset
let stderr: String = "/tmp/Snippet.swift:\(userBodyLine):5: error: synthetic"
let diagnostics: [Diagnostic] = DiagnosticParser.parse(
stderr: stderr,
userBodyLineOffset: wrapped.userBodyLineOffset
)
try #require(diagnostics.count == 1)
#expect(diagnostics[0].line == 1)
}
}
#endif
@@ -0,0 +1,91 @@
// LiveCompilerTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdLiveCompile
#if os(macOS)
@Suite("LiveCompiler")
struct LiveCompilerTests {
/// Marker buffer the snippet writes to via the `ctx` pointer. One element so
/// we can confirm the entry symbol was actually invoked end-to-end. Held by
/// the test through a withUnsafeMutablePointer scope so the snippet write
/// lands in this process's address space.
@Test
func compileLoadAndInvokeEntry() throws {
// Snippet writes a sentinel `Int32` into the context pointer it gets handed.
let source: String = """
@_cdecl("lyrebird_snippet_entry")
public func lyrebird_snippet_entry(_ ctx: UnsafeMutableRawPointer?) {
guard let ctx else { return }
ctx.assumingMemoryBound(to: Int32.self).pointee = 0x4C425342 // 'LBSB'
}
"""
let snippet: CompiledSnippet = try LiveCompiler.compile(source: source)
#expect(snippet.moduleName.hasPrefix("LBSnippet_"))
#expect(snippet.dylibPath.hasSuffix(".dylib"))
var marker: Int32 = 0
withUnsafeMutablePointer(to: &marker) { ptr in
snippet.entry(UnsafeMutableRawPointer(ptr))
}
#expect(marker == 0x4C425342)
}
@Test
func compileFailureCarriesStderr() {
let source: String = """
@_cdecl("lyrebird_snippet_entry")
public func lyrebird_snippet_entry(_ ctx: UnsafeMutableRawPointer?) {
let _: Int = "this is a string, not an Int"
}
"""
do {
_ = try LiveCompiler.compile(source: source)
Issue.record("expected compileFailed, got success")
} catch let LiveCompileError.compileFailed(exitCode, stderr) {
#expect(exitCode != 0)
#expect(!stderr.isEmpty)
// Don't pin exact wording — Swift compiler diagnostics rephrase between
// toolchain versions. Just confirm the error is present in stderr.
#expect(stderr.lowercased().contains("error"))
} catch {
Issue.record("expected LiveCompileError.compileFailed, got \(error)")
}
}
@Test
func missingEntrySymbolIsDetected() {
// Snippet compiles cleanly but exports no `lyrebird_snippet_entry`.
let source: String = """
public func someUnrelatedFunction() -> Int { 42 }
"""
do {
_ = try LiveCompiler.compile(source: source)
Issue.record("expected entrySymbolMissing, got success")
} catch let LiveCompileError.entrySymbolMissing(symbol, _) {
#expect(symbol == lyrebirdSnippetEntrySymbol)
} catch {
Issue.record("expected LiveCompileError.entrySymbolMissing, got \(error)")
}
}
@Test
func swiftcResolvesToExecutablePath() throws {
let path: String = try LiveCompiler.findSwiftc()
#expect(!path.isEmpty)
// The resolved path must point at an actual executable on disk.
#expect(FileManager.default.isExecutableFile(atPath: path))
}
}
#endif
@@ -0,0 +1,89 @@
// LiveSessionDiagnosticsTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
@testable import LyrebirdLiveCompile
#if os(macOS)
@Suite("LiveSession diagnostics")
struct LiveSessionDiagnosticsTests {
private func makeEngine() -> SynthesisEngine {
SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
}
@Test
func typeErrorYieldsDiagnosticOnUserLine() throws {
let engine: SynthesisEngine = makeEngine()
let session: LiveSession = LiveSession(engine: engine)
// First user-body line forces a Swift type error; line should map to 1.
let body: String = "let _: Int = \"nope\""
do {
_ = try session.compileAndRun(body)
Issue.record("expected snippetCompileFailed")
return
} catch let LiveSessionError.snippetCompileFailed(diagnostics, _) {
let errors: [Diagnostic] = diagnostics.filter { $0.severity == .error }
try #require(!errors.isEmpty)
// The first reported error should land on user line 1.
#expect(errors.first?.line == 1)
} catch {
Issue.record("expected snippetCompileFailed, got \(error)")
}
}
@Test
func compilerErrorWrapsUnderlyingForNonCompileFailures() {
// Force a non-compile error by pointing at a build dir that doesn't exist.
// The Phase 142 compile path still succeeds (a swiftc invocation with -I
// pointing at a missing dir surfaces as `compileFailed` via swiftc's own
// "no such module" — not `compilerError`). Instead, drive a real
// compilerError case by routing through a LiveCompileError that isn't
// `compileFailed`. The simplest reachable non-`compileFailed` path is
// entrySymbolMissing — but a real run with full build dir succeeds.
// We just verify the type LiveSessionError.compilerError exists and is
// representable; behavioural coverage of non-compileFailed cases is
// exercised at the LiveCompiler layer (Phase 142 tests).
let err: LiveSessionError = LiveSessionError.compilerError(.swiftcNotFound)
#expect(String(describing: err).contains("swiftc"))
}
@Test
func diagnosticsContainColumnInformation() throws {
let engine: SynthesisEngine = makeEngine()
let session: LiveSession = LiveSession(engine: engine)
let body: String = "let _: Int = \"nope\""
do {
_ = try session.compileAndRun(body)
Issue.record("expected snippetCompileFailed")
return
} catch let LiveSessionError.snippetCompileFailed(diagnostics, _) {
let errors: [Diagnostic] = diagnostics.filter { $0.severity == .error }
try #require(!errors.isEmpty)
// Column should be > 0 (1-based). We don't pin the exact column —
// swiftc may report on the literal or the assignment depending on
// version — but it must be positive.
#expect((errors.first?.column ?? 0) > 0)
} catch {
Issue.record("expected snippetCompileFailed, got \(error)")
}
}
}
#endif
@@ -0,0 +1,132 @@
// LiveSessionTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
@testable import LyrebirdLiveCompile
#if os(macOS)
@Suite("LiveSession")
struct LiveSessionTests {
/// NRT engine — `start()` is not called. We never pull audio. The session
/// holds a reference; the snippet reads `engine.sampleRate` via `context`.
private func makeEngine() -> SynthesisEngine {
SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
}
@Test
func buildDirDiscoveryFindsLyrebirdDylib() throws {
let buildDir: URL = try #require(LiveSession.currentBuildDir())
let dylib: URL = buildDir.appendingPathComponent("libLyrebird.dylib")
#expect(FileManager.default.fileExists(atPath: dylib.path))
}
@Test
func snippetReadsEngineSampleRateViaContext() throws {
let engine: SynthesisEngine = makeEngine()
let session: LiveSession = LiveSession(engine: engine)
try session.compileAndRun("context.reportSampleRate(context.engine.sampleRate)")
#expect(session.reportedSampleRate == 48_000)
}
@Test
func snippetReportMessageRoundTripsThroughSession() throws {
let engine: SynthesisEngine = makeEngine()
let session: LiveSession = LiveSession(engine: engine)
try session.compileAndRun("context.reportMessage(\"hello from snippet\")")
#expect(session.lastSnippetMessage == "hello from snippet")
}
@Test
func reEvaluationClearsLastMessageStateThenReruns() throws {
let engine: SynthesisEngine = makeEngine()
let session: LiveSession = LiveSession(engine: engine)
try session.compileAndRun("context.reportMessage(\"first\")")
#expect(session.lastSnippetMessage == "first")
try session.compileAndRun("context.reportMessage(\"second\")")
#expect(session.lastSnippetMessage == "second")
}
@Test
func asyncCompileAndRunRoundTripsMessage() async throws {
let engine: SynthesisEngine = makeEngine()
let session: LiveSession = LiveSession(engine: engine)
_ = try await session.compileAndRunAsync(
"context.reportMessage(\"async hello\")"
)
#expect(session.lastSnippetMessage == "async hello")
}
@Test
func asyncCompileFailureSurfacesDiagnosticsThroughSnippetCompileFailed() async {
let engine: SynthesisEngine = makeEngine()
let session: LiveSession = LiveSession(engine: engine)
do {
_ = try await session.compileAndRunAsync("let x: Int = \"nope\"\n")
Issue.record("expected snippetCompileFailed")
} catch let LiveSessionError.snippetCompileFailed(diags, _) {
#expect(diags.isEmpty == false)
#expect(diags.contains(where: { $0.severity == .error }))
} catch {
Issue.record("unexpected error: \(error)")
}
}
@Test
func additiveReEvaluationDoesNotClearTrackedSynths() throws {
let engine: SynthesisEngine = makeEngine()
let session: LiveSession = LiveSession(engine: engine)
// No synths added in either run; just verify the additive branch executes
// without nuking session state.
try session.compileAndRun("context.reportMessage(\"a\")", additive: false)
try session.compileAndRun("context.reportMessage(\"b\")", additive: true)
#expect(session.lastSnippetMessage == "b")
#expect(session.trackedSynthCount == 0)
}
@Test
func swiftcArgsIncludeImportLibrarySearchAndRpathFlags() {
let buildDir: URL = URL(fileURLWithPath: "/tmp/fake-build")
let session: LiveSession = LiveSession(
engine: makeEngine(),
importPaths: [buildDir],
librarySearchPaths: [buildDir],
libraries: ["Lyrebird"],
rpaths: [buildDir]
)
// Indirectly verify makeSwiftcArgs via attempting a compile that will
// fail with the fake paths but expose the flags through the stderr.
do {
_ = try session.compileAndRun("// empty body")
Issue.record("expected compile failure with fake build dir")
} catch let LiveSessionError.snippetCompileFailed(_, underlying) {
guard case .compileFailed(_, let stderr) = underlying else {
Issue.record("expected compileFailed underlying, got \(underlying)")
return
}
// swiftc rejects with "no such module 'Lyrebird'" — that's the proof
// the -I /tmp/fake-build flag was passed and searched.
#expect(stderr.contains("Lyrebird") || stderr.contains("module"))
} catch {
Issue.record("expected snippetCompileFailed, got \(error)")
}
}
}
#endif
@@ -0,0 +1,46 @@
// SnippetHarnessTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdLiveCompile
#if os(macOS)
@Suite("SnippetHarness")
struct SnippetHarnessTests {
@Test
func wrappedSourceContainsPreambleAndUserBody() {
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: "context.reportMessage(\"hello\")")
#expect(wrapped.source.contains("import LyrebirdSynth"))
#expect(wrapped.source.contains("import LyrebirdLiveCompile"))
#expect(wrapped.source.contains("@_cdecl(\"lyrebird_snippet_entry\")"))
#expect(wrapped.source.contains("Unmanaged<SnippetContext>"))
#expect(wrapped.source.contains("context.reportMessage(\"hello\")"))
}
@Test
func userBodyLineOffsetMatchesActualSourceLayout() {
let body: String = "let x = 1"
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: body)
let lines: [String.SubSequence] = wrapped.source.split(separator: "\n", omittingEmptySubsequences: false)
// Line at index `offset - 1` (0-indexed) should be the first line of the body.
let bodyLineIndex: Int = wrapped.userBodyLineOffset - 1
#expect(bodyLineIndex >= 0)
#expect(bodyLineIndex < lines.count)
#expect(String(lines[bodyLineIndex]) == body)
}
@Test
func multilineUserBodyIsPreservedVerbatim() {
let body: String = "let a = 1\nlet b = 2\ncontext.reportMessage(\"\\(a + b)\")"
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: body)
#expect(wrapped.source.contains(body))
}
}
#endif
@@ -0,0 +1,171 @@
// LyrebirdScratchModelTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import Foundation
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@testable import LyrebirdLiveCompileUI
@Suite("LyrebirdScratchModel")
@MainActor
struct LyrebirdScratchModelTests {
/// NRT engine — `start()` is never called. Matches the LiveSession test
/// fixture so we exercise the same compile + dlopen + entry path.
private func makeSession() -> LiveSession {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
return LiveSession(engine: engine)
}
@Test
func defaultPlaceholderMentionsBothShortcuts() {
let placeholder: String = LyrebirdScratchModel.defaultPlaceholder
#expect(placeholder.contains("⌘↩"))
#expect(placeholder.contains("⌘⇧↩"))
#expect(placeholder.contains("context"))
}
@Test
func initSeedsTextAndZeroTrackedSynths() {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "// hi")
#expect(model.text == "// hi")
#expect(model.trackedSynthCount == 0)
#expect(model.diagnostics.isEmpty)
#expect(model.statusMessage.isEmpty)
#expect(model.isCompiling == false)
#expect(model.documentURL == nil)
}
@Test
func runValidSnippetClearsDiagnosticsAndReportsReplaced() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "context.reportMessage(\"hello\")"
)
let ok: Bool = await model.run(additive: false)
#expect(ok)
#expect(model.diagnostics.isEmpty)
#expect(model.statusMessage.contains("replaced"))
#expect(model.statusMessage.contains("Tracked synths: 0"))
#expect(session.lastSnippetMessage == "hello")
#expect(model.isCompiling == false)
}
@Test
func runInvalidSnippetSurfacesUserCoordinateDiagnostics() async throws {
let session: LiveSession = makeSession()
// `let x: Int = "nope"` — guaranteed type-check error on the first row
// of the user body. Phase 144 maps the wrapped-source line back to
// user line 1.
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "let x: Int = \"nope\"\n"
)
let ok: Bool = await model.run(additive: false)
#expect(ok == false)
#expect(model.diagnostics.isEmpty == false)
let first: Diagnostic = try #require(model.diagnostics.first)
#expect(first.severity == .error)
#expect(first.line == 1)
#expect(model.statusMessage.contains("Compile failed"))
#expect(model.isCompiling == false)
}
@Test
func clearTrackedZerosCountAndUpdatesStatus() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "")
await model.run(additive: false)
model.clearTracked()
#expect(model.trackedSynthCount == 0)
#expect(model.statusMessage == "Cleared tracked synths.")
}
@Test
func concurrentRunsCollapseToOneCompile() async {
// Both `async let` tasks invoke `model.run(...)`, but the model is
// `@MainActor`-isolated so they cannot truly overlap. The first call
// sets `isCompiling = true` synchronously before its first `await`;
// when main resumes on the second call's body, the `isCompiling`
// guard sees the flag set and returns `false`. Deterministic with no
// wall-clock dependency.
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "context.reportMessage(\"x\")"
)
async let first: Bool = model.run(additive: false)
async let second: Bool = model.run(additive: false)
let results: [Bool] = await [first, second]
let successes: Int = results.filter { $0 }.count
let rejections: Int = results.filter { !$0 }.count
#expect(successes == 1)
#expect(rejections == 1)
#expect(model.isCompiling == false)
}
@Test
func saveRoundTripsTextAndSetsDocumentURL() throws {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "let a = 1\n")
let url: URL = FileManager.default
.temporaryDirectory
.appendingPathComponent("scratch_\(UUID().uuidString).swift")
defer { try? FileManager.default.removeItem(at: url) }
try model.save(to: url)
#expect(model.documentURL == url)
#expect(model.statusMessage.contains("Saved"))
let onDisk: String = try String(contentsOf: url, encoding: .utf8)
#expect(onDisk == "let a = 1\n")
}
@Test
func loadReplacesTextAndSetsDocumentURL() throws {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "// stale\n")
let url: URL = FileManager.default
.temporaryDirectory
.appendingPathComponent("scratch_\(UUID().uuidString).swift")
defer { try? FileManager.default.removeItem(at: url) }
try "let b = 2\n".write(to: url, atomically: true, encoding: .utf8)
try model.load(from: url)
#expect(model.text == "let b = 2\n")
#expect(model.documentURL == url)
#expect(model.statusMessage.contains("Loaded"))
#expect(model.diagnostics.isEmpty)
}
@Test
func loadFromMissingURLThrowsAndPreservesText() {
let session: LiveSession = makeSession()
let original: String = "// keep me\n"
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: original)
let url: URL = FileManager.default
.temporaryDirectory
.appendingPathComponent("does_not_exist_\(UUID().uuidString).swift")
#expect(throws: (any Error).self) {
try model.load(from: url)
}
#expect(model.text == original)
#expect(model.documentURL == nil)
}
}
#endif