v1.4.0 release: live-coding scratch editor, interpreted Graph DSL, ClosureSynthesizer + SampleLoop
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
// GraphDSLDiagnosticMapperTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdGraphDSLEmbedded
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@Suite("GraphDSLDiagnosticMapper")
|
||||
struct GraphDSLDiagnosticMapperTests {
|
||||
|
||||
@Test
|
||||
func parseErrorMapsSpanToLineAndColumn() {
|
||||
// Offset 4 in "abc\nX" → line 2, column 1 (the char after the newline).
|
||||
let span: DSLSpan = DSLSpan.point(4)
|
||||
let error: DSLParseError = DSLParseError(kind: .unexpectedCharacter("%"), span: span)
|
||||
let diags: [Diagnostic] = GraphDSLDiagnosticMapper.diagnostics(for: error, source: "abc\n%")
|
||||
#expect(diags.count == 1)
|
||||
#expect(diags[0].line == 2)
|
||||
#expect(diags[0].column == 1)
|
||||
#expect(diags[0].severity == .error)
|
||||
#expect(diags[0].message.contains("unexpected"))
|
||||
}
|
||||
|
||||
@Test
|
||||
func firstColumnOfFirstLineIsOneOne() {
|
||||
let error: DSLParseError = DSLParseError(kind: .unclosedParen, span: DSLSpan.point(0))
|
||||
let diags: [Diagnostic] = GraphDSLDiagnosticMapper.diagnostics(for: error, source: "OscSin(")
|
||||
#expect(diags[0].line == 1)
|
||||
#expect(diags[0].column == 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
func buildErrorHasNoLine() {
|
||||
let error: DSLBuildError = DSLBuildError.unknownBuiltin("Nope")
|
||||
let diags: [Diagnostic] = GraphDSLDiagnosticMapper.diagnostics(for: error, source: "Nope()")
|
||||
#expect(diags.count == 1)
|
||||
#expect(diags[0].line == nil)
|
||||
#expect(diags[0].message.contains("Nope"))
|
||||
}
|
||||
|
||||
@Test
|
||||
func offsetPastEndClampsToFinalPosition() {
|
||||
let error: DSLParseError = DSLParseError(kind: .unclosedParen, span: DSLSpan.point(1_000))
|
||||
let diags: [Diagnostic] = GraphDSLDiagnosticMapper.diagnostics(for: error, source: "ab\ncd")
|
||||
// Two lines, second is "cd": clamps to line 2, column 3 (past 'd').
|
||||
#expect(diags[0].line == 2)
|
||||
#expect(diags[0].column == 3)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -86,6 +86,48 @@ struct LiveCompilerTests {
|
||||
// The resolved path must point at an actual executable on disk.
|
||||
#expect(FileManager.default.isExecutableFile(atPath: path))
|
||||
}
|
||||
|
||||
// MARK: - Prewarm
|
||||
|
||||
/// Module-resolution args pointing at the built Lyrebird modules, mirroring
|
||||
/// `LiveSession.makeModuleResolutionArgs()`.
|
||||
private func moduleResolutionArgs() -> [String] {
|
||||
let importPaths: [URL] = LiveSession.defaultImportPaths()
|
||||
var args: [String] = []
|
||||
for path: URL in importPaths {
|
||||
args += ["-I", path.path]
|
||||
}
|
||||
for url: URL in LiveSession.discoverClangModuleMaps(in: importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
/// The prewarm type-checks `import LyrebirdSynth` / `import LyrebirdLiveCompile`;
|
||||
/// with real module-resolution args it must succeed (cold ~2–3 s the first
|
||||
/// time it builds the `.pcm`). This exercises the mechanism directly, not
|
||||
/// behind `LiveSession.prewarm()`'s error-swallowing `try?`.
|
||||
@Test
|
||||
func prewarmSucceedsWithModuleResolutionArgs() throws {
|
||||
try LiveCompiler.prewarm(extraSwiftcArgs: moduleResolutionArgs())
|
||||
}
|
||||
|
||||
@Test
|
||||
func prewarmThrowsWhenModulesUnresolvable() {
|
||||
// No `-I`: `import LyrebirdSynth` cannot be found → type-check fails.
|
||||
do {
|
||||
try LiveCompiler.prewarm(extraSwiftcArgs: [])
|
||||
Issue.record("expected prewarm to throw with no module paths")
|
||||
} catch let LiveCompileError.compileFailed(exitCode, stderr) {
|
||||
#expect(exitCode != 0)
|
||||
#expect(!stderr.isEmpty)
|
||||
} catch {
|
||||
Issue.record("expected LiveCompileError.compileFailed, got \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
// LiveSessionGraphDSLTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
import LyrebirdGraphDSLEmbedded
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@MainActor
|
||||
@Suite("LiveSession graph-DSL")
|
||||
struct LiveSessionGraphDSLTests {
|
||||
|
||||
/// NRT engine — `start()` is never called. The DSL graphs use only
|
||||
/// oscillators (no `LyrebirdBuffer`), so no engine run cycle is needed and
|
||||
/// the buffer-teardown race is avoided.
|
||||
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 anonymousStatementIsTracked() throws {
|
||||
let session: LiveSession = makeSession()
|
||||
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
|
||||
#expect(session.trackedSynthCount == 1)
|
||||
#expect(session.slotCount == 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
func multipleAnonymousStatementsEachTrack() throws {
|
||||
let session: LiveSession = makeSession()
|
||||
try session.runGraphDSL("OscSin(freq: 440) * 0.1\nOscSawtooth(freq: 55) * 0.2")
|
||||
#expect(session.trackedSynthCount == 2)
|
||||
}
|
||||
|
||||
@Test
|
||||
func namedStatementGoesToASlotNotTracked() throws {
|
||||
let session: LiveSession = makeSession()
|
||||
try session.runGraphDSL("bass = OscSawtooth(freq: 55) * 0.2")
|
||||
#expect(session.trackedSynthCount == 0)
|
||||
#expect(session.slotCount == 1)
|
||||
#expect(session.slotNames == ["bass"])
|
||||
}
|
||||
|
||||
@Test
|
||||
func nonAdditiveReRunReplacesAnonymousSynths() throws {
|
||||
let session: LiveSession = makeSession()
|
||||
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
|
||||
try session.runGraphDSL("OscSin(freq: 220) * 0.1")
|
||||
#expect(session.trackedSynthCount == 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
func additiveReRunKeepsPriorSynths() throws {
|
||||
let session: LiveSession = makeSession()
|
||||
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
|
||||
try session.runGraphDSL("OscSin(freq: 220) * 0.1", additive: true)
|
||||
#expect(session.trackedSynthCount == 2)
|
||||
}
|
||||
|
||||
@Test
|
||||
func namedSlotSurvivesNonAdditiveReRun() throws {
|
||||
let session: LiveSession = makeSession()
|
||||
try session.runGraphDSL("bass = OscSawtooth(freq: 55) * 0.2")
|
||||
// A plain anonymous re-run should not disturb the slot.
|
||||
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
|
||||
#expect(session.slotCount == 1)
|
||||
#expect(session.trackedSynthCount == 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
func parseErrorThrowsGraphDSLFailedWithLine() {
|
||||
let session: LiveSession = makeSession()
|
||||
// `%` starts no token — a lex error on the second line.
|
||||
#expect {
|
||||
try session.runGraphDSL("OscSin(freq: 1)\n%%%")
|
||||
} throws: { error in
|
||||
guard case LiveSessionError.graphDSLFailed(let diags, _) = error else { return false }
|
||||
return diags.count == 1 && diags[0].line == 2
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func buildErrorThrowsGraphDSLFailedWithoutLine() {
|
||||
let session: LiveSession = makeSession()
|
||||
#expect {
|
||||
try session.runGraphDSL("NotAGenerator(freq: 1)")
|
||||
} throws: { error in
|
||||
guard case LiveSessionError.graphDSLFailed(let diags, _) = error else { return false }
|
||||
return diags.count == 1 && diags[0].line == nil
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func failedEvaluationLeavesPriorGraphUntouched() throws {
|
||||
let session: LiveSession = makeSession()
|
||||
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
|
||||
#expect(session.trackedSynthCount == 1)
|
||||
// A broken non-additive re-run must NOT clear the playing graph — the
|
||||
// program is built before any engine mutation.
|
||||
#expect(throws: LiveSessionError.self) {
|
||||
try session.runGraphDSL("Nope(freq: 1)")
|
||||
}
|
||||
#expect(session.trackedSynthCount == 1)
|
||||
}
|
||||
|
||||
/// Engine whose `pendingQueue` holds only `capacity` (power-of-two) adds
|
||||
/// before it fills — and it is never processed, so it never drains. Lets a
|
||||
/// test drive a deterministic mid-run `.pendingQueueFull`.
|
||||
private func makeSmallQueueSession(capacity: Int) -> LiveSession {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: capacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LiveSession(engine: engine)
|
||||
}
|
||||
|
||||
@Test
|
||||
func engineRejectionIsPerStatementNotAbortAll() {
|
||||
// A small pending queue fills partway through eight statements. Continue-
|
||||
// on-error attempts EVERY statement, so `tracked + failed == 8` and more
|
||||
// than one failed. An abort-on-first-error loop would stop at the first
|
||||
// rejection, leaving `tracked + failed < 8` and exactly one diagnostic.
|
||||
let session: LiveSession = makeSmallQueueSession(capacity: 4)
|
||||
let count: Int = 8
|
||||
let source: String = (0..<count)
|
||||
.map { "OscSin(freq: \(100 + $0)) * 0.1" }
|
||||
.joined(separator: "\n")
|
||||
var thrownDiags: [Diagnostic] = []
|
||||
do {
|
||||
try session.runGraphDSL(source)
|
||||
Issue.record("expected a pendingQueueFull failure")
|
||||
} catch let LiveSessionError.graphDSLFailed(diags, _) {
|
||||
thrownDiags = diags
|
||||
} catch {
|
||||
Issue.record("unexpected error: \(error)")
|
||||
}
|
||||
#expect(session.trackedSynthCount + thrownDiags.count == count)
|
||||
#expect(thrownDiags.count >= 2)
|
||||
#expect(session.trackedSynthCount >= 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
func resetAllClearsDSLTrackedAndSlots() throws {
|
||||
let session: LiveSession = makeSession()
|
||||
try session.runGraphDSL("bass = OscSawtooth(freq: 55) * 0.2\nOscSin(freq: 440) * 0.1")
|
||||
#expect(session.trackedSynthCount == 1)
|
||||
#expect(session.slotCount == 1)
|
||||
session.resetAll()
|
||||
#expect(session.trackedSynthCount == 0)
|
||||
#expect(session.slotCount == 0)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -95,6 +95,158 @@ struct LiveSessionTests {
|
||||
#expect(session.trackedSynthCount == 1)
|
||||
}
|
||||
|
||||
/// Bare-graph `context.play { … }` — no `SynthesizerBase` subclass — adds
|
||||
/// and tracks a synth, exercising the `ClosureSynthesizer` forwarder.
|
||||
@Test
|
||||
func closurePlayAddsAndTracksBareGraph() async throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
#expect(session.trackedSynthCount == 0)
|
||||
_ = try await session.compileAndRunAsync(
|
||||
"context.play { OscSin.Audio(freq: 440, mul: 0.1) }"
|
||||
)
|
||||
#expect(session.trackedSynthCount == 1)
|
||||
}
|
||||
|
||||
// MARK: - Named slots
|
||||
|
||||
@Test
|
||||
func assignSlotReplacesInPlaceKeepingOneVoice() throws {
|
||||
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||
let first: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
|
||||
try session.engine.add(first)
|
||||
session.assignSlot("bass", synth: first)
|
||||
#expect(session.slotCount == 1)
|
||||
#expect(session.slotNames == ["bass"])
|
||||
// Re-assigning the same name replaces the voice — count stays 1.
|
||||
let second: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
|
||||
try session.engine.add(second)
|
||||
session.assignSlot("bass", synth: second)
|
||||
#expect(session.slotCount == 1)
|
||||
// Slots are separate from the anonymous tracked list.
|
||||
#expect(session.trackedSynthCount == 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
func clearSlotRemovesNamedSlotOnly() throws {
|
||||
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||
let a: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
|
||||
let b: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
|
||||
try session.engine.add(a); session.assignSlot("a", synth: a)
|
||||
try session.engine.add(b); session.assignSlot("b", synth: b)
|
||||
#expect(session.slotCount == 2)
|
||||
#expect(session.clearSlot("a") == true)
|
||||
#expect(session.slotCount == 1)
|
||||
#expect(session.slotNames == ["b"])
|
||||
// Clearing an empty slot is a no-op.
|
||||
#expect(session.clearSlot("missing") == false)
|
||||
#expect(session.slotCount == 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
func clearSlotsRemovesAllSlots() throws {
|
||||
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||
let a: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
|
||||
let b: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
|
||||
try session.engine.add(a); session.assignSlot("a", synth: a)
|
||||
try session.engine.add(b); session.assignSlot("b", synth: b)
|
||||
#expect(session.slotCount == 2)
|
||||
session.clearSlots()
|
||||
#expect(session.slotCount == 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
func clearTrackedLeavesSlotsIntact() throws {
|
||||
// Slots must survive a non-additive re-evaluation (that is the whole
|
||||
// point) — `clearTracked()` clears only the anonymous list.
|
||||
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||
let anon: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
|
||||
let slotted: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
|
||||
try session.engine.add(anon); session.track(anon)
|
||||
try session.engine.add(slotted); session.assignSlot("bass", synth: slotted)
|
||||
#expect(session.trackedSynthCount == 1)
|
||||
#expect(session.slotCount == 1)
|
||||
session.clearTracked()
|
||||
#expect(session.trackedSynthCount == 0)
|
||||
#expect(session.slotCount == 1)
|
||||
}
|
||||
|
||||
// MARK: - Swap quantization
|
||||
|
||||
@Test
|
||||
func quantizedSwapSchedulesAndReportsPendingBeat() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
session.swapClock = LyrebirdClock(engine: engine, bpm: 120)
|
||||
session.swapQuantize = .nextBeat
|
||||
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
|
||||
#expect(session.slotCount == 1)
|
||||
// Offline clock sits at beat 0, so the swap targets beat 1 and is pending.
|
||||
#expect(session.pendingSwapBeat == 1.0)
|
||||
}
|
||||
|
||||
@Test
|
||||
func immediateSwapReportsNoPendingBeat() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
// No clock set → immediate regardless of the quantize mode.
|
||||
session.swapQuantize = .nextBeat
|
||||
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
|
||||
#expect(session.slotCount == 1)
|
||||
#expect(session.pendingSwapBeat == nil)
|
||||
}
|
||||
|
||||
/// A running engine: two quantized swaps of the same slot must leave exactly
|
||||
/// one voice in the node tree once the scheduled events have fired.
|
||||
@Test
|
||||
func quantizedSwapReplaceEndsWithOneVoiceInTree() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
session.swapClock = LyrebirdClock(engine: engine, bpm: 120)
|
||||
session.swapQuantize = .nextBeat
|
||||
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
|
||||
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.2 })
|
||||
#expect(session.slotCount == 1)
|
||||
// Beat 1 @ 120 bpm / 48 kHz = 24000 samples; 64-sample blocks.
|
||||
for _: Int in 0..<500 { engine.processBlock(inputSamples: []) }
|
||||
#expect(engine.synthesizerCount == 1)
|
||||
}
|
||||
|
||||
/// Regression: clearing a slot *before* its scheduled quantized add fires
|
||||
/// must not orphan the pending voice. The removal is scheduled no earlier
|
||||
/// than the add, so the add and remove cancel out — the tree ends empty.
|
||||
@Test
|
||||
func clearSlotsBeforeScheduledSwapFiresLeavesNoOrphan() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
try engine.start()
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
session.swapClock = LyrebirdClock(engine: engine, bpm: 120)
|
||||
session.swapQuantize = .nextBeat
|
||||
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
|
||||
session.clearSlots()
|
||||
#expect(session.slotCount == 0)
|
||||
for _: Int in 0..<500 { engine.processBlock(inputSamples: []) }
|
||||
#expect(engine.synthesizerCount == 0)
|
||||
}
|
||||
|
||||
/// End-to-end through the real swiftc pipeline: `context.play(slot:) { }`
|
||||
/// installs one voice, and a non-additive re-run of the same slot replaces
|
||||
/// it in place (still one voice) — the slot survives the non-additive clear.
|
||||
@Test
|
||||
func closureSlotPlayReplacesAcrossReevaluations() async throws {
|
||||
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||
_ = try await session.compileAndRunAsync(
|
||||
"context.play(slot: \"bass\") { OscSin.Audio(freq: 110, mul: 0.1) }"
|
||||
)
|
||||
#expect(session.slotCount == 1)
|
||||
#expect(session.trackedSynthCount == 0)
|
||||
_ = try await session.compileAndRunAsync(
|
||||
"context.play(slot: \"bass\") { OscSin.Audio(freq: 220, mul: 0.1) }"
|
||||
)
|
||||
#expect(session.slotCount == 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
func asyncCompileFailureSurfacesDiagnosticsThroughSnippetCompileFailed() async {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
@@ -122,6 +274,102 @@ struct LiveSessionTests {
|
||||
#expect(session.trackedSynthCount == 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
func discoverSPMModuleMapsMatchesTopLevelBuildDirMapsAndDedups() throws {
|
||||
// Fixture mirroring the `swift build` layout: a C target's generated map
|
||||
// sits at `<buildDir>/<Target>.build/module.modulemap`, while a Swift
|
||||
// target's map is one level deeper (`.build/include/module.modulemap`)
|
||||
// and must NOT be picked up.
|
||||
let fm: FileManager = FileManager.default
|
||||
let root: URL = fm.temporaryDirectory
|
||||
.appendingPathComponent("spm-maps-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? fm.removeItem(at: root) }
|
||||
|
||||
let cTargetMap: URL = root
|
||||
.appendingPathComponent("LyrebirdC.build", isDirectory: true)
|
||||
.appendingPathComponent("module.modulemap")
|
||||
let swiftTargetMap: URL = root
|
||||
.appendingPathComponent("LyrebirdSynth.build", isDirectory: true)
|
||||
.appendingPathComponent("include", isDirectory: true)
|
||||
.appendingPathComponent("module.modulemap")
|
||||
let nonBuildMap: URL = root
|
||||
.appendingPathComponent("Modules", isDirectory: true)
|
||||
.appendingPathComponent("module.modulemap")
|
||||
for url: URL in [cTargetMap, swiftTargetMap, nonBuildMap] {
|
||||
try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try "module X {}".write(to: url, atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
// Pass the same path twice to exercise dedup.
|
||||
let found: [URL] = LiveSession.discoverSPMModuleMaps(in: [root, root])
|
||||
#expect(found.count == 1)
|
||||
// Suffix match, not full-path equality: the temp dir resolves through
|
||||
// the `/var` → `/private/var` symlink, so `contentsOfDirectory` returns
|
||||
// a differently-prefixed but equivalent path.
|
||||
#expect(found.first?.path.hasSuffix("LyrebirdC.build/module.modulemap") == true)
|
||||
}
|
||||
|
||||
// MARK: - Session reset + snippet accounting
|
||||
|
||||
@Test
|
||||
func resetAllClearsTrackedAndSlots() throws {
|
||||
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||
let anon: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
|
||||
let slotted: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
|
||||
try session.engine.add(anon); session.track(anon)
|
||||
try session.engine.add(slotted); session.assignSlot("bass", synth: slotted)
|
||||
#expect(session.trackedSynthCount == 1)
|
||||
#expect(session.slotCount == 1)
|
||||
session.resetAll()
|
||||
#expect(session.trackedSynthCount == 0)
|
||||
#expect(session.slotCount == 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
func resetAllClearsPendingSwap() throws {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
session.swapClock = LyrebirdClock(engine: engine, bpm: 120)
|
||||
session.swapQuantize = .nextBeat
|
||||
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
|
||||
#expect(session.pendingSwapBeat == 1.0)
|
||||
session.resetAll()
|
||||
#expect(session.pendingSwapBeat == nil)
|
||||
#expect(session.slotCount == 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
func loadedSnippetCountGrowsPerCompile() async throws {
|
||||
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||
#expect(session.loadedSnippetCount == 0)
|
||||
_ = try await session.compileAndRunAsync("context.reportMessage(\"a\")")
|
||||
#expect(session.loadedSnippetCount == 1)
|
||||
_ = try await session.compileAndRunAsync("context.reportMessage(\"b\")")
|
||||
#expect(session.loadedSnippetCount == 2)
|
||||
}
|
||||
|
||||
// MARK: - Module-cache prewarm
|
||||
|
||||
@Test
|
||||
func prewarmCompletesAndSetsFlag() async {
|
||||
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||
#expect(session.isPrewarmed == false)
|
||||
// Await the detached prewarm task (a real `swiftc -typecheck` that warms
|
||||
// swiftc's default module cache — cold ~2–3 s the first time).
|
||||
await session.prewarm().value
|
||||
#expect(session.isPrewarmed == true)
|
||||
}
|
||||
|
||||
@Test
|
||||
func prewarmIsIdempotentAfterCompletion() async {
|
||||
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||
await session.prewarm().value
|
||||
#expect(session.isPrewarmed == true)
|
||||
// A second call is a no-op (already warmed) and returns immediately.
|
||||
await session.prewarm().value
|
||||
#expect(session.isPrewarmed == true)
|
||||
}
|
||||
|
||||
@Test
|
||||
func swiftcArgsIncludeImportLibrarySearchAndRpathFlags() {
|
||||
let buildDir: URL = URL(fileURLWithPath: "/tmp/fake-build")
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// SnippetCompletionServiceTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
/// Integration tests that spawn the toolchain's real `sourcekit-lsp` and drive
|
||||
/// it end-to-end. Serialised (`.serialized`) because each launches a server
|
||||
/// subprocess; kept out of the fast unit path by their inherent latency.
|
||||
@MainActor
|
||||
@Suite("SnippetCompletionService", .serialized)
|
||||
struct SnippetCompletionServiceTests {
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
/// Member completion after `OscSin.` resolves the generator's nested types —
|
||||
/// proof that sourcekit-lsp sees `LyrebirdSynth` via the generated
|
||||
/// `compile_commands.json`.
|
||||
@Test func completesGeneratorMembers() async throws {
|
||||
let service: SnippetCompletionService = SnippetCompletionService(session: makeSession())
|
||||
try await service.start()
|
||||
defer { service.shutdownSynchronously() }
|
||||
|
||||
let body: String = "let x = OscSin."
|
||||
let items: [LSPCompletionItem] = try await service.completions(
|
||||
userBody: body, line: 0, character: body.count)
|
||||
|
||||
let labels: Set<String> = Set(items.map { $0.label })
|
||||
#expect(labels.contains("Audio"), "expected OscSin.Audio; got \(labels.sorted())")
|
||||
#expect(labels.contains("Control"), "expected OscSin.Control; got \(labels.sorted())")
|
||||
}
|
||||
|
||||
/// The injected `context` binding is in scope for the snippet body, so its
|
||||
/// members (`play`, `engine`, …) complete.
|
||||
@Test func completesContextMembers() async throws {
|
||||
let service: SnippetCompletionService = SnippetCompletionService(session: makeSession())
|
||||
try await service.start()
|
||||
defer { service.shutdownSynchronously() }
|
||||
|
||||
let body: String = "context."
|
||||
let items: [LSPCompletionItem] = try await service.completions(
|
||||
userBody: body, line: 0, character: body.count)
|
||||
|
||||
let labels: Set<String> = Set(items.map { $0.label })
|
||||
#expect(labels.contains("engine"), "expected context.engine; got \(labels.sorted())")
|
||||
#expect(labels.contains { $0.hasPrefix("play") },
|
||||
"expected a context.play member; got \(labels.sorted())")
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,68 @@
|
||||
// SourceKitLSPClientTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@Suite("SourceKitLSPClient")
|
||||
struct SourceKitLSPClientTests {
|
||||
|
||||
/// A server that never answers must make a request FAIL (`timedOut`) within
|
||||
/// the timeout — not hang. Uses `/bin/sleep` as a stand-in process that stays
|
||||
/// alive but speaks no LSP, so the `initialize` request in `start()` times
|
||||
/// out. Regression guard for the task-group/continuation deadlock where a
|
||||
/// dropped-but-not-resumed continuation left `request(...)` awaiting forever.
|
||||
@Test func requestTimesOutOnUnresponsiveServer() async {
|
||||
let client: SourceKitLSPClient = SourceKitLSPClient(
|
||||
executableURL: URL(fileURLWithPath: "/bin/sleep"),
|
||||
arguments: ["3600"],
|
||||
requestTimeout: 0.5
|
||||
)
|
||||
let start: Date = Date()
|
||||
await #expect(throws: SourceKitLSPError.self) {
|
||||
try await client.start(rootURI: "file:///tmp")
|
||||
}
|
||||
let elapsed: TimeInterval = Date().timeIntervalSince(start)
|
||||
// Must resolve near the 0.5 s timeout, not hang (the old bug never returned).
|
||||
#expect(elapsed < 5.0, "start() took \(elapsed)s — expected a prompt timeout")
|
||||
client.shutdown()
|
||||
}
|
||||
|
||||
/// A server that launches then exits immediately (EOF on stdout) must fail
|
||||
/// an in-flight request promptly rather than hang the full timeout — the
|
||||
/// reader marks the client not-running and fails pending requests on EOF.
|
||||
/// `/usr/bin/true` exits 0 at once.
|
||||
@Test func serverExitFailsRequestPromptly() async {
|
||||
let client: SourceKitLSPClient = SourceKitLSPClient(
|
||||
executableURL: URL(fileURLWithPath: "/usr/bin/true"),
|
||||
requestTimeout: 10.0
|
||||
)
|
||||
let start: Date = Date()
|
||||
await #expect(throws: SourceKitLSPError.self) {
|
||||
try await client.start(rootURI: "file:///tmp")
|
||||
}
|
||||
let elapsed: TimeInterval = Date().timeIntervalSince(start)
|
||||
#expect(elapsed < 5.0, "server-exit took \(elapsed)s — expected a prompt failure, not a timeout")
|
||||
client.shutdown()
|
||||
}
|
||||
|
||||
/// Launching a non-existent executable surfaces `.launchFailed` rather than
|
||||
/// crashing or hanging.
|
||||
@Test func launchFailureIsReported() async {
|
||||
let client: SourceKitLSPClient = SourceKitLSPClient(
|
||||
executableURL: URL(fileURLWithPath: "/nonexistent/sourcekit-lsp-xyz"),
|
||||
requestTimeout: 0.5
|
||||
)
|
||||
await #expect(throws: SourceKitLSPError.self) {
|
||||
try await client.start(rootURI: "file:///tmp")
|
||||
}
|
||||
client.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,51 @@
|
||||
// SwapQuantizeTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@MainActor
|
||||
@Suite("SwapQuantize")
|
||||
struct SwapQuantizeTests {
|
||||
|
||||
/// Offline engine that never processes a block, so `clock.currentBeat`
|
||||
/// stays at 0 — target beats are then deterministic.
|
||||
private func makeClock(bpm: Double = 120) -> LyrebirdClock {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LyrebirdClock(engine: engine, bpm: bpm)
|
||||
}
|
||||
|
||||
@Test func immediateHasNoTargetBeat() {
|
||||
#expect(SwapQuantize.immediate.targetBeat(clock: makeClock()) == nil)
|
||||
}
|
||||
|
||||
@Test func nextBeatTargetsUpcomingWholeBeat() {
|
||||
#expect(SwapQuantize.nextBeat.targetBeat(clock: makeClock()) == 1.0)
|
||||
}
|
||||
|
||||
@Test func nextBarTargetsUpcomingBarBoundary() {
|
||||
#expect(SwapQuantize.nextBar(beatsPerBar: 4).targetBeat(clock: makeClock()) == 4.0)
|
||||
}
|
||||
|
||||
@Test func nextBarClampsNonPositiveBeatsPerBar() {
|
||||
// beatsPerBar <= 0 clamps to 1, behaving like `.nextBeat`.
|
||||
#expect(SwapQuantize.nextBar(beatsPerBar: 0).targetBeat(clock: makeClock()) == 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user