2 Commits

Author SHA1 Message Date
josh abc64df4d7 v1.4.1 release: Learning Swift for Lyrebird intro guide
Documentation-only release. Adds docs/learning-swift/ — a four-part
introduction to Swift for Lyrebird users coming from SuperCollider,
Max/MSP, Csound, etc. (Hello World, Swift basics & best practices,
types & functional programming, Xcode/packages/debugging). Linked from
README.md and LYREBIRD_START_HERE.md. See RELEASES.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 12:10:00 -07:00
josh 38d2107f64 v1.4.0 release: live-coding scratch editor, interpreted Graph DSL, ClosureSynthesizer + SampleLoop 2026-07-20 10:02:49 -07:00
110 changed files with 15345 additions and 11454 deletions
+3
View File
@@ -60,6 +60,7 @@ These guards catch classes of regression that **`swift build` / `swift test` str
**Generators**
- Generator protocol + DemandGenerator → `docs/protocols/generator.md`
- **Implementing a new Generator** → `docs/protocols/writing-generators.md` (§13 = shared helpers)
- Inline custom per-sample DSP / single-sample feedback without a new Generator type (`SampleLoop` — pre-allocated output, typed `inout` feedback state, channel inference + broadcast) → `Sources/Lyrebird/Generators/Core/SampleLoop.swift`
- Built-in generator catalog → `docs/stdlib/generators.md`
- Multi-channel / `outputChannelCount` / channel-aware operators → `docs/stdlib/multichannel.md`
- Musical math (MIDI↔Hz, dB, intervals) → `docs/stdlib/generators.md` (LyrebirdMusicMath section)
@@ -92,9 +93,11 @@ These guards catch classes of regression that **`swift build` / `swift test` str
**UI**
- LyrebirdUI / parameter binding → `docs/ui/gui-system.md`
- Live-compile scratchpad (`LyrebirdScratchView`, `LyrebirdLiveCompile`, `LyrebirdLiveCompileUI`) → `LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md`. **Lives in the separate `LiveCompile/` SwiftPM sub-package** (Phase 167) — cross-package dependency forces `libLyrebirdLiveCompile.dylib` to dynamic-link `libLyrebird.dylib` instead of statically embedding it, eliminating the ObjC class double-registration crash that aborted full `swift test` runs in the single-package layout. Build sub-package with `(cd LiveCompile && swift build)` / `(cd LiveCompile && swift test)`.
- Interpreted graph-DSL (`LyrebirdGraphDSL` target — cross-platform, no swiftc) + its code-gen (`Tools/DSLRegistryGen`, separate SwiftPM package so swift-syntax stays out of the main build; run `scripts/generate-dsl-registry.sh`, committed output, `--check` drift guard) → `docs/tooling/graph-dsl-design.md`. Registry (`Sources/LyrebirdGraphDSL/Generated/GeneratedDSLRegistry.swift`) is generated from generator init signatures — regenerate + commit after changing a public generator init. In progress (LC-8); language/parser not yet built.
**Diagnostics**
- User-visible messages (`LyrebirdMessage`, `LyrebirdMessageCenter`, `LyrebirdMessageView` / Banner) + node-tree mirror (`NodeTreeMirror`, `NodeTreeSnapshot`, `LyrebirdNodeTreeView`) → `docs/diagnostics-guide.md`
- Developer-side debugging (per-instance RT debug tap `SynthesizerBase.debugTap`, `GeneratorBase.debugTag`, LLDB breakpoint recipes for inspecting a live voice / generator) → `Sources/Lyrebird/Lyrebird.docc/Debugging.md`
**Planning**
- What to build next → `docs/00-working-order.md`
+5 -2
View File
@@ -149,10 +149,12 @@ A macOS app that compiles a typed Swift snippet against the live engine at ⌘
- Type arbitrary Swift code in the editor pane. The snippet body has `context: SnippetContext` in scope.
- `context.engine` — the host `SynthesisEngine`, started at launch.
- `context.play(synth)` — adds a `Synthesizer` to the engine and tracks it for cleanup.
- `context.play { <graph> }` — plays a bare generator graph, no `SynthesizerBase` subclass needed.
- `context.play(slot: "name") { <graph> }` — plays into a named slot; re-running that slot replaces just that voice in place while the rest keeps playing (persists across a ⌘↩ run).
- `context.reportMessage(_:)` — writes a string back to the host status bar.
- **⌘↩** — compile and replace. Removes synths from the previous run, compiles the snippet via `swiftc -emit-library`, `dlopen`s the resulting dylib, calls `lyrebird_snippet_entry`.
- **⌘↩** — compile and replace. Removes the previous run's anonymous synths (named slots persist), compiles the snippet via `swiftc -emit-library`, `dlopen`s the resulting dylib, calls `lyrebird_snippet_entry`.
- **⌘⇧↩** — compile additive. Prior synths stay in the engine.
- **Clear Synths** toolbar button — removes all tracked synths immediately.
- **Clear Synths** toolbar button — full reset: removes all tracked synths *and* every named slot immediately.
**Why this app cannot be sandboxed:**
`swiftc` is a subprocess (`posix_spawn`); the output dylib is unsigned. Both are blocked by the macOS App Sandbox. This app is a direct-distribution developer tool only. The entitlements file (`LyrebirdScratchDemo.entitlements`) sets `com.apple.security.cs.disable-library-validation = true` to let Hardened Runtime `dlopen` the unsigned snippet dylib.
@@ -200,6 +202,7 @@ final class MySynth: SynthesizerBase {
| Topic | Doc |
|-------|-----|
| New to Swift? Intro for Lyrebird users | `docs/learning-swift/README.md` |
| Engine setup and Core Audio | `docs/engine/synthesis-engine.md` |
| Bus system, In/Out generators | `docs/engine/bus-system.md` |
| Sample-accurate scheduling | `docs/engine/scheduling.md` |
+25
View File
@@ -46,10 +46,34 @@ let package = Package(
.package(name: "Lyrebird", path: "..")
],
targets: [
// The interpreted graph-DSL, compiled from the main package's shared
// sources (a symlink at `Sources/LyrebirdGraphDSLEmbedded`) as a LOCAL
// target here rather than consumed as a main-package product.
//
// Why not the main-package product: any `LyrebirdGraphDSL` product —
// static OR dynamic — bakes a SECOND copy of `LyrebirdSynth` into its
// dylib (a same-package target dependency is always static-embedded), so
// both `libLyrebirdDynamic` and that product's dylib register Lyrebird's
// ObjC classes → double registration → spurious cast failures + SIGSEGV
// under `swift test`. Compiling the DSL as a local target here lets its
// `import LyrebirdSynth` resolve cross-package to the ONE shared
// `libLyrebirdDynamic`. Safe because the DSL is pure value types (no
// classes), so recompiling it in a second module registers nothing with
// the ObjC runtime. Distinct module name (`…Embedded`) avoids any clash
// with the main package's `LyrebirdGraphDSL` in a shared Xcode graph.
.target(
name: "LyrebirdGraphDSLEmbedded",
dependencies: [
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
],
path: "Sources/LyrebirdGraphDSLEmbedded"
),
.target(
name: "LyrebirdLiveCompile",
dependencies: [
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
// Instant, no-swiftc graph evaluation for the editor's DSL mode.
"LyrebirdGraphDSLEmbedded",
],
path: "Sources/LyrebirdLiveCompile"
),
@@ -67,6 +91,7 @@ let package = Package(
dependencies: [
"LyrebirdLiveCompile",
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
"LyrebirdGraphDSLEmbedded",
],
path: "Tests/LyrebirdLiveCompileTests"
),
+1
View File
@@ -0,0 +1 @@
../../Sources/LyrebirdGraphDSL
@@ -0,0 +1,74 @@
// GraphDSLDiagnosticMapper.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// Turns a thrown `DSLParseError` / `DSLBuildError` into the same `[Diagnostic]`
// the swiftc path produces, so `LyrebirdScratchView`'s gutter renders DSL
// failures with no special-casing. Parse errors carry a source span → a real
// (line, column); build errors carry no span → `line: nil` with the message
// alone.
#if os(macOS)
import LyrebirdGraphDSLEmbedded
/// Maps interpreted-graph-DSL errors to editor diagnostics.
enum GraphDSLDiagnosticMapper {
/// Convert `error` (a `DSLParseError`, a `DSLBuildError`, or anything else)
/// into one or more ``Diagnostic``s, resolving parse-error spans against
/// `source` for a 1-based line/column.
static func diagnostics(for error: Error, source: String) -> [Diagnostic] {
if let parse: DSLParseError = error as? DSLParseError {
let (line, column): (Int, Int) = lineColumn(of: parse.span.start, in: source)
return [Diagnostic(
line: line,
column: column,
severity: .error,
message: parse.description,
rawLine: line
)]
}
if let build: DSLBuildError = error as? DSLBuildError {
// Build errors carry no span; report at file scope.
return [Diagnostic(
line: nil,
column: 0,
severity: .error,
message: build.description,
rawLine: 0
)]
}
return [Diagnostic(
line: nil,
column: 0,
severity: .error,
message: "\(error)",
rawLine: 0
)]
}
/// Map a character `offset` into `source` to a 1-based (line, column).
/// An offset past the end clamps to the final position.
private static func lineColumn(of offset: Int, in source: String) -> (line: Int, column: Int) {
var line: Int = 1
var column: Int = 1
var seen: Int = 0
for character: Character in source {
if seen >= offset { break }
if character == "\n" {
line += 1
column = 1
} else {
column += 1
}
seen += 1
}
return (line, column)
}
}
#endif
@@ -0,0 +1,42 @@
// LSPCompletionItem.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// One parsed code-completion candidate from `sourcekit-lsp`. macOS only.
#if os(macOS)
/// One code-completion candidate returned by sourcekit-lsp.
public struct LSPCompletionItem: Sendable, Equatable {
/// Display label (e.g. `Audio`).
public let label: String
/// Type / signature detail (e.g. `OscSin.Audio`), if provided.
public let detail: String?
/// Text to insert when chosen. Falls back to `label` when the server gives
/// no explicit insert text.
public let insertText: String
/// LSP `CompletionItemKind` raw value, or `nil`. Lets the UI pick an icon.
public let kind: Int?
/// Server-provided sort key; the UI orders by this then by `label`.
public let sortText: String?
public init(
label: String,
detail: String?,
insertText: String,
kind: Int?,
sortText: String?
) {
self.label = label
self.detail = detail
self.insertText = insertText
self.kind = kind
self.sortText = sortText
}
}
#endif
@@ -190,10 +190,11 @@ public enum LiveCompiler {
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.
// stdout discarded — swiftc emits no useful output in the modes used
// here (-emit-library and -typecheck). 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()
@@ -205,6 +206,53 @@ public enum LiveCompiler {
let stderrString: String = String(data: stderrData, encoding: .utf8) ?? ""
return SwiftcResult(exitCode: process.terminationStatus, stderr: stderrString)
}
// MARK: - Module-cache prewarm
/// Build the Clang/Swift module cache (the precompiled `.pcm` for the large
/// `LyrebirdSynth` interface and its dependencies) by **type-checking** a
/// trivial source that imports the same modules a real snippet does.
///
/// The cold cache build costs ~2–3 s and otherwise lands on the user's first
/// ⌘↩; running this once at session start (off-main) moves that cost into the
/// background, so the first real ``compile(source:extraSwiftcArgs:)`` hits a
/// warm cache (~0.1 s). `-typecheck` is enough — the `.pcm`s are produced
/// during import resolution, before codegen/link — and avoids emitting or
/// `dlopen`ing a dylib.
///
/// - Parameter extraSwiftcArgs: The module-resolution flags (`-I`,
/// `-Xcc -fmodule-map-file=…`) that point at the same modules the real
/// compile uses, so both warm the same (default) module cache.
/// `LiveSession` supplies these via its module-resolution args.
/// - Throws: `LiveCompileError` for a missing toolchain, IO failure, or a
/// non-zero type-check exit.
public static func prewarm(extraSwiftcArgs: [String]) throws {
let swiftc: String = try findSwiftc()
let id: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
let workDir: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LyrebirdLiveCompile-prewarm-\(id)", isDirectory: true)
let sourcePath: String = workDir.appendingPathComponent("Prewarm.swift").path
let source: String = "import LyrebirdSynth\nimport LyrebirdLiveCompile\n"
do {
try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true)
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
} catch {
throw LiveCompileError.ioFailed(underlying: "\(error)")
}
defer { try? FileManager.default.removeItem(at: workDir) }
var arguments: [String] = ["-typecheck", "-module-name", "LBPrewarm_\(id)"]
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)
}
}
}
#endif
@@ -28,9 +28,10 @@ import LyrebirdSynth
/// Swift 6 requires it to be `Sendable`. The conformance is sound by construction:
///
/// - `engine` and all `-I` / `-L` / `-l` / `rpath` configuration are immutable `let`.
/// - The only mutable graph state — `trackedSynths` and `loadedSnippets` — is accessed
/// exclusively under `trackingLock` (`track`, `clearTracked`, `trackedSynthCount`,
/// `runEntry`).
/// - The mutable graph state — `trackedSynths`, `loadedSnippets`, and the named-slot map
/// `slottedSynths` — is accessed exclusively under `trackingLock` (`track`,
/// `clearTracked`, `trackedSynthCount`, `runEntry`, `assignSlot`, `clearSlot`,
/// `clearSlots`, `slotCount`, `slotNames`).
/// - `reportedSampleRate` / `lastSnippetMessage` are test-only side channels (`@testable`),
/// written by the single in-flight snippet entry under the documented
/// one-invocation-at-a-time precondition (see `compileAndRunAsync`) and read by tests
@@ -53,6 +54,12 @@ public final class LiveSession: @unchecked Sendable {
/// runtime without `DYLD_LIBRARY_PATH` ceremony.
public let rpaths: [URL]
// Prewarm lifecycle — guarded by `trackingLock`. `_prewarmed` flips true
// when a prewarm completes; `_prewarming` guards a call in flight so
// repeat calls (e.g. a view re-appearing) don't spawn a second swiftc.
private var _prewarmed: Bool = false
private var _prewarming: Bool = false
/// Side-channel for snippet `context.reportSampleRate(_:)` calls. Tests read
/// via `@testable import`; not part of the public API.
internal var reportedSampleRate: Double?
@@ -66,6 +73,33 @@ public final class LiveSession: @unchecked Sendable {
private var trackedSynths: [any Synthesizer] = []
private var loadedSnippets: [CompiledSnippet] = []
// A named-slot occupant plus the sample time its add was scheduled at.
// The add time lets a later teardown schedule the occupant's removal no
// earlier than its own add, so a still-pending *scheduled* voice (quantized
// swap not yet fired) is never orphaned by an immediate clear or an earlier
// re-swap. See `removeSlotOccupant`.
private struct SlotEntry {
let synth: any Synthesizer
let addTime: SampleTime
}
// Named slots — `Pdef`-style persistent voices, keyed by name. Kept
// separate from the anonymous `trackedSynths` so they SURVIVE a
// non-additive re-evaluation: re-running a `context.play(slot: "bass") { … }`
// definition replaces just that voice in place (via `assignSlot`) instead of
// being cleared with the anonymous synths. Guarded by `trackingLock`.
private var slottedSynths: [String: SlotEntry] = [:]
// Swap-quantization config + pending-swap signal — all guarded by
// `trackingLock`. When `_swapClock` is set and `_swapQuantize` is not
// `.immediate`, a slot swap schedules the new voice's add and the old
// voice's removal at the next musical boundary instead of taking effect at
// once (latency masking). `_pendingSwapBeat` is the latest target beat of a
// not-yet-fired scheduled swap, surfaced via ``pendingSwapBeat``.
private var _swapClock: LyrebirdClock?
private var _swapQuantize: SwapQuantize = .immediate
private var _pendingSwapBeat: Double?
public init(
engine: SynthesisEngine,
importPaths: [URL] = LiveSession.defaultImportPaths(),
@@ -208,9 +242,314 @@ public final class LiveSession: @unchecked Sendable {
trackedSynths.append(synth)
}
// MARK: - Named slots
/// Number of named slots currently holding a synth. Thread-safe.
public var slotCount: Int {
trackingLock.lock(); defer { trackingLock.unlock() }
return slottedSynths.count
}
/// Names of the currently-populated slots. Thread-safe.
public var slotNames: [String] {
trackingLock.lock(); defer { trackingLock.unlock() }
return Array(slottedSynths.keys)
}
/// Install `synth` into the named `slot` immediately, replacing any synth
/// previously held there.
///
/// Internal hook for the immediate path of ``swapSlot(_:synth:)``. **Call
/// after `engine.add(synth)` has succeeded** — the new voice is live before
/// the old one is torn down, so a slot replacement is a brief overlap rather
/// than a silent gap. The previous occupant is removed via
/// ``removeSlotOccupant(_:desired:)`` (scheduled no earlier than its own
/// add, so a still-pending scheduled voice is never orphaned). Thread-safe;
/// `engine.remove` runs outside the lock.
func assignSlot(_ name: String, synth: any Synthesizer) {
let now: SampleTime = engine.currentTime
let previous: SlotEntry?
do {
trackingLock.lock(); defer { trackingLock.unlock() }
previous = slottedSynths[name]
slottedSynths[name] = SlotEntry(synth: synth, addTime: now)
}
if let previous: SlotEntry = previous {
removeSlotOccupant(previous, desired: now)
}
}
/// Remove every named-slot synth from the engine and clear all slots.
/// Anonymous tracked synths are untouched — pair with ``clearTracked()``
/// for a full reset.
public func clearSlots() {
let now: SampleTime = engine.currentTime
let snapshot: [SlotEntry]
do {
trackingLock.lock(); defer { trackingLock.unlock() }
snapshot = Array(slottedSynths.values)
slottedSynths.removeAll()
}
for entry: SlotEntry in snapshot {
removeSlotOccupant(entry, desired: now)
}
}
/// Remove the synth in the named `slot` (if any) from the engine and clear
/// the slot. No-op when the slot is empty. Returns `true` if a synth was
/// removed.
@discardableResult
public func clearSlot(_ name: String) -> Bool {
let now: SampleTime = engine.currentTime
let previous: SlotEntry?
do {
trackingLock.lock(); defer { trackingLock.unlock() }
previous = slottedSynths.removeValue(forKey: name)
}
if let previous: SlotEntry = previous {
removeSlotOccupant(previous, desired: now)
return true
}
return false
}
/// Remove a slot occupant, scheduling the removal no earlier than the
/// occupant's own add time (`max(desired, addTime)`) so a still-pending
/// scheduled add is never orphaned. `desired` is the caller's intended
/// removal time — a swap boundary, or the current time for an immediate
/// teardown. Because the occupant's add is always enqueued before this
/// removal and the engine's per-block event sort is stable at equal times,
/// an add and removal landing on the same sample apply add-then-removal, so
/// the voice is always cleaned up. Runs outside `trackingLock`.
@discardableResult
private func removeSlotOccupant(_ entry: SlotEntry, desired: SampleTime) -> Bool {
let removeAt: SampleTime = max(desired, entry.addTime)
return engine.remove(entry.synth, at: removeAt)
}
// MARK: - Session reset + snippet accounting
/// Panic / clear-everything valve: remove every snippet-played synth — both
/// the anonymous tracked ones (``clearTracked()``) and every named slot
/// (``clearSlots()``) — from the engine, and clear the pending-swap signal.
/// Stops all snippet audio and gives a clean slate without tearing down the
/// engine.
///
/// It does **not** reclaim the compiled snippet dylibs — see
/// ``loadedSnippetCount``. Reclaiming that memory would require `dlclose`,
/// which is unsafe for these Swift dylibs: `dlopen` registers their type
/// metadata and protocol-conformance records into process-global runtime
/// caches that `dlclose` does not deregister, so unmapping the dylib leaves
/// those caches dangling. Mapped snippet memory is therefore reclaimed only
/// by restarting the process. (The interpreted-graph path on the roadmap
/// avoids dylibs entirely and is the structural fix.)
///
/// - Precondition: same one-invocation-at-a-time caveat as
/// ``compileAndRunAsync(_:additive:)``. Calling this concurrently with an
/// in-flight compile can interleave the internal `clearTracked()` with a
/// not-yet-completed `runEntry`, missing a just-added synth (which then
/// leaks until process restart). The built-in ``LyrebirdScratchModel``
/// serialises through its `isCompiling` flag. This is also not a single
/// atomic critical section — the synth removal and the pending-swap clear
/// take `trackingLock` separately — which is acceptable for a panic valve.
public func resetAll() {
clearTracked()
clearSlots()
trackingLock.lock(); defer { trackingLock.unlock() }
_pendingSwapBeat = nil
}
/// Number of compiled snippet dylibs currently mapped into the process.
///
/// Each ⌘↩ compiles a new dylib that stays mapped for the process's lifetime
/// (unloading is unsafe — see ``resetAll()``), so within a session this only
/// grows. Exposed for host observability, e.g. a "restart to reclaim memory"
/// nudge after a very long session. Thread-safe.
public var loadedSnippetCount: Int {
trackingLock.lock(); defer { trackingLock.unlock() }
return loadedSnippets.count
}
// MARK: - Swap quantization (on-beat latency masking)
/// Clock that slot swaps quantize against. When `nil` (default), swaps are
/// always immediate regardless of ``swapQuantize``. Setting it clears any
/// pending-swap signal (``pendingSwapBeat``). Thread-safe.
public var swapClock: LyrebirdClock? {
get { trackingLock.lock(); defer { trackingLock.unlock() }; return _swapClock }
set {
trackingLock.lock(); defer { trackingLock.unlock() }
_swapClock = newValue
_pendingSwapBeat = nil
}
}
/// When a named-slot swap becomes audible. Defaults to ``SwapQuantize/immediate``.
/// Only takes effect when ``swapClock`` is also set. Setting it clears any
/// pending-swap signal (``pendingSwapBeat``). Thread-safe.
public var swapQuantize: SwapQuantize {
get { trackingLock.lock(); defer { trackingLock.unlock() }; return _swapQuantize }
set {
trackingLock.lock(); defer { trackingLock.unlock() }
_swapQuantize = newValue
_pendingSwapBeat = nil
}
}
/// Target beat of the latest scheduled-but-not-yet-fired slot swap, or `nil`
/// when none is pending (immediate mode, the boundary has already passed, or
/// the swap config changed). Self-clearing: returns `nil` once the clock
/// reaches the target beat. Drives the editor's `.queued` readiness state.
///
/// When several slots have swaps pending at different beats this reports the
/// latest of them — treat it as "some swap is still outstanding", not "this
/// specific run's swap". Thread-safe, but not atomic against a concurrent
/// swap: the `_swapClock` snapshot and the `clock.currentBeat` read happen in
/// separate critical sections, so a swap scheduled between them may not yet
/// be reflected. Fine for the main-actor UI that consumes it.
public var pendingSwapBeat: Double? {
let target: Double?
let clock: LyrebirdClock?
do {
trackingLock.lock(); defer { trackingLock.unlock() }
target = _pendingSwapBeat
clock = _swapClock
}
guard let target: Double = target, let clock: LyrebirdClock = clock else { return nil }
return clock.currentBeat < target ? target : nil
}
/// Install `synth` into the named `slot`, quantizing the swap per
/// ``swapQuantize`` / ``swapClock``.
///
/// Immediate mode (`.immediate` or no clock): adds `synth` now and removes
/// the previous slot synth now (via ``assignSlot(_:synth:)``). Quantized
/// mode: schedules `synth`'s add and the previous synth's removal at the same
/// upcoming boundary sample time, so the swap is glitch-free and on-grid,
/// and records the target beat for ``pendingSwapBeat``.
///
/// Backs ``SnippetContext/play(slot:_:)``. `@MainActor` because it touches
/// the engine's node tree (`add`/`schedule`/`remove`).
///
/// - Throws: `EngineAddError` if the engine rejects the add/schedule; the
/// prior slot synth is left in place on throw.
@MainActor
func swapSlot(_ name: String, synth: any Synthesizer) throws {
let clock: LyrebirdClock?
let quantize: SwapQuantize
do {
trackingLock.lock(); defer { trackingLock.unlock() }
clock = _swapClock
quantize = _swapQuantize
}
if let clock: LyrebirdClock = clock, let beat: Double = quantize.targetBeat(clock: clock) {
let time: SampleTime = clock.sampleTime(beat: beat)
try engine.schedule(synth, at: time)
scheduleSlotReplace(name, newSynth: synth, at: time, targetBeat: beat)
} else {
try engine.add(synth)
assignSlot(name, synth: synth)
}
}
/// Commit a scheduled slot replacement: swap the dictionary entry, schedule
/// removal of the previous synth at the boundary `time` (no earlier than its
/// own add), and record the pending target beat. Call only after
/// `engine.schedule(new, at: time)` succeeded. `engine.remove` runs outside
/// the lock; a dropped removal (pending queue full) is surfaced via
/// `lastSnippetMessage` rather than silently leaving an overlap.
private func scheduleSlotReplace(
_ name: String,
newSynth: any Synthesizer,
at time: SampleTime,
targetBeat: Double
) {
let previous: SlotEntry?
do {
trackingLock.lock(); defer { trackingLock.unlock() }
previous = slottedSynths[name]
slottedSynths[name] = SlotEntry(synth: newSynth, addTime: time)
_pendingSwapBeat = max(_pendingSwapBeat ?? targetBeat, targetBeat)
}
if let previous: SlotEntry = previous {
let removed: Bool = removeSlotOccupant(previous, desired: time)
if !removed {
lastSnippetMessage =
"slot '\(name)': previous voice removal dropped (pending queue full) — voices may overlap"
}
}
}
// MARK: - Prewarm
/// `true` once a ``prewarm()`` has **succeeded** for this session. A prewarm
/// that failed (e.g. missing toolchain) leaves this `false` so a later call
/// retries. Thread-safe.
public var isPrewarmed: Bool {
trackingLock.lock(); defer { trackingLock.unlock() }
return _prewarmed
}
/// Warm the module cache in the background so the first real ⌘↩ is fast.
///
/// The cold `LyrebirdSynth` `.pcm` build costs ~2–3 s; without a prewarm it
/// lands on the user's first compile. This kicks a detached, `.utility`
/// type-check of a trivial import-only snippet (via
/// ``LiveCompiler/prewarm(extraSwiftcArgs:)``) that warms swiftc's default
/// module cache, so the first `compileAndRunAsync` hits a warm cache
/// (~0.1 s). All the work — including the filesystem walk that builds the
/// compiler flags — runs on the detached task, not the caller's thread.
///
/// Idempotent: a call while a prewarm has already succeeded or is in flight
/// is a no-op. A *failed* prewarm leaves ``isPrewarmed`` `false` (a later
/// call retries); the real compile then simply pays the build itself, so the
/// failure is non-fatal and intentionally not thrown.
///
/// - Returns: The detached `Task`, so callers/tests can `await` its `value`.
/// The no-op case returns an already-scheduled empty task.
@discardableResult
public func prewarm() -> Task<Void, Never> {
let shouldRun: Bool
do {
trackingLock.lock(); defer { trackingLock.unlock() }
shouldRun = !_prewarmed && !_prewarming
if shouldRun { _prewarming = true }
}
guard shouldRun else { return Task {} }
return Task.detached(priority: .utility) { [weak self] in
guard let self: LiveSession = self else { return }
// Off-main: build the flags (a small filesystem walk) here rather
// than on the caller (this method is a synchronous `nonisolated`
// call, so anything before the detached task runs on the caller).
let args: [String] = self.makeModuleResolutionArgs()
do {
try LiveCompiler.prewarm(extraSwiftcArgs: args)
self.finishPrewarm(succeeded: true)
} catch {
self.finishPrewarm(succeeded: false)
}
}
}
/// Record a ``prewarm()`` outcome: clear the in-flight flag, and mark warmed
/// only on success so a failed attempt can retry.
private func finishPrewarm(succeeded: Bool) {
trackingLock.lock(); defer { trackingLock.unlock() }
_prewarming = false
if succeeded { _prewarmed = true }
}
// MARK: - swiftc flag construction
private func makeSwiftcArgs() -> [String] {
/// Module-resolution flags shared by the real compile and the prewarm:
/// `-I` import paths plus the Xcode + bare-SPM Clang module maps. No linker
/// flags — a `-typecheck` prewarm needs none. Deliberately does **not** pin
/// `-module-cache-path`: prewarm and the real compile both use swiftc's
/// default cache, so the prewarm warms exactly the cache the compile reads.
/// (Pinning a dedicated cache built fresh diverges its module metadata from
/// the already-loaded `libLyrebirdLiveCompileDynamic`, which turns the test
/// bundle's benign ObjC class-duplication warning into a hard cast crash.)
private func makeModuleResolutionArgs() -> [String] {
var args: [String] = []
for path: URL in importPaths {
args += ["-I", path.path]
@@ -222,6 +561,19 @@ public final class LiveSession: @unchecked Sendable {
for url: URL in LiveSession.discoverClangModuleMaps(in: importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
// Bare-SPM (`swift build` / `swift test`) layout: C-target module maps
// live at `<buildDir>/<CTarget>.build/module.modulemap`, which the Xcode
// discovery above does not cover. Surface them so a snippet's
// `import LyrebirdSynth` can resolve the underlying `LyrebirdC` clang
// module outside Xcode too.
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
return args
}
private func makeSwiftcArgs() -> [String] {
var args: [String] = makeModuleResolutionArgs()
// When a Lyrebird dylib exists in any -L path, link against it
// (-l<name>) and bake an rpath. When no dylib is found (Xcode SPM
// case — modules statically linked into the host app), use
@@ -279,6 +631,33 @@ public final class LiveSession: @unchecked Sendable {
return found
}
/// Locate SPM-generated Clang module maps for a `swift build` / `swift test`
/// layout. Each C target's map is emitted at
/// `<buildDir>/<CTarget>.build/module.modulemap`; the umbrella header path
/// inside is absolute, so the map alone is enough to resolve the module (no
/// extra `-I` needed). Empty under an Xcode SPM layout, where
/// `discoverClangModuleMaps` handles the `GeneratedModuleMaps` location
/// instead.
static func discoverSPMModuleMaps(in importPaths: [URL]) -> [URL] {
var found: [URL] = []
var visited: Set<String> = Set<String>()
for base: URL in importPaths {
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
at: base,
includingPropertiesForKeys: nil
) else { continue }
for entry: URL in entries where entry.pathExtension == "build" {
let probe: URL = entry.appendingPathComponent("module.modulemap")
if FileManager.default.fileExists(atPath: probe.path),
!visited.contains(probe.path) {
visited.insert(probe.path)
found.append(probe)
}
}
}
return found
}
// MARK: - Build-dir discovery
/// Best-effort discovery of the SPM `.build/<triple>/<config>` directory
@@ -23,6 +23,12 @@ public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
/// missing entry symbol, IO failure.
case compilerError(LiveCompileError)
/// The interpreted graph-DSL failed to lex/parse/build or its graphs were
/// rejected by the engine. `diagnostics` are already mapped to user-source
/// coordinates (a parse error resolves to a line/column; a build error has
/// `line: nil`). No swiftc is involved — this is the instant DSL path.
case graphDSLFailed(diagnostics: [Diagnostic], underlying: Error)
public var description: String {
switch self {
case .snippetCompileFailed(let diagnostics, let underlying):
@@ -36,6 +42,15 @@ public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
return "snippet compile failed:\n\(summary)"
case .compilerError(let underlying):
return "live compile error: \(underlying)"
case .graphDSLFailed(let diagnostics, let underlying):
if diagnostics.isEmpty {
return "graph DSL failed:\n\(underlying)"
}
let summary: String = diagnostics.map { diag -> String in
let location: String = diag.line.map { "\($0):\(diag.column)" } ?? "?"
return "\(location) \(diag.severity.rawValue): \(diag.message)"
}.joined(separator: "\n")
return "graph DSL failed:\n\(summary)"
}
}
}
@@ -0,0 +1,104 @@
// LiveSessionGraphDSL.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// The editor's instant, no-swiftc evaluation path. `runGraphDSL` lexes, parses,
// and builds interpreted graph-DSL source into `ClosureSynthesizer`s and plays
// them through the SAME tracking + named-slot machinery `compileAndRun` uses, so
// non-additive re-evaluation, slot hot-swap, and `resetAll()` behave identically
// across the Swift and DSL paths. The only difference is speed: a graph edit
// re-evaluates in microseconds instead of a swiftc round-trip.
#if os(macOS)
import LyrebirdSynth
import LyrebirdGraphDSLEmbedded
extension LiveSession {
/// Evaluate interpreted graph-DSL `source` and play each statement.
///
/// Mirrors ``compileAndRun(_:additive:)`` but with no compiler: the source is
/// interpreted in-process. Each statement becomes one output —
///
/// - an anonymous statement (`OscSin(freq: 440) * 0.1`) is added to the
/// engine and tracked, so a later non-additive run removes it;
/// - a named statement (`bass = OscSawtooth(freq: 55) * 0.2`) is installed into
/// the matching named slot via ``swapSlot(_:synth:)`` — a persistent,
/// hot-swappable voice that survives a non-additive re-evaluation and is
/// replaced in place on the next run.
///
/// The whole program is lexed/parsed/built **before** any engine mutation, so
/// a syntax or build error leaves the currently-playing graph untouched — a
/// *malformed* edit never drops audio. Once the program is valid, playback is
/// best-effort per statement: an engine-level rejection of one statement
/// (e.g. `.pendingQueueFull`) is collected and surfaced but does not abort
/// the others, matching ``SnippetContext/play(_:)``.
///
/// - Parameters:
/// - source: DSL program text (one statement per line).
/// - additive: When `false` (default), removes every previously tracked
/// anonymous synth before playing (named slots persist). When `true`,
/// leaves prior synths in place.
/// - resources: Host resource table resolving bare-identifier references
/// (e.g. buffers). Defaults to an empty table.
/// - Throws: ``LiveSessionError/graphDSLFailed(diagnostics:underlying:)`` with
/// editor-ready diagnostics for a lex/parse/build failure (before any
/// mutation), or for one or more per-statement engine rejections (after the
/// surviving statements have gone live).
@MainActor
public func runGraphDSL(
_ source: String,
additive: Bool = false,
resources: DSLResourceResolver = DSLEmptyResources()
) throws {
// Build everything first — no engine mutation until we know the whole
// program is valid.
let outputs: [DSLOutput]
do {
outputs = try DSLInterpreter.evaluate(source, resources: resources)
} catch {
throw LiveSessionError.graphDSLFailed(
diagnostics: GraphDSLDiagnosticMapper.diagnostics(for: error, source: source),
underlying: error
)
}
if !additive { clearTracked() }
// Play every statement. An engine-level rejection of ONE statement
// (e.g. `.pendingQueueFull`) must not abort the rest — the others still
// go live, mirroring `SnippetContext.play`'s per-statement best-effort
// behavior. Failures are collected and surfaced together; the graphs
// that added successfully keep playing.
var failures: [Diagnostic] = []
var firstError: Error?
for output: DSLOutput in outputs {
let synth: ClosureSynthesizer = ClosureSynthesizer {
// The graph is already built (eagerly, by the interpreter); the
// closure just hands it to `build()`. Each `DSLOutput.graph` is
// owned by exactly one synth, so this never shares a graph.
output.graph
}
do {
if let slot: String = output.slot {
try swapSlot(slot, synth: synth)
} else {
try engine.add(synth)
track(synth)
}
} catch {
if firstError == nil { firstError = error }
failures.append(contentsOf: GraphDSLDiagnosticMapper.diagnostics(for: error, source: source))
}
}
if let firstError: Error = firstError {
throw LiveSessionError.graphDSLFailed(diagnostics: failures, underlying: firstError)
}
}
}
#endif
@@ -0,0 +1,184 @@
// SnippetCompletionService.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// Bridges the live-coding editor to `sourcekit-lsp` (via ``SourceKitLSPClient``)
// so the user gets real Swift code completion — the same symbols the snippet
// would see at compile time (`context`, `LyrebirdSynth` generators, …).
//
// It maintains a small on-disk workspace: the snippet is written WRAPPED in the
// same `SnippetHarness` preamble the compiler uses, next to a
// `compile_commands.json` carrying the module-resolution flags derived from the
// host `LiveSession`. sourcekit-lsp's compilation-database build system reads
// that file, which is what lets `import LyrebirdSynth` and the injected
// `context: SnippetContext` resolve for an otherwise free-standing file.
//
// macOS only.
#if os(macOS)
import Foundation
/// Provides code completion for a live-coding editor buffer.
public actor SnippetCompletionService {
private let _client: SourceKitLSPClient
private let _session: LiveSession
private let _workspace: URL
private let _fileURL: URL
private let _fileURI: String
// Version counter for `didChange`, and the offset (from the last wrap) that
// maps a user-body line to its line in the wrapped document.
private var _version: Int = 1
private var _userBodyLineOffset: Int = 1
private var _started: Bool = false
/// - Parameters:
/// - session: Host session whose `importPaths` / `librarySearchPaths` /
/// `libraries` are reused verbatim, so completion sees exactly the
/// modules the real compile links.
/// - client: LSP client to drive (injectable for tests).
public init(
session: LiveSession,
client: SourceKitLSPClient = SourceKitLSPClient()
) {
self._client = client
self._session = session
// URL computation only — no filesystem or subprocess I/O here, so the
// synchronous init never blocks its caller (the @MainActor model).
self._workspace = FileManager.default.temporaryDirectory
.appendingPathComponent("lyrebird-completion-" + UUID().uuidString, isDirectory: true)
self._fileURL = _workspace.appendingPathComponent("snippet.swift")
self._fileURI = "file://" + _fileURL.path
}
/// Create the workspace directory, a seed snippet file, and the
/// `compile_commands.json` describing how to compile it. Runs on the actor
/// executor (off the main thread) — it shells out to `xcrun` for the SDK
/// path, which must not block the UI.
private func _writeWorkspace() {
try? FileManager.default.createDirectory(at: _workspace, withIntermediateDirectories: true)
let seed: WrappedSnippet = SnippetHarness.wrap(userBody: "\n")
try? seed.source.write(to: _fileURL, atomically: true, encoding: .utf8)
let arguments: [String] = SnippetCompletionService.compileArguments(
session: _session, file: _fileURL.path)
let entry: [String: Any] = [
"directory": _workspace.path,
"file": _fileURL.path,
"arguments": arguments
]
if let data: Data = try? JSONSerialization.data(withJSONObject: [entry], options: [.prettyPrinted]) {
try? data.write(to: _workspace.appendingPathComponent("compile_commands.json"))
}
}
/// Build the swiftc invocation for the compilation database: the `-I`
/// module paths, C-target module maps, and link flags from `session`, plus
/// the explicit `-sdk` / `-target` sourcekit-lsp needs for a free-standing
/// file (swiftc infers those during a normal build, but the LSP does not).
static func compileArguments(session: LiveSession, file: String) -> [String] {
var args: [String] = ["swiftc", file]
for path: URL in session.importPaths {
args += ["-I", path.path]
}
for url: URL in LiveSession.discoverClangModuleMaps(in: session.importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
for url: URL in LiveSession.discoverSPMModuleMaps(in: session.importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
for path: URL in session.librarySearchPaths {
args += ["-L", path.path]
}
for lib: String in session.libraries {
args += ["-l\(lib)"]
}
if let sdk: String = sdkPath() {
args += ["-sdk", sdk]
}
args += ["-target", targetTriple()]
return args
}
private static func sdkPath() -> String? {
let p: Process = Process()
p.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
p.arguments = ["--show-sdk-path", "--sdk", "macosx"]
let out: Pipe = Pipe()
p.standardOutput = out
p.standardError = Pipe()
try? p.run()
p.waitUntilExit()
let data: Data = out.fileHandleForReading.readDataToEndOfFile()
let path: String? = String(data: data, encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines)
return (path?.isEmpty == false) ? path : nil
}
/// Minimum-deployment target triple. Arch matches the running process;
/// the OS floor matches the package's `macOS 15` minimum.
private static func targetTriple() -> String {
#if arch(arm64)
let arch: String = "arm64"
#else
let arch: String = "x86_64"
#endif
return "\(arch)-apple-macosx15.0"
}
/// Launch sourcekit-lsp and open the (empty) document. Call once before the
/// first ``completions(userBody:line:character:)``. Idempotent.
public func start() async throws {
guard !_started else { return }
// Build the workspace (SDK lookup + file writes) here, on the actor
// executor, so the blocking `xcrun` call never lands on the main thread.
_writeWorkspace()
try await _client.start(rootURI: "file://" + _workspace.path)
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: "\n")
_userBodyLineOffset = wrapped.userBodyLineOffset
_client.didOpen(uri: _fileURI, text: wrapped.source, version: _version)
_started = true
}
/// Request completions for `userBody` at the user-space `line` / `character`
/// (both zero-based, in the user's own text — not the wrapped document).
///
/// The body is re-synced to the server first, then the cursor is mapped
/// through the harness offset into the wrapped document.
public func completions(userBody: String, line: Int, character: Int) async throws -> [LSPCompletionItem] {
if !_started { try await start() }
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: userBody)
_userBodyLineOffset = wrapped.userBodyLineOffset
_version += 1
_client.didChange(uri: _fileURI, text: wrapped.source, version: _version)
// User line 0 sits at wrapped line `userBodyLineOffset - 1` (0-based);
// the column is unchanged (the preamble adds only whole lines).
let wrappedLine: Int = line + (_userBodyLineOffset - 1)
return try await _client.completion(uri: _fileURI, line: wrappedLine, character: character)
}
/// Shut down the server and remove the workspace. Safe to call more than once.
public func stop() {
shutdownSynchronously()
_started = false
}
/// Synchronous teardown usable from `deinit` and non-async contexts (a test
/// `defer`): terminate the LSP client and delete the temp workspace. Touches
/// only `let` members, so it is safe to run `nonisolated`. Idempotent.
public nonisolated func shutdownSynchronously() {
_client.shutdown()
try? FileManager.default.removeItem(at: _workspace)
}
deinit {
shutdownSynchronously()
}
}
#endif
@@ -48,6 +48,94 @@ public final class SnippetContext {
}
}
/// Play `synth` into a **named slot**, replacing whatever synth was there
/// before — the `Pdef`-style hot-swap primitive.
///
/// Unlike ``play(_:)``, a slotted synth is *not* torn down by the next
/// non-additive re-evaluation. Re-running a `play(slot:)` for the same name
/// swaps that one voice in place (the new voice starts before the old is
/// removed — a brief overlap, no gap), while other slots keep playing.
/// This lets you mutate one voice at a time, live.
///
/// ```swift
/// context.play(slot: "bass") { OscSaw.Audio(freq: 55, mul: 0.2) }
/// ```
///
/// Clear a slot with `context.session.clearSlot("bass")`, or all slots with
/// `context.session.clearSlots()`.
///
/// The swap is immediate by default, or quantized to the next beat/bar when
/// the session has a ``LiveSession/swapClock`` and a non-`.immediate`
/// ``LiveSession/swapQuantize`` — see ``LiveSession/swapSlot(_:synth:)``.
///
/// - Parameters:
/// - name: Slot identifier. Re-using a name replaces that slot's synth.
/// - synth: The `Synthesizer` to install.
/// - Returns: `true` if the engine accepted the add/schedule; `false` if it
/// threw (in which case the prior slot synth is left in place).
@discardableResult
@MainActor public func play(slot name: String, _ synth: any Synthesizer) -> Bool {
do {
try session.swapSlot(name, synth: synth)
return true
} catch {
session.lastSnippetMessage = "play(slot: \"\(name)\") failed: \(error)"
return false
}
}
/// Play a bare generator graph into a **named slot** — the `Pdef`-style
/// hot-swap primitive with no `SynthesizerBase` subclass to declare.
///
/// See ``play(slot:_:)`` for the slot semantics.
///
/// ```swift
/// context.play(slot: "lead") { Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0) }
/// ```
///
/// - Parameters:
/// - name: Slot identifier. Re-using a name replaces that slot's synth.
/// - bus: Output bus the graph is written to (multi-channel sources
/// continue into following buses). Defaults to `0`.
/// - make: Builds and returns the output graph. Called once, inside the
/// synthesizer's `build()`.
/// - Returns: `true` if the engine accepted the enqueue; `false` otherwise.
@discardableResult
@MainActor public func play(
slot name: String,
bus: any ValidBus = 0,
_ make: @escaping () -> any ValidGeneratorInput
) -> Bool {
play(slot: name, ClosureSynthesizer(bus: bus, make))
}
/// Add a bare generator graph to the engine — the fastest path to sound in
/// a snippet, with no `SynthesizerBase` subclass to declare.
///
/// ```swift
/// context.play { OscSin.Audio(freq: 440, mul: 0.1) }
/// context.play(bus: 0) { Pan2(input: saw, pan: 0) }
/// ```
///
/// Wraps `make` in a ``ClosureSynthesizer`` and forwards to ``play(_:)`` —
/// the synth is tracked for cleanup on the next non-additive re-evaluation
/// just like any other. Construct the generators inside the closure.
///
/// - Parameters:
/// - bus: Output bus the graph is written to (multi-channel sources
/// continue into following buses). Defaults to `0`.
/// - make: Builds and returns the output graph. Called once, inside the
/// synthesizer's `build()`.
/// - Returns: `true` if the engine accepted the enqueue; `false` if
/// `engine.add` threw.
@discardableResult
@MainActor public func play(
bus: any ValidBus = 0,
_ make: @escaping () -> any ValidGeneratorInput
) -> Bool {
play(ClosureSynthesizer(bus: bus, make))
}
/// Snippet-side hook for test verification: report the engine's sample rate
/// back through the session so tests can confirm the `context.engine`
/// linkage compiled and called correctly.
@@ -0,0 +1,413 @@
// SourceKitLSPClient.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// A minimal LSP JSON-RPC client that drives the toolchain's `sourcekit-lsp`
// executable over stdio to provide Swift code completion for the live-coding
// editor. Only the handful of requests the editor needs are implemented:
// `initialize` / `initialized`, `textDocument/didOpen` / `didChange`, and
// `textDocument/completion`.
//
// macOS only — the whole live-compile surface shells out to the toolchain.
#if os(macOS)
import Foundation
/// Nanoseconds in one second — for `Task.sleep`.
private let nanosecondsPerSecond: Double = 1_000_000_000
/// Drives `sourcekit-lsp` over stdio.
///
/// `@unchecked Sendable`: the process handles and the pending-request table are
/// guarded by `_lock`; a dedicated background reader thread parses framed
/// messages and completes the continuations stored under that lock. Public
/// methods are `async` and safe to call from any task.
public final class SourceKitLSPClient: @unchecked Sendable {
private let _process: Process = Process()
private let _stdin: Pipe = Pipe()
private let _stdout: Pipe = Pipe()
private let _lock: NSLock = NSLock()
private var _nextID: Int = 1
// Response continuations keyed by request id, completed by the reader thread.
// The payload is the raw response-body `Data` (Sendable); callers parse it.
private var _pending: [Int: CheckedContinuation<Data, Error>] = [:]
private var _running: Bool = false
// Accumulates stdout bytes until a full `Content-Length`-framed message is available.
private var _readBuffer: Data = Data()
/// Default request timeout in seconds. Completion should be well under this;
/// the ceiling guards against a wedged server.
public static let defaultRequestTimeout: TimeInterval = 15.0
// `nil` = resolve from the toolchain lazily in `start()`. Kept lazy so the
// synchronous `init` — evaluated in the caller's isolation, often the main
// actor via `SnippetCompletionService`'s default argument — never shells out
// to `xcrun`.
private let _explicitExecutableURL: URL?
private let _launchArguments: [String]
private let _requestTimeout: TimeInterval
/// - Parameters:
/// - executableURL: Path to `sourcekit-lsp`. When `nil` (default) it is
/// resolved from the toolchain via `xcrun` inside `start()` — not in
/// `init`, so construction never blocks its caller.
/// - arguments: Launch arguments for the executable (default none).
/// - requestTimeout: Per-request ceiling in seconds before ``request`` fails
/// with ``SourceKitLSPError/timedOut(method:)``.
public init(
executableURL: URL? = nil,
arguments: [String] = [],
requestTimeout: TimeInterval = SourceKitLSPClient.defaultRequestTimeout
) {
self._explicitExecutableURL = executableURL
self._launchArguments = arguments
self._requestTimeout = requestTimeout
}
deinit {
// Safety net: a client dropped without an explicit `shutdown()` would
// otherwise orphan the `sourcekit-lsp` subprocess and leave the reader
// thread blocked in `availableData`. `shutdown()` is idempotent.
shutdown()
}
/// Resolve `sourcekit-lsp` from the active toolchain via `xcrun`, falling
/// back to the conventional Xcode path.
private static func resolveExecutable() -> URL {
let xcrun: Process = Process()
xcrun.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
xcrun.arguments = ["--find", "sourcekit-lsp"]
let out: Pipe = Pipe()
xcrun.standardOutput = out
xcrun.standardError = Pipe()
try? xcrun.run()
xcrun.waitUntilExit()
let data: Data = out.fileHandleForReading.readDataToEndOfFile()
if let path: String = String(data: data, encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines), !path.isEmpty {
return URL(fileURLWithPath: path)
}
return URL(fileURLWithPath:
"/usr/bin/sourcekit-lsp") // last resort; run(...) will surface a launch error
}
// MARK: - Lifecycle
/// Launch the server, run the `initialize` handshake against `rootURI`, and
/// send `initialized`. Call once per client — the caller (e.g.
/// ``SnippetCompletionService``) guards against a second call; a repeat call
/// here would re-`run()` the process. Resolving the executable (an `xcrun`
/// lookup when no explicit path was given) happens here, off the constructing
/// caller's thread.
public func start(rootURI: String) async throws {
_process.executableURL = _explicitExecutableURL ?? SourceKitLSPClient.resolveExecutable()
_process.arguments = _launchArguments
_process.standardInput = _stdin
_process.standardOutput = _stdout
_process.standardError = Pipe() // discard server logging
do {
try _process.run()
} catch {
throw SourceKitLSPError.launchFailed("\(error)")
}
_setRunning(true)
_startReader()
let params: [String: Any] = [
"processId": Int(ProcessInfo.processInfo.processIdentifier),
"rootUri": rootURI,
"capabilities": [
"textDocument": [
"completion": [
"completionItem": ["snippetSupport": false]
]
]
]
]
_ = try await request(method: "initialize", params: params)
notify(method: "initialized", params: [:])
}
/// Terminate the server. Safe to call multiple times.
public func shutdown() {
_lock.lock()
let wasRunning: Bool = _running
_lock.unlock()
_failAllPending(with: SourceKitLSPError.notRunning)
guard wasRunning else { return }
// Send the graceful `exit` while still marked running (`_send` gates on
// `_running`), then flip the flag and terminate.
notify(method: "exit", params: [:])
_setRunning(false)
_process.terminate()
}
/// Remove and fail every in-flight request continuation with `error`.
/// Under `_lock`, so it never double-resumes against the reader's dispatch.
private func _failAllPending(with error: Error) {
_lock.lock()
let pending: [Int: CheckedContinuation<Data, Error>] = _pending
_pending.removeAll()
_lock.unlock()
for (_, cont): (Int, CheckedContinuation<Data, Error>) in pending {
cont.resume(throwing: error)
}
}
// MARK: - Document sync
/// Open `text` as a Swift document at `uri`.
public func didOpen(uri: String, text: String, version: Int = 1) {
notify(method: "textDocument/didOpen", params: [
"textDocument": [
"uri": uri, "languageId": "swift", "version": version, "text": text
]
])
}
/// Replace the full contents of `uri` with `text` (whole-document sync).
public func didChange(uri: String, text: String, version: Int) {
notify(method: "textDocument/didChange", params: [
"textDocument": ["uri": uri, "version": version],
"contentChanges": [["text": text]]
])
}
// MARK: - Completion
/// Request completions at a zero-based `line` / `character` in `uri`.
/// Returns the parsed items (possibly empty).
public func completion(uri: String, line: Int, character: Int) async throws -> [LSPCompletionItem] {
let body: Data = try await request(method: "textDocument/completion", params: [
"textDocument": ["uri": uri],
"position": ["line": line, "character": character]
])
let message: [String: Any] = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]
// The result is either a CompletionList ({ items: [...] }) or a bare
// CompletionItem[].
let rawItems: [Any]
if let dict: [String: Any] = message["result"] as? [String: Any],
let items: [Any] = dict["items"] as? [Any] {
rawItems = items
} else if let arr: [Any] = message["result"] as? [Any] {
rawItems = arr
} else {
return []
}
var out: [LSPCompletionItem] = []
out.reserveCapacity(rawItems.count)
for case let item as [String: Any] in rawItems {
guard let label: String = item["label"] as? String else { continue }
let detail: String? = item["detail"] as? String
let insert: String = (item["insertText"] as? String)
?? (item["filterText"] as? String)
?? label
let kind: Int? = item["kind"] as? Int
let sortText: String? = item["sortText"] as? String
out.append(LSPCompletionItem(
label: label, detail: detail, insertText: insert, kind: kind, sortText: sortText))
}
return out
}
// MARK: - JSON-RPC plumbing
// Lock-protected mutations, factored into sync helpers so no `NSLock` call
// happens inside an `async` function (forbidden under Swift 6).
private func _setRunning(_ value: Bool) {
_lock.lock(); defer { _lock.unlock() }
_running = value
}
private func _isRunning() -> Bool {
_lock.lock(); defer { _lock.unlock() }
return _running
}
private func _claimRequestID() -> Int? {
_lock.lock(); defer { _lock.unlock() }
guard _running else { return nil }
let id: Int = _nextID; _nextID += 1
return id
}
private func _storePending(_ id: Int, _ cont: CheckedContinuation<Data, Error>) {
_lock.lock(); defer { _lock.unlock() }
_pending[id] = cont
}
/// Remove a pending request AND resume its continuation with `error`.
/// Resuming is essential: a task-group child suspended on
/// `withCheckedThrowingContinuation` is not woken by `cancelAll()`, so
/// merely dropping the entry would leave `request(...)`'s group awaiting a
/// child that never completes — a deadlock. `removeValue` under `_lock` means
/// only one side (this drop, or the reader's dispatch) ever holds the
/// continuation, so there is no double-resume.
private func _dropPending(_ id: Int, resumingWith error: Error) {
_lock.lock()
let cont: CheckedContinuation<Data, Error>? = _pending.removeValue(forKey: id)
_lock.unlock()
cont?.resume(throwing: error)
}
/// Send a request and await its response body (`Data`). Times out per
/// ``requestTimeout``.
private func request(method: String, params: [String: Any]) async throws -> Data {
guard let id: Int = _claimRequestID() else { throw SourceKitLSPError.notRunning }
// Frame the message to `Data` synchronously here so the child task
// captures only Sendable state (`framed`, `id`), never the non-Sendable
// `[String: Any]` params.
guard let framed: Data = _frame(id: id, method: method, params: params) else {
throw SourceKitLSPError.serverError(code: -1, message: "could not encode \(method)")
}
let timeoutSeconds: TimeInterval = _requestTimeout
return try await withThrowingTaskGroup(of: Data.self) { group in
group.addTask { [weak self] in
guard let self: SourceKitLSPClient else { throw SourceKitLSPError.notRunning }
return try await withCheckedThrowingContinuation { cont in
self._storePending(id, cont)
// Close the store-vs-EOF window: if the server died between
// `_claimRequestID` and here, the reader already drained the
// pending table, so fail this one now instead of waiting for
// the timeout. `_dropPending` removes under the lock, so it
// can't double-resume against a concurrent reader/shutdown.
guard self._isRunning() else {
self._dropPending(id, resumingWith: SourceKitLSPError.notRunning)
return
}
self._send(framed)
}
}
group.addTask {
try await Task.sleep(nanoseconds: UInt64(timeoutSeconds * nanosecondsPerSecond))
throw SourceKitLSPError.timedOut(method: method)
}
defer { group.cancelAll() }
do {
guard let first: Data = try await group.next() else {
throw SourceKitLSPError.timedOut(method: method)
}
return first
} catch {
// On timeout / failure, resume and drop the still-pending request
// continuation so its child task completes (cancelAll() alone does
// not wake a suspended continuation) and the group can return.
_dropPending(id, resumingWith: error)
throw error
}
}
}
private func notify(method: String, params: [String: Any]) {
if let framed: Data = _frame(id: nil, method: method, params: params) {
_send(framed)
}
}
/// Build a `Content-Length`-framed JSON-RPC message. Pure; no shared state.
private func _frame(id: Int?, method: String, params: [String: Any]) -> Data? {
var payload: [String: Any] = ["jsonrpc": "2.0", "method": method, "params": params]
if let id: Int = id { payload["id"] = id }
guard let body: Data = try? JSONSerialization.data(withJSONObject: payload) else { return nil }
var framed: Data = Data("Content-Length: \(body.count)\r\n\r\n".utf8)
framed.append(body)
return framed
}
/// Write a pre-framed message to the server's stdin, unless shut down.
private func _send(_ framed: Data) {
_lock.lock()
let running: Bool = _running
_lock.unlock()
guard running else { return }
_stdin.fileHandleForWriting.write(framed)
}
// MARK: - Reader
private func _startReader() {
let handle: FileHandle = _stdout.fileHandleForReading
let thread: Thread = Thread { [weak self] in
while true {
guard let self: SourceKitLSPClient else { return }
self._lock.lock(); let running: Bool = self._running; self._lock.unlock()
guard running else { return }
let chunk: Data = handle.availableData
if chunk.isEmpty {
// EOF — the server exited. Mark not-running so later `_send`s
// don't write to a dead pipe (EPIPE/SIGPIPE), and fail any
// in-flight requests instead of letting them hang to timeout.
self._setRunning(false)
self._failAllPending(with: SourceKitLSPError.notRunning)
return
}
self._lock.lock()
self._readBuffer.append(chunk)
let bodies: [Data] = self._drainMessagesLocked()
self._lock.unlock()
for body: Data in bodies {
self._dispatch(body)
}
}
}
thread.name = "lyrebird.sourcekit-lsp.reader"
thread.start()
}
/// Slice out as many complete `Content-Length`-framed message bodies as are
/// buffered, returning each raw JSON body. Caller holds `_lock`.
private func _drainMessagesLocked() -> [Data] {
var out: [Data] = []
let headerTerminator: Data = Data("\r\n\r\n".utf8)
while true {
guard let headerEnd: Range<Data.Index> = _readBuffer.range(of: headerTerminator) else { break }
let header: String = String(data: _readBuffer[_readBuffer.startIndex..<headerEnd.lowerBound],
encoding: .utf8) ?? ""
var contentLength: Int = 0
for line: Substring in header.split(separator: "\r\n") {
let parts: [Substring] = line.split(separator: ":", maxSplits: 1)
if parts.count == 2, parts[0].trimmingCharacters(in: .whitespaces) == "Content-Length" {
contentLength = Int(parts[1].trimmingCharacters(in: .whitespaces)) ?? 0
}
}
let bodyStart: Data.Index = headerEnd.upperBound
let available: Int = _readBuffer.distance(from: bodyStart, to: _readBuffer.endIndex)
guard available >= contentLength else { break } // wait for more bytes
let bodyEnd: Data.Index = _readBuffer.index(bodyStart, offsetBy: contentLength)
out.append(Data(_readBuffer[bodyStart..<bodyEnd]))
_readBuffer.removeSubrange(_readBuffer.startIndex..<bodyEnd)
}
return out
}
private func _dispatch(_ body: Data) {
guard let message: [String: Any] = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any]
else { return }
// Only responses (carrying our request id) are of interest; server
// notifications (diagnostics, logging) and server→client requests are
// ignored. sourcekit-lsp tolerates unanswered server requests here.
guard let id: Int = message["id"] as? Int else { return }
_lock.lock()
let cont: CheckedContinuation<Data, Error>? = _pending.removeValue(forKey: id)
_lock.unlock()
guard let cont: CheckedContinuation<Data, Error> = cont else { return }
if let error: [String: Any] = message["error"] as? [String: Any] {
let code: Int = error["code"] as? Int ?? 0
let msg: String = error["message"] as? String ?? "unknown"
cont.resume(throwing: SourceKitLSPError.serverError(code: code, message: msg))
return
}
// Hand the raw body back; the caller parses `result` for its own shape.
cont.resume(returning: body)
}
}
#endif
@@ -0,0 +1,39 @@
// SourceKitLSPError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// Errors surfaced by ``SourceKitLSPClient``. macOS only.
#if os(macOS)
/// A failure from the `sourcekit-lsp` client.
public enum SourceKitLSPError: Error, CustomStringConvertible {
/// The `sourcekit-lsp` executable could not be launched (bad path, missing
/// toolchain, spawn failure). Thrown from ``SourceKitLSPClient/start(rootURI:)``.
case launchFailed(String)
/// A request was made against a client that was never started or has been
/// shut down (or the server exited). Also used to fail in-flight requests
/// when the server dies.
case notRunning
/// A request exceeded the client's per-request timeout. Guards against a
/// wedged server; carries the LSP method that timed out.
case timedOut(method: String)
/// The server returned a JSON-RPC error response, carrying its code and
/// message.
case serverError(code: Int, message: String)
public var description: String {
switch self {
case .launchFailed(let m): return "sourcekit-lsp failed to launch: \(m)"
case .notRunning: return "sourcekit-lsp is not running"
case .timedOut(let m): return "sourcekit-lsp timed out on \(m)"
case .serverError(let c, let m): return "sourcekit-lsp error \(c): \(m)"
}
}
}
#endif
@@ -0,0 +1,56 @@
// SwapQuantize.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// `SwapQuantize` chooses when a named-slot swap becomes audible: immediately, or
// aligned to the next beat / bar of a `LyrebirdClock`. Quantizing the swap to a
// musical boundary is what masks compile latency — the `swiftc` build finishes a
// few hundred ms after ⌘↩, then the swap lands exactly on the downbeat rather
// than whenever the compile happened to finish.
#if os(macOS)
import Foundation
import LyrebirdSynth
/// When a ``LiveSession`` named-slot swap becomes audible.
///
/// Set on ``LiveSession/swapQuantize`` together with a ``LiveSession/swapClock``.
/// With no clock, or `.immediate`, a swap takes effect right away. `.nextBeat` /
/// `.nextBar` schedule the new voice's add and the old voice's removal at the
/// same upcoming boundary sample time, so the swap is glitch-free and on-grid.
public enum SwapQuantize: Sendable, Equatable {
/// Swap immediately, as soon as the snippet runs.
case immediate
/// Swap on the next whole beat boundary.
case nextBeat
/// Swap on the next bar boundary, where a bar is `beatsPerBar` beats.
case nextBar(beatsPerBar: Int)
/// The absolute clock beat this quantization targets from *now*, or `nil`
/// for `.immediate`. `.nextBeat` returns the next whole beat; `.nextBar`
/// returns the next multiple of `beatsPerBar` beats.
///
/// Reads `clock.currentBeat` once; the returned beat is strictly in the
/// future for a running clock (a whole-numbered current beat rounds up to
/// the following boundary, matching `LyrebirdClock.nextBeat`).
public func targetBeat(clock: LyrebirdClock) -> Double? {
switch self {
case .immediate:
return nil
case .nextBeat:
return floor(clock.currentBeat) + 1.0
case .nextBar(let beatsPerBar):
let bar: Double = Double(max(1, beatsPerBar))
return (floor(clock.currentBeat / bar) + 1.0) * bar
}
}
}
#endif
@@ -0,0 +1,38 @@
// EditorPositionMapping.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile
//
// Maps an `NSTextView` UTF-16 insertion offset to a zero-based (line, character)
// position. LSP positions are UTF-16-based, matching `NSTextView`'s own offsets,
// so no re-encoding is needed — only newline counting.
#if os(macOS)
/// Convert a UTF-16 offset into `text` to a zero-based `(line, character)`
/// where `character` is a UTF-16 code-unit column — the coordinate space
/// `sourcekit-lsp` expects. An offset past the end clamps to the final position.
func editorLineAndUTF16Char(in text: String, utf16Offset: Int) -> (line: Int, character: Int) {
let units: String.UTF16View = text.utf16
var idx: String.UTF16View.Index = units.startIndex
var consumed: Int = 0
var line: Int = 0
var character: Int = 0
let newline: UInt16 = 10
while consumed < utf16Offset, idx < units.endIndex {
if units[idx] == newline {
line += 1
character = 0
} else {
character += 1
}
idx = units.index(after: idx)
consumed += 1
}
return (line, character)
}
#endif
@@ -41,11 +41,18 @@ window.open {
| Shortcut | Action |
|----------|--------|
| ⌘↩ | Compile + run. Removes synths from the previous run before executing. |
| ⌘↩ | Compile + run. Removes the previous run's *anonymous* synths first (named slots persist). |
| ⌘⇧↩ | Compile + run additively. Keeps previously played synths in the engine. |
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
`LiveSession.clearTracked()` directly.
``LyrebirdScratchModel/clearTracked()`` — a full reset that removes both the
anonymous tracked synths and every named slot.
The engine status pill at the top-left is also a **Start/Stop** button
(``LyrebirdScratchModel/toggleEngine()``): green "engine running" when live,
red "▶ start engine" when stopped. A snippet is only audible while the engine
is running; the host normally starts it at launch, but this lets the user
recover from a failed start (e.g. no output device) without relaunching.
## Snippet API surface
@@ -55,32 +62,236 @@ A snippet has one local in scope:
context: SnippetContext
```
`SnippetContext` is intentionally minimal in v1:
`SnippetContext`:
- `context.engine` — the host `SynthesisEngine`.
- `context.play(_:)` — add a `Synthesizer` to the engine and register it for
cleanup on the next non-additive run.
- `context.play { <graph> }` — play a bare generator graph, no `SynthesizerBase`
subclass needed (wraps it in a `ClosureSynthesizer`).
- `context.play(slot:_:)` / `context.play(slot:) { <graph> }` — play into a
**named slot** (see below).
- `context.reportMessage(_:)` — write back to the host (used by tests; handy for
`print`-style probes during development).
## Named slots (hot-swap)
`context.play(slot: "name") { … }` installs a voice under a name. Re-running a
slot definition **replaces just that voice in place** — the new voice starts
before the old one is removed (a brief overlap, no gap), while everything else
keeps playing:
```swift
context.play(slot: "bass") { OscSaw.Audio(freq: 55, mul: 0.2) }
context.play(slot: "lead") { Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0) }
```
Unlike anonymous `context.play`, a slotted voice is **not** torn down by the
next non-additive (⌘↩) run — that is what lets you edit and re-evaluate one
voice at a time while the rest of the patch keeps going (the `Pdef` idiom).
| API | Lifetime |
|-----|----------|
| `context.play(_:)` / `context.play { }` | Removed on the next non-additive run. |
| `context.play(slot:) { }` | Persists; a same-name re-run replaces it in place. |
Clear a slot with `context.session.clearSlot("bass")`, all slots with
`context.session.clearSlots()`. The toolbar **Clear Synths** button is a full
reset — anonymous synths *and* every slot. A slot definition you delete from the
buffer and stop re-running is *not* auto-removed (a `Pdef`-style gotcha) — clear
it explicitly or hit Clear Synths.
## Threading
All UI is `@MainActor`-isolated. `LiveSession.compileAndRun` is invoked
synchronously inside the button action, so the editor freezes for the duration
of the `swiftc` invocation (≈ 1 second cold, much faster on warm cache). v1
accepts that trade-off; an off-main compile path is on the polish list.
All UI is `@MainActor`-isolated. The Run / Run Additive actions dispatch a
`Task` that awaits ``LyrebirdScratchModel/run(additive:)``, which awaits
`LiveSession.compileAndRunAsync` — the `swiftc` subprocess runs on a background
`Task.detached`, so the editor stays responsive while a compile is in flight.
The snippet entry then resumes on the main actor to touch engine + UI state.
`LyrebirdScratchMenuController` disables the Run / Run Additive commands
whenever ``ReevalState/canEvaluate`` is `false` (a compile is in flight or the
buffer is empty); `run(additive:)` additionally guards re-entrancy on
``LyrebirdScratchModel/isCompiling``.
## Re-evaluation readiness
``LyrebirdScratchModel/reevalState`` publishes a ``ReevalState`` — a structured
signal for *when* a re-evaluation is available and whether it would change
anything:
| State | Meaning |
|-------|---------|
| `.empty` | Buffer is blank. Nothing to run. |
| `.dirty` | Edited since the last run (or never run). An eval is available. |
| `.compiling` | A compile + run is in flight. |
| `.queued(untilBeat:)` | Compiled; a quantized slot swap is scheduled but not yet audible (see below). |
| `.clean` | Buffer matches what is currently playing. |
| `.failed(diagnosticCount:)` | The last run failed to compile. |
The editor renders this as a colored dot + label in the status bar.
``ReevalState/canEvaluate`` is `true` whenever a run can be triggered right now
(non-blank buffer, no compile already running) — hosts can gate their own Run
controls on it.
## Quantized swaps (on-beat latency masking)
A `swiftc` build finishes a few hundred milliseconds after ⌘↩ — long enough to
feel loose against a running groove. Point the session at a `LyrebirdClock` and
choose a `SwapQuantize` mode, and named-slot swaps land on the next musical
boundary instead of whenever the compile happens to finish:
```swift
let clock = LyrebirdClock(engine: engine, bpm: 120)
let session = LiveSession(engine: engine)
session.swapClock = clock
session.swapQuantize = .nextBar(beatsPerBar: 4) // .immediate | .nextBeat | .nextBar
```
Now `context.play(slot: "bass") { … }` **schedules** the new voice's add and the
old voice's removal at the same upcoming boundary sample time (`engine.schedule` /
`engine.remove(_:at:)`), so the swap is glitch-free and on-grid. Because the
change is quantized to a boundary that is comfortably past the compile, the
compile latency is hidden: you edit, hit ⌘↩, and the change drops exactly on the
downbeat.
While the swap is pending, ``LyrebirdScratchModel/reevalState`` reads
`.queued(untilBeat:)` (a purple badge); it settles to `.clean` once the clock
passes the boundary (or `.dirty` if you edit again first). ``LiveSession/pendingSwapBeat``
exposes the target beat. `.immediate` (or no `swapClock`) makes swaps take effect
at once. Anonymous `context.play` is unaffected; quantization applies to named
slots only.
Re-running a slot while its previous quantized swap is still pending is safe: the
previous voice's removal is always scheduled no earlier than its own add, so a
just-scheduled voice is never left orphaned.
## First-run latency (module-cache prewarm)
A snippet compiles in ~0.1 s once the Swift/Clang module cache is warm — but the
*first* compile of a session pays ~2–3 s to build the precompiled module for the
large `LyrebirdSynth` interface. Left alone, that cost lands on the user's first
⌘↩ (the "time to first sound").
``LiveSession/prewarm()`` moves it into the background: it type-checks a trivial
import-only snippet on a detached `.utility` task, warming swiftc's default
module cache so the first real compile is already fast. `LyrebirdScratchView`
calls it from `onAppear` (idempotent — safe to call again). It is *not* wired
into `LyrebirdScratchModel.init`, so constructing a model never shells out to
swiftc; a headless host should call `session.prewarm()` at launch itself.
A prewarm never throws: a failure (e.g. a missing toolchain) leaves
``LiveSession/isPrewarmed`` `false` — so a later call retries, and the first
real compile simply pays the cold build itself and surfaces any real error
through its own diagnostics.
> Note: the prewarm deliberately uses swiftc's default module cache rather than a
> pinned `-module-cache-path`. A freshly-built dedicated cache produces module
> metadata that diverges from the already-loaded `libLyrebirdLiveCompileDynamic`,
> which turns a benign ObjC class-duplication warning into a hard cast crash when
> a snippet is `dlopen`'d.
## Code completion
Swift code completion is provided by the toolchain's `sourcekit-lsp`, driven over
stdio by ``SourceKitLSPClient`` and bridged to the editor by
``SnippetCompletionService``. Typing `.` after an expression pops the standard
completion window; the candidates are the real symbols the snippet would see at
compile time — `LyrebirdSynth` generators (`OscSin.` → `Audio`, `Control`, …),
the injected `context` (`context.` → `play`, `engine`, …), and the Swift
standard library.
How it resolves those symbols for an otherwise free-standing file: the service
maintains a small temp workspace holding the snippet **wrapped** in the same
`SnippetHarness` preamble the compiler uses, next to a `compile_commands.json`
carrying the host `LiveSession`'s `-I` / module-map / link flags. sourcekit-lsp's
compilation-database build system reads that file. The caret is mapped through
the harness line offset, so a completion request at the user's row hits the right
row in the wrapped document. Completion is Swift-mode only — graph-DSL mode is
interpreted and needs no compiler — and best-effort: any LSP failure yields no
candidates rather than an error.
## Limitations
- macOS only.
- No syntax highlighting, code completion, or line-number gutter (deferred).
- Compiled dylibs are leaked by design — types in a loaded snippet may still be
referenced by tracked synths; unloading is unsafe.
- Syntax highlighting is a lightweight built-in lexer (`ScratchSwiftTokenizer`) —
approximate by design, not a full parser. Completion (above) uses the real
compiler via sourcekit-lsp; the two are independent.
- Completion currently triggers on `.`; a manual-invoke shortcut is a possible
follow-up.
- The host `.app` must not be sandboxed and must allow library validation to be
disabled, since `swiftc` is invoked via `Process` and the resulting unsigned
dylib is `dlopen`'d.
## Snippet memory (the dylib leak)
Every ⌘↩ compiles a fresh dylib and `dlopen`s it; those dylibs are **never
unloaded**, so a session's mapped memory grows one dylib per successful
evaluation. ``LiveSession/loadedSnippetCount`` reports how many are mapped — a
host can nudge the user to restart after a very long session.
This is a hard limit of the compiled approach, not an oversight. Reclaiming the
memory would require `dlclose`, which is **unsafe** for these dylibs: `dlopen`
registers a Swift dylib's type metadata and protocol-conformance records into
process-global runtime caches, and `dlclose` unmaps the dylib without
deregistering them — leaving those caches pointing into freed memory, so a later
type operation can crash. That holds even after every synth a snippet produced
has been removed. A refcount-gated `dlclose` was therefore considered and
rejected rather than shipped as a crash-prone flag.
``LiveSession/resetAll()`` (the toolbar **Clear Synths**) is the pressure-relief
valve: it stops all snippet audio — removing every anonymous and slotted synth —
and gives a clean slate without tearing down the engine, but it does not reclaim
the mapped dylibs. Only restarting the process does. The **Graph DSL mode**
below sidesteps dylibs entirely and is the structural fix.
The editor makes this visible rather than silent: the engine bar shows a
**"snippets: N"** count (`LyrebirdScratchModel.loadedSnippetCount`), and once it
crosses ``LyrebirdScratchModel/snippetRestartThreshold`` (50) the count turns
orange and a warning banner appears — nudging the user to restart to reclaim the
memory, or to switch to Graph DSL mode (which maps no dylibs). It is a nudge, not
a hard stop: the choice stays with the user.
## Graph DSL mode (instant, no compile)
The status-bar toggle switches the editor between two evaluators:
- **Swift** — the full snippet path above: swiftc compiles a dylib, which is
`dlopen`'d and run. The whole language, `SynthesizerBase` subclasses, arbitrary
code — at the cost of a compile and a permanently mapped dylib.
- **Graph DSL** — the interpreted graph-DSL. The buffer is lexed, parsed, and
built into a generator graph **in-process**: no swiftc, no dylib, microseconds
instead of a compile round-trip, and nothing leaks. The trade is scope — only
generator-graph *expressions*, not arbitrary Swift.
A DSL buffer is one statement per line:
```
bass = OscSawtooth.Audio(freq: 55, mul: 0.15)
Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0)
```
- A **bare** line plays anonymously and is tracked, so a non-additive re-run
(⌘↩) replaces it — exactly like `context.play { … }`.
- A **named** line (`name = …`) installs a persistent, hot-swappable named slot
(like `context.play(slot:)`): it survives a non-additive re-run and is swapped
in place on the next evaluation, so you can mutate one voice while others keep
playing. Quantized swaps apply here too.
Generators are spelled **exactly** as in a Lyrebird `build()` —
`OscSin.Audio(freq:)`, `.Control` for the control-rate variant — so a graph you
like in the editor pastes into a project unchanged (only the wrapping differs;
see the `LyrebirdGraphDSL` design notes). The bare `OscSin(…)` no-rate form is a
DSL shorthand for the audio variant.
The whole program is built **before** any engine mutation, so a syntax or build
error leaves the currently-playing graph untouched — a bad edit never drops
audio. Errors surface in the same gutter as swiftc diagnostics: a parse error
points at its line/column; a build error (unknown generator, bad argument)
reports at file scope. See ``LyrebirdScratchModel/switchMode(to:)`` and
``LiveSession/runGraphDSL(_:additive:resources:)``.
## Topics
- ``LyrebirdScratchView``
- ``LyrebirdScratchModel``
- ``ScratchEvalMode``
@@ -13,8 +13,12 @@ import LyrebirdLiveCompile
/// Builds and installs the macOS application menu bar for a live-coding host
/// driven by a `LyrebirdScratchModel`. Owns the action targets so menu items
/// stay wired for the lifetime of the controller.
///
/// Conforms to `NSMenuItemValidation` so the Run / Run Additive commands
/// disable when the buffer cannot be evaluated — i.e. while a compile is in
/// flight or the buffer is empty (``ReevalState/canEvaluate``).
@MainActor
public final class LyrebirdScratchMenuController: NSObject {
public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation {
public let model: LyrebirdScratchModel
@@ -201,6 +205,21 @@ public final class LyrebirdScratchMenuController: NSObject {
return item
}
// MARK: - Menu validation
/// Disable the Run / Run Additive commands whenever the buffer cannot be
/// evaluated (a compile is in flight, or the buffer is empty). All other
/// items stay enabled. AppKit calls this automatically for items whose
/// target is this controller.
public func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
switch menuItem.action {
case #selector(runSnippet(_:)), #selector(runSnippetAdditive(_:)):
return model.reevalState.canEvaluate
default:
return true
}
}
// MARK: - Action targets
private func target(_ item: NSMenuItem) -> NSMenuItem {
@@ -42,27 +42,54 @@ public final class LyrebirdScratchModel: ObservableObject {
// ⌘⇧↩ — additive run (keep previously played synths around).
//
// The snippet body has `context: SnippetContext` in scope.
// `context.engine` → the host `SynthesisEngine`.
// `context.play(synth)` → adds a `Synthesizer` and tracks it for cleanup.
// `context.reportMessage(_)`→ writes back to the host (useful for `print`-style probes).
// `context.play { <graph> }` → play a bare generator graph, no subclass needed.
// `context.play(synth)` → add a `Synthesizer` you declared.
// `context.engine` → the host `SynthesisEngine`.
// `context.reportMessage(_)` → write back to the host (`print`-style probes).
class SineSynth: SynthesizerBase {
override func build() {
let sine = OscSin.Audio(freq: 440, mul: 0.15)
let stereo = Pan2(input: sine, pan: 0)
output(bus: 0, source: stereo)
}
}
let synth = SineSynth()
_ = context.play(synth)
context.play { Pan2(input: OscSin.Audio(freq: 440, mul: 0.15), pan: 0) }
context.reportMessage("playing 440 Hz sine — stereo, centered")
"""
/// Placeholder for the interpreted graph-DSL mode. Shows the instant path:
/// no `context`, no subclass — just generator-graph expressions, one per
/// line, spelled exactly as they would be in a Lyrebird `build()`.
public nonisolated static let graphDSLPlaceholder: String = """
# Graph DSL — instant, no compile. One graph expression per line.
# A bare line plays anonymously; `name = …` plays a named, hot-swappable slot.
# Generators are spelled exactly as in Swift: OscSin.Audio(freq: 440) * 0.1
bass = OscSawtooth.Audio(freq: 55, mul: 0.15)
Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0)
"""
/// The seed text for a given evaluation mode.
public nonisolated static func defaultPlaceholder(for mode: ScratchEvalMode) -> String {
switch mode {
case .swift: return defaultPlaceholder
case .graphDSL: return graphDSLPlaceholder
}
}
/// Current editor text. View binds to this; user edits flow back here via
/// the `NSTextView` delegate inside `LyrebirdScratchView`.
@Published public var text: String
///
/// Edits recompute ``reevalState`` (unless a compile is in flight, which
/// owns the state until it resolves).
@Published public var text: String {
didSet { recomputeReevalStateAfterEdit() }
}
/// Structured re-evaluation readiness signal. See ``ReevalState``. The view
/// binds a status badge to this and gates the Run controls on
/// ``ReevalState/canEvaluate``.
@Published public private(set) var reevalState: ReevalState
/// Text of the most recent *successful* run. `nil` before the first
/// successful run. Compared against ``text`` to decide `.clean` vs `.dirty`.
private var lastEvaluatedText: String?
/// Parsed swiftc diagnostics from the last `run(additive:)` invocation.
/// Empty when the last run compiled cleanly or has not yet been attempted.
@@ -76,6 +103,37 @@ public final class LyrebirdScratchModel: ObservableObject {
/// `clearTracked` call so the toolbar can show the count without polling.
@Published public private(set) var trackedSynthCount: Int
/// Mirror of `session.loadedSnippetCount` — compiled snippet dylibs mapped
/// into the process this session. Each successful **Swift-mode** run maps
/// one; they are never unloaded (`dlclose` is unsafe for Swift dylibs — see
/// ``LiveSession/resetAll()``), so this only grows until a process restart.
/// Graph-DSL runs add nothing. Refreshed alongside ``trackedSynthCount``.
@Published public private(set) var loadedSnippetCount: Int
/// Count of mapped snippet dylibs past which the editor nudges the user to
/// restart (or switch to the leak-free Graph DSL mode).
public nonisolated static let snippetRestartThreshold: Int = 50
/// A restart suggestion once ``loadedSnippetCount`` reaches
/// ``snippetRestartThreshold``, else `nil`. The mapped dylibs cannot be
/// reclaimed without a process restart (by design), so this is the
/// user-facing safety valve over that leak.
public var snippetMemoryHint: String? {
LyrebirdScratchModel.snippetMemoryHint(count: loadedSnippetCount)
}
/// Pure form of ``snippetMemoryHint`` — the message for `count` mapped
/// snippets, or `nil` below `threshold`. Factored out so the boundary is
/// unit-testable without running dozens of real compiles.
nonisolated static func snippetMemoryHint(
count: Int,
threshold: Int = LyrebirdScratchModel.snippetRestartThreshold
) -> String? {
guard count >= threshold else { return nil }
return "\(count) compiled snippets are mapped and can't be freed without "
+ "restarting. Restart to reclaim memory, or use Graph DSL mode (no compile, no leak)."
}
/// `true` while a `run(additive:)` invocation is awaiting the background
/// swiftc compile. View code disables Run / Run Additive buttons against
/// this so a second compile cannot stack on top of a still-running one.
@@ -93,8 +151,39 @@ public final class LyrebirdScratchModel: ObservableObject {
/// horizontally.
@Published public var wrapsLines: Bool = true
/// Which evaluator ``run(additive:)`` sends the buffer through. `.swift`
/// compiles a snippet dylib; `.graphDSL` interprets a generator graph
/// instantly. Toggle via ``switchMode(to:)`` so the seed placeholder swaps
/// with the mode. See ``ScratchEvalMode``.
@Published public private(set) var evalMode: ScratchEvalMode = .swift
public let session: LiveSession
/// Lazily-created code-completion service (Swift mode only). Spun up on the
/// first completion request so a session that never triggers completion
/// never launches `sourcekit-lsp`.
private var _completion: SnippetCompletionService?
/// Fetch Swift code-completion candidates for the current buffer at a
/// zero-based user-space `line` / `character` (UTF-16). Returns `[]` in
/// graph-DSL mode (the interpreter needs no LSP) or on any LSP failure —
/// completion is best-effort and never surfaces an error to the editor.
public func completionItems(line: Int, character: Int) async -> [LSPCompletionItem] {
guard evalMode == .swift else { return [] }
let service: SnippetCompletionService
if let existing: SnippetCompletionService = _completion {
service = existing
} else {
service = SnippetCompletionService(session: session)
_completion = service
}
do {
return try await service.completions(userBody: text, line: line, character: character)
} catch {
return []
}
}
public nonisolated static let minFontSize: CGFloat = 9
public nonisolated static let maxFontSize: CGFloat = 32
public nonisolated static let defaultFontSize: CGFloat = 13
@@ -124,6 +213,44 @@ public final class LyrebirdScratchModel: ObservableObject {
self.session = session
self.text = initialText
self.trackedSynthCount = session.trackedSynthCount
self.loadedSnippetCount = session.loadedSnippetCount
// No run yet: blank buffer is `.empty`, otherwise `.dirty` (runnable,
// never evaluated). `lastEvaluatedText` stays nil until a run succeeds.
self.reevalState = LyrebirdScratchModel.isBlank(initialText) ? .empty : .dirty
}
/// Whether `text` is empty once whitespace and newlines are stripped.
private nonisolated static func isBlank(_ text: String) -> Bool {
text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
/// Recompute ``reevalState`` from the current buffer after a user edit.
/// A no-op while a compile is in flight — the run owns the state until it
/// resolves (edits made mid-compile are re-evaluated once it finishes).
private func recomputeReevalStateAfterEdit() {
guard !isCompiling else { return }
reevalState = derivedIdleState()
}
/// Settle a `.queued` state once its scheduled swap has become audible.
/// Called on the editor's heartbeat (the view's refresh timer): when the
/// session no longer reports a pending swap, drop back to the idle state
/// (`.clean`, or `.dirty` if the buffer was edited while queued). No-op
/// unless the current state is `.queued`.
public func refreshQueuedState() {
guard case .queued = reevalState else { return }
if session.pendingSwapBeat == nil {
reevalState = derivedIdleState()
}
}
/// The readiness state implied by the current buffer when no compile is in
/// flight: `.empty` for a blank buffer, `.clean` when it matches the last
/// successful run, `.dirty` otherwise.
private func derivedIdleState() -> ReevalState {
if LyrebirdScratchModel.isBlank(text) { return .empty }
if let last: String = lastEvaluatedText, last == text { return .clean }
return .dirty
}
/// Compile and execute the current `text`. Updates `diagnostics`,
@@ -140,19 +267,30 @@ public final class LyrebirdScratchModel: ObservableObject {
/// without throwing; `false` otherwise.
@discardableResult
public func run(additive: Bool) async -> Bool {
switch evalMode {
case .swift: return await runSwiftSnippet(additive: additive)
case .graphDSL: return runGraphDSLBuffer(additive: additive)
}
}
/// Swift path: compile the buffer to a dylib off-main and run it.
private func runSwiftSnippet(additive: Bool) async -> Bool {
guard !isCompiling else { return false }
let body: String = text
diagnostics = []
statusMessage = "Compiling…"
isCompiling = true
reevalState = .compiling
defer {
isCompiling = false
trackedSynthCount = session.trackedSynthCount
loadedSnippetCount = session.loadedSnippetCount
}
do {
try await session.compileAndRunAsync(body, additive: additive)
let mode: String = additive ? "additive" : "replaced"
statusMessage = "Ran (\(mode)). Tracked synths: \(session.trackedSynthCount)."
settleReevalAfterSuccess(body: body)
return true
} catch let sessionError as LiveSessionError {
switch sessionError {
@@ -173,19 +311,122 @@ public final class LyrebirdScratchModel: ObservableObject {
}
case .compilerError(let underlying):
statusMessage = "Compiler error: \(underlying)"
case .graphDSLFailed(let diags, _):
// Not expected on the Swift path, but map it faithfully.
diagnostics = diags
statusMessage = "DSL error — \(diags.count) diagnostic(s)."
}
reevalState = .failed(diagnosticCount: diagnostics.count)
return false
} catch {
statusMessage = "Error: \(error)"
reevalState = .failed(diagnosticCount: diagnostics.count)
return false
}
}
/// Forward to `LiveSession.clearTracked()` and refresh `trackedSynthCount`.
/// Graph-DSL path: interpret the buffer in-process — instant, no swiftc, so
/// no `isCompiling` spinner and no `await`. A parse/build failure leaves the
/// currently-playing graph untouched (the session builds before it mutates).
private func runGraphDSLBuffer(additive: Bool) -> Bool {
guard !isCompiling else { return false }
let body: String = text
diagnostics = []
defer {
trackedSynthCount = session.trackedSynthCount
loadedSnippetCount = session.loadedSnippetCount
}
do {
try session.runGraphDSL(body, additive: additive)
let mode: String = additive ? "additive" : "replaced"
statusMessage = "Ran DSL (\(mode)). Tracked synths: \(session.trackedSynthCount)."
settleReevalAfterSuccess(body: body)
return true
} catch let sessionError as LiveSessionError {
if case .graphDSLFailed(let diags, _) = sessionError {
diagnostics = diags
let plural: String = diags.count == 1 ? "" : "s"
statusMessage = "DSL error — \(diags.count) diagnostic\(plural)."
} else {
statusMessage = "Error: \(sessionError)"
}
reevalState = .failed(diagnosticCount: diagnostics.count)
return false
} catch {
statusMessage = "Error: \(error)"
reevalState = .failed(diagnosticCount: diagnostics.count)
return false
}
}
/// Record the just-run text as the baseline and settle the readiness state:
/// `.queued` when the buffer is unchanged and a quantized slot swap is
/// scheduled but not yet audible, otherwise the derived idle state (`.clean`,
/// or `.dirty` if the buffer was edited while the run was in flight).
private func settleReevalAfterSuccess(body: String) {
lastEvaluatedText = body
let idle: ReevalState = derivedIdleState()
if idle == .clean, let beat: Double = session.pendingSwapBeat {
reevalState = .queued(untilBeat: beat)
} else {
reevalState = idle
}
}
/// Switch evaluation mode. When the buffer still holds the *current* mode's
/// untouched placeholder, swap in the target mode's placeholder so the seed
/// example matches the mode; any edited buffer is left as-is.
///
/// The new mode's evaluator has not run whatever is on screen, so the last-run
/// baseline is dropped (the buffer reads as `.dirty`) and any diagnostics from
/// a prior run in the old mode are cleared — leaving them would show gutter
/// markers against a buffer the current mode never evaluated.
public func switchMode(to mode: ScratchEvalMode) {
guard mode != evalMode else { return }
if text == LyrebirdScratchModel.defaultPlaceholder(for: evalMode) {
text = LyrebirdScratchModel.defaultPlaceholder(for: mode)
}
lastEvaluatedText = nil
diagnostics = []
evalMode = mode
reevalState = derivedIdleState()
}
/// Start the audio engine if stopped, or stop it if running. Surfaces the
/// outcome (including a start failure — e.g. no audio device) on the status
/// line. The host normally starts the engine at launch; this lets the user
/// see the state and recover from a failed start without relaunching.
public func toggleEngine() {
let engine: SynthesisEngine = session.engine
if engine.isRunning {
engine.stop()
statusMessage = "Engine stopped."
} else {
do {
try engine.start()
statusMessage = "Engine started."
} catch {
statusMessage = "Engine failed to start: \(error)"
}
}
}
/// Full reset: remove both the anonymous tracked synths *and* every named
/// slot from the engine, then refresh `trackedSynthCount`.
///
/// Clearing the engine means nothing the buffer produced is still playing,
/// so the "last run" baseline is dropped and the buffer reads as `.dirty`
/// (or `.empty`) — a re-evaluation is again meaningful.
public func clearTracked() {
session.clearTracked()
session.resetAll()
trackedSynthCount = session.trackedSynthCount
statusMessage = "Cleared tracked synths."
// `resetAll` stops audio but does NOT unload the compiled snippet dylibs
// (unsafe), so the mapped-snippet count is unchanged — refresh the mirror
// so the UI stays truthful about it.
loadedSnippetCount = session.loadedSnippetCount
statusMessage = "Cleared all synths (tracked + slots)."
lastEvaluatedText = nil
reevalState = derivedIdleState()
}
// MARK: - Snippet save / load
@@ -197,10 +438,14 @@ public final class LyrebirdScratchModel: ObservableObject {
/// `NSOpenPanel` UI; this method does the IO.
public func load(from url: URL) throws {
let loaded: String = try String(contentsOf: url, encoding: .utf8)
// Drop the run baseline first so the `text` didSet — and the explicit
// recompute below — treat freshly loaded content as unrun (`.dirty`).
lastEvaluatedText = nil
text = loaded
documentURL = url
diagnostics = []
statusMessage = "Loaded \(url.lastPathComponent)."
reevalState = derivedIdleState()
}
/// Write `text` to `url` as UTF-8, set ``documentURL``, refresh status.
@@ -45,12 +45,15 @@ import LyrebirdLiveCompile
///
/// ## Threading
///
/// All UI work is `@MainActor`-isolated. The Run / Run Additive buttons
/// dispatch a `Task` that awaits `LyrebirdScratchModel.run(additive:)`, which
/// itself awaits `LiveSession.compileAndRunAsync`. The swiftc subprocess runs
/// on a background `Task.detached`; the snippet entry then resumes on the
/// main actor so it can touch UI-side state. Both Run buttons disable while
/// ``LyrebirdScratchModel/isCompiling`` is `true`.
/// All UI work is `@MainActor`-isolated. The Run / Run Additive commands (in the
/// menu bar built by ``LyrebirdScratchMenuController``) dispatch a `Task` that
/// awaits `LyrebirdScratchModel.run(additive:)`, which itself awaits
/// `LiveSession.compileAndRunAsync`. The swiftc subprocess runs on a background
/// `Task.detached`; the snippet entry then resumes on the main actor so it can
/// touch UI-side state. The menu controller gates the Run commands on
/// ``ReevalState/canEvaluate`` (disabled while a compile is in flight or the
/// buffer is empty); `run(additive:)` additionally guards re-entrancy on
/// ``LyrebirdScratchModel/isCompiling``.
@MainActor
public struct LyrebirdScratchView: View {
@@ -84,6 +87,10 @@ public struct LyrebirdScratchView: View {
public var body: some View {
VStack(spacing: 0) {
engineBar
if let hint: String = model.snippetMemoryHint {
Divider()
snippetMemoryBanner(hint)
}
Divider()
ScratchEditor(
text: Binding(
@@ -91,7 +98,10 @@ public struct LyrebirdScratchView: View {
set: { model.text = $0 }
),
fontSize: model.fontSize,
wrapsLines: model.wrapsLines
wrapsLines: model.wrapsLines,
requestCompletions: { line, character in
await model.completionItems(line: line, character: character)
}
)
.frame(minHeight: editorMinHeight)
Divider()
@@ -102,18 +112,37 @@ public struct LyrebirdScratchView: View {
}
}
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
.onReceive(engineRefresh) { _ in engineTick &+= 1 }
.onAppear {
// Warm the module cache in the background so the first ⌘↩ is ~0.1 s
// instead of paying the ~2–3 s cold `LyrebirdSynth` .pcm build.
// Idempotent — safe if `onAppear` fires again.
model.session.prewarm()
}
.onReceive(engineRefresh) { _ in
engineTick &+= 1
// Settle a `.queued` readiness badge once its swap has fired.
model.refreshQueuedState()
}
}
private var engineBar: some View {
let engine: SynthesisEngine = model.session.engine
return HStack(spacing: toolbarSpacing) {
Circle()
.fill(engine.isRunning ? Color.green : Color.red)
.frame(width: engineDotSize, height: engineDotSize)
Text(engine.isRunning ? "engine running" : "engine stopped")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
Button {
model.toggleEngine()
engineTick &+= 1
} label: {
HStack(spacing: reevalBadgeSpacing) {
Circle()
.fill(engine.isRunning ? Color.green : Color.red)
.frame(width: engineDotSize, height: engineDotSize)
Text(engine.isRunning ? "engine running" : "▶ start engine")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(engine.isRunning ? Color.secondary : Color.primary)
}
}
.buttonStyle(.plain)
.help(engine.isRunning ? "Stop the audio engine" : "Start the audio engine")
Spacer()
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(engine.averageCPU))")
.font(.system(.caption, design: .monospaced))
@@ -122,12 +151,35 @@ public struct LyrebirdScratchView: View {
Text("synths: \(model.trackedSynthCount)")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
Spacer().frame(width: 8)
Text("snippets: \(model.loadedSnippetCount)")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(model.snippetMemoryHint == nil ? Color.secondary : Color.orange)
.help("Compiled snippet dylibs mapped this session. They can't be "
+ "unloaded without restarting (Graph DSL mode maps none).")
}
.padding(.horizontal, toolbarPadding)
.padding(.vertical, 6)
.id(engineTick)
}
/// Warning strip shown once mapped snippet dylibs cross the restart
/// threshold — the user-facing safety valve over the by-design leak.
private func snippetMemoryBanner(_ hint: String) -> some View {
HStack(spacing: reevalBadgeSpacing) {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(.orange)
Text(hint)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.primary)
.fixedSize(horizontal: false, vertical: true)
Spacer(minLength: 0)
}
.padding(.horizontal, toolbarPadding)
.padding(.vertical, 6)
.background(Color.orange.opacity(0.12))
}
private func formatCPU(_ value: Double) -> String {
String(format: "%.0f%%", value * 100)
}
@@ -180,18 +232,96 @@ public struct LyrebirdScratchView: View {
}
private var statusBar: some View {
HStack {
HStack(spacing: toolbarSpacing) {
reevalBadge
Text(model.statusMessage.isEmpty ? "Ready." : model.statusMessage)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
.lineLimit(1)
.truncationMode(.middle)
Spacer()
modePicker
}
.padding(.horizontal, statusHPad)
.padding(.vertical, statusVPad)
}
/// Segmented toggle between the Swift-compile and instant graph-DSL
/// evaluators. Routes through ``LyrebirdScratchModel/switchMode(to:)`` so the
/// seed placeholder follows the mode.
private var modePicker: some View {
Picker("Mode", selection: Binding(
get: { model.evalMode },
// Defer to the next main-actor tick: the Picker's `set` runs inside
// SwiftUI's view-update pass, and `switchMode` mutates @Published
// state ("Publishing changes from within view updates is not
// allowed"). Scheduling it off the current pass avoids that.
set: { newMode in Task { @MainActor in model.switchMode(to: newMode) } }
)) {
ForEach(ScratchEvalMode.allCases, id: \.self) { mode in
Text(mode.title).tag(mode)
}
}
.pickerStyle(.segmented)
.labelsHidden()
.fixedSize()
.help("Swift compiles a snippet dylib; Graph DSL interprets a generator graph instantly, no compile.")
}
/// Re-evaluation readiness indicator: a colored dot + short label bound to
/// ``LyrebirdScratchModel/reevalState``. Tells the user at a glance whether
/// an eval is available (dirty), in flight (compiling), matches what is
/// playing (clean), or failed.
private var reevalBadge: some View {
HStack(spacing: reevalBadgeSpacing) {
Circle()
.fill(reevalColor)
.frame(width: engineDotSize, height: engineDotSize)
Text(reevalLabel)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
}
.help(reevalHelp)
}
private var reevalColor: Color {
switch model.reevalState {
case .empty: return .secondary
case .clean: return .green
case .dirty: return .yellow
case .compiling: return .blue
case .queued: return .purple
case .failed: return .red
}
}
private var reevalLabel: String {
switch model.reevalState {
case .empty: return "empty"
case .clean: return "clean"
case .dirty: return "dirty"
case .compiling: return "compiling"
case .queued: return "queued"
case .failed: return "failed"
}
}
private var reevalHelp: String {
switch model.reevalState {
case .empty: return "Nothing to evaluate."
case .clean: return "Buffer matches what is playing. ⌘↩ re-runs it."
case .dirty: return "Edited since the last run — ⌘↩ to re-evaluate."
case .compiling: return "Compiling…"
case .queued(let beat):
return String(format: "Compiled — swap lands on beat %.0f.", beat)
case .failed(let count):
let plural: String = count == 1 ? "" : "s"
return count == 0
? "Last run failed to compile."
: "Last run failed — \(count) diagnostic\(plural)."
}
}
private var diagnosticsList: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
@@ -219,6 +349,7 @@ public struct LyrebirdScratchView: View {
private let diagnosticsMinHeight: CGFloat = 80
private let diagnosticsMaxHeight: CGFloat = 200
private let engineDotSize: CGFloat = 8
private let reevalBadgeSpacing: CGFloat = 4
}
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
@@ -250,7 +381,12 @@ private struct DiagnosticRow: View {
if let line: Int = diagnostic.line {
return "\(line):\(diagnostic.column)"
}
return "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
// No user-body line. A swiftc preamble hit carries a real (1-based)
// rawLine; a graph-DSL file-scope error carries rawLine 0 (there is no
// harness/preamble at all), so label the two cases distinctly.
return diagnostic.rawLine >= 1
? "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
: "(file)"
}
private func color(for severity: DiagnosticSeverity) -> Color {
@@ -266,7 +402,37 @@ private struct DiagnosticRow: View {
private let severityColumnWidth: CGFloat = 56
}
/// `NSViewRepresentable` wrapping a vanilla `NSTextView` inside an
/// `NSTextView` subclass that fixes member-completion behavior.
///
/// The default `rangeForUserCompletion` scans back over the whole dotted
/// expression, so completing a member right after a `.` (e.g. `context.` →
/// `engine`) would *replace* the receiver (`context`) with the chosen member
/// instead of inserting after the dot. When the character before the insertion
/// point is a `.`, this override returns an empty range at the caret, so the
/// completion is a pure insertion and `context.engine` is produced.
/// UTF-16 code unit for `.` (the member-access operator that triggers and
/// shapes completion).
private let dotCharacterCode: unichar = 46
/// Whether `selection` is a bare insertion point sitting immediately after a
/// `.` in `text` — the member-completion trigger condition.
private func caretFollowsDot(in text: NSString, selection: NSRange) -> Bool {
guard selection.length == 0, selection.location > 0, selection.location <= text.length
else { return false }
return text.character(at: selection.location - 1) == dotCharacterCode
}
final class ScratchTextView: NSTextView {
override var rangeForUserCompletion: NSRange {
let sel: NSRange = selectedRange()
if caretFollowsDot(in: string as NSString, selection: sel) {
return NSRange(location: sel.location, length: 0)
}
return super.rangeForUserCompletion
}
}
/// `NSViewRepresentable` wrapping a ``ScratchTextView`` inside an
/// `NSScrollView`. Monospaced 13 pt, plain text, no smart-quote / dash /
/// auto-correct interference — matches the editor expectations of someone
/// typing Swift code.
@@ -275,24 +441,90 @@ private struct ScratchEditor: NSViewRepresentable {
@Binding var text: String
let fontSize: CGFloat
let wrapsLines: Bool
/// Async source of code-completion candidates for a zero-based user-space
/// (line, UTF-16 character). Supplied by the view from the model.
let requestCompletions: @MainActor (_ line: Int, _ character: Int) async -> [LSPCompletionItem]
@MainActor
final class Coordinator: NSObject, NSTextViewDelegate {
var parent: ScratchEditor
/// Candidate insert-texts from the most recent completion fetch; served
/// synchronously to the text view's completion window via the delegate.
private var _completionStrings: [String] = []
/// Monotonic id of the latest completion request; a resolving fetch only
/// applies its results if it is still the newest (so a slow older request
/// can't clobber a fresher one that landed first).
private var _completionGeneration: Int = 0
init(_ parent: ScratchEditor) { self.parent = parent }
func textDidChange(_ notification: Notification) {
guard let tv: NSTextView = notification.object as? NSTextView else { return }
parent.text = tv.string
parent.applyHighlight(to: tv)
// Auto-trigger member completion right after a `.` is typed.
if caretFollowsDot(in: tv.string as NSString, selection: tv.selectedRange()) {
triggerCompletion(tv)
}
}
/// The text view calls this synchronously from `complete(_:)`; return the
/// candidates fetched asynchronously just before. Replaces the default
/// dictionary-word completions entirely.
func textView(_ textView: NSTextView,
completions words: [String],
forPartialWordRange charRange: NSRange,
indexOfSelectedItem index: UnsafeMutablePointer<Int>?) -> [String] {
_completionStrings
}
/// Fetch completions for the current caret position, then show the text
/// view's completion window. No-op when the selection is non-empty (a
/// range is selected, not an insertion point) or the fetch is empty.
func triggerCompletion(_ tv: NSTextView) {
let sel: NSRange = tv.selectedRange()
guard sel.length == 0 else { return }
let (line, character): (Int, Int) = editorLineAndUTF16Char(
in: tv.string, utf16Offset: sel.location)
let request: @MainActor (Int, Int) async -> [LSPCompletionItem] = parent.requestCompletions
_completionGeneration += 1
let generation: Int = _completionGeneration
Task { @MainActor [weak self, weak tv] in
let items: [LSPCompletionItem] = await request(line, character)
guard let self: Coordinator = self, let tv: NSTextView = tv,
!items.isEmpty else { return }
// Ignore a superseded request (a newer trigger fired meanwhile)
// and one whose caret has since moved.
guard generation == self._completionGeneration,
tv.selectedRange() == sel else { return }
self._completionStrings = items.map { $0.insertText }
tv.complete(nil)
}
}
}
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSScrollView {
let scroll: NSScrollView = NSTextView.scrollableTextView()
if let tv: NSTextView = scroll.documentView as? NSTextView {
configure(tv, in: scroll, with: context.coordinator)
}
// Build the scroll view around a `ScratchTextView` subclass so its
// `rangeForUserCompletion` override can keep member completion from
// eating the receiver expression (see the class doc).
let scroll: NSScrollView = NSScrollView()
scroll.borderType = .noBorder
scroll.hasVerticalScroller = true
scroll.autoresizingMask = [.width, .height]
let tv: ScratchTextView = ScratchTextView(frame: .zero)
tv.autoresizingMask = [.width]
tv.isVerticallyResizable = true
tv.isHorizontallyResizable = false
tv.minSize = NSSize(width: 0, height: 0)
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude)
tv.textContainer?.widthTracksTextView = true
scroll.documentView = tv
configure(tv, in: scroll, with: context.coordinator)
return scroll
}
@@ -311,7 +543,7 @@ private struct ScratchEditor: NSViewRepresentable {
if tv.string != text {
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
} else if fontChanged {
reapplyAttrs(to: tv, font: font, paragraph: paragraphStyle)
applyHighlight(to: tv, font: font, paragraph: paragraphStyle)
}
}
@@ -340,16 +572,28 @@ private struct ScratchEditor: NSViewRepresentable {
let attributed: NSAttributedString = NSAttributedString(string: newText, attributes: attrs)
tv.textStorage?.setAttributedString(attributed)
tv.typingAttributes = attrs
applyHighlight(to: tv, font: font, paragraph: paragraph)
}
private func reapplyAttrs(to tv: NSTextView,
font: NSFont,
paragraph: NSParagraphStyle) {
// MARK: - Syntax highlighting
/// Re-tokenize the buffer and paint token colors via
/// ``ScratchSyntaxHighlighter``. Attribute-only — the string and the
/// selection are untouched.
private func applyHighlight(to tv: NSTextView,
font: NSFont,
paragraph: NSParagraphStyle) {
guard let storage: NSTextStorage = tv.textStorage else { return }
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
let range: NSRange = NSRange(location: 0, length: storage.length)
storage.setAttributes(attrs, range: range)
tv.typingAttributes = attrs
let base: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
tv.typingAttributes = base
}
/// Convenience for the delegate path, which has only the text view: rebuilds
/// the font/paragraph from the current `fontSize`.
func applyHighlight(to tv: NSTextView) {
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
applyHighlight(to: tv, font: font, paragraph: makeParagraphStyle(for: font))
}
private func applyWrap(to tv: NSTextView, in scroll: NSScrollView) {
@@ -378,7 +622,15 @@ private struct ScratchEditor: NSViewRepresentable {
tv.delegate = coordinator
let editorFont: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
tv.font = editorFont
tv.isRichText = false
// Rich text so per-token foreground colors render. User styling can't
// creep in: every edit re-runs `applyHighlight`, which normalizes the
// font/paragraph over the whole buffer before recoloring, and the smart
// substitutions below stay disabled.
tv.isRichText = true
// Rich text would otherwise allow dragged/pasted images to inject
// NSTextAttachment glyphs into the buffer; keep it plain-text-only so the
// content is always compilable Swift source.
tv.importsGraphics = false
tv.isAutomaticQuoteSubstitutionEnabled = false
tv.isAutomaticDashSubstitutionEnabled = false
tv.isAutomaticTextReplacementEnabled = false
@@ -0,0 +1,78 @@
// ReevalState.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile
//
// `ReevalState` is the structured re-evaluation readiness signal published by
// `LyrebirdScratchModel`. It answers "can I re-evaluate, and would it change
// anything?" for the editor UI — distinct from the free-text `statusMessage`.
// A snippet's buffer becomes `.dirty` when edited away from the last
// successfully-run text, flips to `.compiling` while a run is in flight, and
// settles to `.clean` (buffer matches what is playing) or `.failed` afterward.
//
// macOS only — the whole LiveCompile UI surface is macOS-only.
#if os(macOS)
/// Re-evaluation readiness of a live-coding buffer.
///
/// Published by ``LyrebirdScratchModel/reevalState`` so the editor can show a
/// status badge and enable/disable the Run controls without inspecting the
/// free-text status line.
///
/// State machine:
///
/// - ``empty`` → editing non-blank text → ``dirty``
/// - ``dirty`` → run starts → ``compiling``
/// - ``compiling`` → success → ``clean`` (or ``dirty`` if the buffer was edited
/// mid-compile; or ``queued(untilBeat:)`` if the run scheduled a quantized
/// slot swap that has not yet fired) / failure → ``failed(diagnosticCount:)``
/// - ``queued(untilBeat:)`` → the scheduled swap fires → ``clean`` (or
/// ``dirty`` if the buffer was edited while queued)
/// - ``clean`` / ``queued(untilBeat:)`` / ``failed(diagnosticCount:)`` →
/// editing → ``dirty`` (or ``empty`` if the buffer is cleared to whitespace)
public enum ReevalState: Equatable, Sendable {
/// Buffer is empty or whitespace-only. Nothing to evaluate.
case empty
/// Buffer matches the text of the last successful run — re-evaluating would
/// re-run the same source. Re-evaluation is still permitted (e.g. additive).
case clean
/// Buffer has been edited since the last successful run (or has never been
/// run) and holds non-blank content. A re-evaluation is available and would
/// change what is playing.
case dirty
/// A compile + run is in flight. Run controls should be disabled.
case compiling
/// The run compiled and its slot swap is scheduled but has not yet fired —
/// the change becomes audible on `untilBeat` (a `LyrebirdClock` beat). Only
/// reached when swaps are quantized (see `SwapQuantize`); the state settles
/// to ``clean`` once the clock passes the boundary.
case queued(untilBeat: Double)
/// The last run failed to compile. `diagnosticCount` is the number of
/// parsed diagnostics (0 when the failure produced no line-mapped
/// diagnostics, e.g. a toolchain error).
case failed(diagnosticCount: Int)
/// `true` when a re-evaluation can be triggered right now — i.e. the buffer
/// holds runnable content and no compile is already in flight. A pending
/// quantized swap (``queued``) does not block a further edit + re-run.
public var canEvaluate: Bool {
switch self {
case .empty, .compiling:
return false
case .clean, .dirty, .queued, .failed:
return true
}
}
}
#endif
@@ -0,0 +1,31 @@
// ScratchEvalMode.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile
//
// Which evaluator the scratch editor runs the buffer through.
#if os(macOS)
/// The evaluation path for a `LyrebirdScratchModel`'s buffer.
public enum ScratchEvalMode: String, CaseIterable, Sendable {
/// Full Swift snippet compiled with swiftc into a dylib and run — the whole
/// language, `SynthesizerBase` subclasses, arbitrary code. Costs a compile.
case swift
/// Interpreted graph-DSL — instant, no swiftc, but only generator-graph
/// expressions (`OscSin.Audio(freq: 440) * 0.1`, `bass = …`).
case graphDSL
/// Human-readable label for a mode toggle.
public var title: String {
switch self {
case .swift: return "Swift"
case .graphDSL: return "Graph DSL"
}
}
}
#endif
@@ -0,0 +1,199 @@
// ScratchSwiftTokenizer.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile
//
// A small, dependency-free lexer that classifies the colorable spans of Swift
// source — comments, string literals, numbers, keywords, and Capitalized type
// names — for the scratch editor's syntax highlighting. It is intentionally
// approximate (a highlighter, not a parser): good enough to read code at a
// glance, and re-run whole on every keystroke — a full grapheme walk of the
// buffer, fine for typical snippet sizes (not tuned or validated for very large
// documents). Pure (no AppKit) so it is unit-testable. Ranges are `NSRange`
// (UTF-16), matching `NSTextView`.
//
// macOS only — consumed by the macOS-only scratch editor.
#if os(macOS)
import Foundation
/// Classifies Swift source into colorable token spans for syntax highlighting.
enum ScratchSwiftTokenizer {
/// A colorable category. Uncategorized text (identifiers, punctuation,
/// whitespace) produces no token and renders in the default text color.
enum Kind: Equatable {
case keyword
case type
case string
case number
case comment
}
/// One colorable span. `range` is a UTF-16 `NSRange` into the source.
struct Token: Equatable {
let range: NSRange
let kind: Kind
}
/// Swift keywords (plus a few common contextual ones) colored as keywords.
private static let keywords: Set<String> = [
"associatedtype", "class", "deinit", "enum", "extension", "fileprivate",
"func", "import", "init", "inout", "internal", "let", "open", "operator",
"private", "precedencegroup", "protocol", "public", "rethrows", "static",
"struct", "subscript", "typealias", "var",
"break", "case", "continue", "default", "defer", "do", "else",
"fallthrough", "for", "guard", "if", "in", "repeat", "return", "switch",
"where", "while",
"as", "await", "catch", "false", "is", "nil", "self", "Self", "super",
"throw", "throws", "true", "try", "Any",
"async", "some", "any", "mutating", "nonmutating", "weak", "unowned",
"final", "lazy", "indirect", "convenience", "required", "optional",
"override", "dynamic", "willSet", "didSet", "get", "set",
"actor", "nonisolated", "isolated", "distributed", "consuming",
"borrowing", "sending", "each",
]
/// UTF-16 length of the `"""` multiline-string delimiter.
private static let tripleQuoteDelimiterLength: Int = 3
/// Classify `text` into colorable token spans, left to right.
static func tokens(in text: String) -> [Token] {
let chars: [Character] = Array(text)
let count: Int = chars.count
// Prefix table of UTF-16 offsets so `[a, b)` maps to an exact NSRange
// even with multi-unit characters (emoji in a comment, etc.).
var utf16Starts: [Int] = [Int](repeating: 0, count: count + 1)
var acc: Int = 0
for k: Int in 0..<count {
utf16Starts[k] = acc
acc += chars[k].utf16.count
}
utf16Starts[count] = acc
func makeRange(_ start: Int, _ end: Int) -> NSRange {
NSRange(location: utf16Starts[start], length: utf16Starts[end] - utf16Starts[start])
}
var tokens: [Token] = []
var i: Int = 0
while i < count {
let c: Character = chars[i]
// Line comment: // … end of line
if c == "/", i + 1 < count, chars[i + 1] == "/" {
let start: Int = i
i += 2
while i < count, chars[i] != "\n" { i += 1 }
tokens.append(Token(range: makeRange(start, i), kind: .comment))
continue
}
// Block comment: /* … */ with Swift's nesting.
if c == "/", i + 1 < count, chars[i + 1] == "*" {
let start: Int = i
i += 2
var depth: Int = 1
while i < count, depth > 0 {
if chars[i] == "/", i + 1 < count, chars[i + 1] == "*" {
depth += 1
i += 2
} else if chars[i] == "*", i + 1 < count, chars[i + 1] == "/" {
depth -= 1
i += 2
} else {
i += 1
}
}
tokens.append(Token(range: makeRange(start, i), kind: .comment))
continue
}
// String literal: triple-quoted (multiline) or single-line.
if c == "\"" {
let start: Int = i
if i + 2 < count, chars[i + 1] == "\"", chars[i + 2] == "\"" {
i += tripleQuoteDelimiterLength
while i < count {
if chars[i] == "\\" { i = min(i + 2, count); continue }
if chars[i] == "\"", i + 2 < count,
chars[i + 1] == "\"", chars[i + 2] == "\"" {
i += tripleQuoteDelimiterLength
break
}
i += 1
}
} else {
i += 1
while i < count {
if chars[i] == "\\" { i = min(i + 2, count); continue } // escape
if chars[i] == "\"" { i += 1; break }
if chars[i] == "\n" { break } // unterminated
i += 1
}
}
tokens.append(Token(range: makeRange(start, i), kind: .string))
continue
}
// Number literal (must start with a digit here).
if c.isNumber {
let start: Int = i
i += 1
while i < count {
let d: Character = chars[i]
if (d == "e" || d == "E" || d == "p" || d == "P"),
i + 1 < count, chars[i + 1] == "+" || chars[i + 1] == "-" {
i += 2 // signed exponent, e.g. 1e-10
} else if d.isHexDigit || d == "_"
|| d == "x" || d == "X" || d == "o" || d == "O"
|| d == "b" || d == "B" || d == "e" || d == "E"
|| d == "p" || d == "P" {
i += 1
} else if d == ".", i + 1 < count, chars[i + 1].isNumber {
i += 1 // decimal point (not a range/member `.`)
} else {
break
}
}
tokens.append(Token(range: makeRange(start, i), kind: .number))
continue
}
// Attribute: @escaping, @MainActor, …
if c == "@" {
let start: Int = i
i += 1
while i < count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" {
i += 1
}
tokens.append(Token(range: makeRange(start, i), kind: .keyword))
continue
}
// Identifier: keyword, Capitalized type, or plain (no token).
if c.isLetter || c == "_" {
let start: Int = i
i += 1
while i < count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" {
i += 1
}
let word: String = String(chars[start..<i])
if keywords.contains(word) {
tokens.append(Token(range: makeRange(start, i), kind: .keyword))
} else if let first: Character = word.first, first.isUppercase {
tokens.append(Token(range: makeRange(start, i), kind: .type))
}
continue
}
i += 1
}
return tokens
}
}
#endif
@@ -0,0 +1,54 @@
// ScratchSyntaxHighlighter.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile
//
// Paints ``ScratchSwiftTokenizer`` token colors onto an `NSTextStorage`. Split
// out of the SwiftUI `NSViewRepresentable` so the tokenizer→color→storage wiring
// is unit-testable against a plain `NSTextStorage` (no window / view needed).
//
// macOS only.
#if os(macOS)
import AppKit
enum ScratchSyntaxHighlighter {
/// Foreground color for a token kind. `NSColor.system*` are dynamic, so they
/// adapt to the editor's light/dark appearance automatically.
static func color(for kind: ScratchSwiftTokenizer.Kind) -> NSColor {
switch kind {
case .keyword: return .systemPink
case .type: return .systemPurple
case .string: return .systemRed
case .number: return .systemBlue
case .comment: return .systemGreen
}
}
/// Normalize `baseAttributes` (font / paragraph / label color) over the whole
/// storage — so a paste or font change can't leave stray styling — then
/// overlay per-token foreground colors. Attribute-only: the string is not
/// changed, so the caller's selection is preserved.
static func apply(to storage: NSTextStorage, baseAttributes: [NSAttributedString.Key: Any]) {
let full: NSRange = NSRange(location: 0, length: storage.length)
storage.beginEditing()
storage.setAttributes(baseAttributes, range: full)
for token: ScratchSwiftTokenizer.Token in ScratchSwiftTokenizer.tokens(in: storage.string) {
// Ranges come from the same string, but guard against any bounds
// drift before touching the storage.
let end: Int = token.range.location + token.range.length
if token.range.location >= 0, end <= storage.length {
storage.addAttribute(.foregroundColor,
value: color(for: token.kind),
range: token.range)
}
}
storage.endEditing()
}
}
#endif
@@ -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
@@ -0,0 +1,53 @@
// EditorPositionMappingTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
@testable import LyrebirdLiveCompileUI
@Suite("editorLineAndUTF16Char")
struct EditorPositionMappingTests {
@Test func offsetZeroIsOrigin() {
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "abc\ndef", utf16Offset: 0)
#expect(line == 0)
#expect(char == 0)
}
@Test func withinFirstLineCountsColumns() {
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "let x = OscSin.", utf16Offset: 15)
#expect(line == 0)
#expect(char == 15)
}
@Test func afterNewlineResetsColumn() {
// "abc\nde" — offset 5 is the 'e' on line 1, column 2.
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "abc\nde", utf16Offset: 5)
#expect(line == 1)
#expect(char == 1)
}
@Test func startOfSecondLineIsColumnZero() {
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "ab\ncd", utf16Offset: 3)
#expect(line == 1)
#expect(char == 0)
}
@Test func offsetPastEndClampsToFinalPosition() {
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "ab\ncd", utf16Offset: 999)
#expect(line == 1)
#expect(char == 2)
}
@Test func astralCharacterCountsAsTwoUTF16Units() {
// "😀x" — the emoji is a surrogate pair (2 UTF-16 units); 'x' is at char 2.
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "😀x", utf16Offset: 2)
#expect(line == 0)
#expect(char == 2)
}
}
#endif
@@ -95,7 +95,7 @@ struct LyrebirdScratchModelTests {
await model.run(additive: false)
model.clearTracked()
#expect(model.trackedSynthCount == 0)
#expect(model.statusMessage == "Cleared tracked synths.")
#expect(model.statusMessage == "Cleared all synths (tracked + slots).")
}
@Test
@@ -166,6 +166,151 @@ struct LyrebirdScratchModelTests {
#expect(model.text == original)
#expect(model.documentURL == nil)
}
// MARK: - Re-eval readiness signal
@Test
func blankInitialTextIsEmptyState() {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: " \n\t")
#expect(model.reevalState == .empty)
#expect(model.reevalState.canEvaluate == false)
}
@Test
func nonBlankInitialTextIsDirtyState() {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "// hi")
#expect(model.reevalState == .dirty)
#expect(model.reevalState.canEvaluate == true)
}
@Test
func editingBlankToContentGoesDirty() {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "")
#expect(model.reevalState == .empty)
model.text = "context.reportMessage(\"x\")"
#expect(model.reevalState == .dirty)
}
// A successful run drives the buffer `.dirty` → `.compiling` → `.clean`.
// (`LiveSession.discoverSPMModuleMaps` makes the snippet compile under a
// bare `swift test`, so a valid snippet reliably succeeds here.)
@Test
func runSettlesToCleanOnSuccess() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "context.reportMessage(\"x\")"
)
#expect(model.reevalState == .dirty)
let ok: Bool = await model.run(additive: false)
#expect(ok)
#expect(model.reevalState == .clean)
}
@Test
func editingAfterCleanReturnsToDirty() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "context.reportMessage(\"x\")"
)
let ok: Bool = await model.run(additive: false)
#expect(ok)
#expect(model.reevalState == .clean)
model.text = "context.reportMessage(\"y\")"
#expect(model.reevalState == .dirty)
}
@Test
func failedRunEntersFailedWithDiagnosticCount() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "let x: Int = \"nope\"\n"
)
await model.run(additive: false)
#expect(model.reevalState == .failed(diagnosticCount: model.diagnostics.count))
#expect(model.diagnostics.isEmpty == false)
}
@Test
func clearTrackedDropsBaselineToDirty() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "context.reportMessage(\"x\")"
)
let ok: Bool = await model.run(additive: false)
#expect(ok)
#expect(model.reevalState == .clean)
model.clearTracked()
// Nothing the buffer produced is still playing → a re-run is meaningful.
#expect(model.reevalState == .dirty)
}
@Test
func quantizedRunEntersQueuedThenSettles() async throws {
let session: LiveSession = makeSession()
session.swapClock = LyrebirdClock(engine: session.engine, bpm: 120)
session.swapQuantize = .nextBeat
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "context.play(slot: \"bass\") { OscSin.Audio(freq: 110, mul: 0.1) }"
)
let ok: Bool = await model.run(additive: false)
#expect(ok)
// Compiled + scheduled: queued until beat 1 (offline clock sits at 0).
if case .queued(let beat) = model.reevalState {
#expect(beat == 1.0)
} else {
Issue.record("expected .queued, got \(model.reevalState)")
}
// Still pending → refresh is a no-op.
model.refreshQueuedState()
if case .queued = model.reevalState {} else {
Issue.record("expected still .queued")
}
// Once the swap is no longer pending (here: clock dropped), it settles
// to .clean since the buffer is unchanged.
session.swapClock = nil
model.refreshQueuedState()
#expect(model.reevalState == .clean)
}
@Test
func clearTrackedFullResetAlsoClearsSlots() throws {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "// x")
let slotted: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
try session.engine.add(slotted)
session.assignSlot("bass", synth: slotted)
#expect(session.slotCount == 1)
// The model's "Clear Synths" is a full reset — tracked + slots.
model.clearTracked()
#expect(session.slotCount == 0)
}
@Test
func loadEntersDirtyEvenIfContentMatchesPriorRun() async throws {
let session: LiveSession = makeSession()
let source: String = "context.reportMessage(\"x\")"
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: source)
let ok: Bool = await model.run(additive: false)
#expect(ok)
#expect(model.reevalState == .clean)
// Load the *same* source from disk: the run baseline is dropped, so it
// reads as dirty rather than clean.
let url: URL = FileManager.default
.temporaryDirectory
.appendingPathComponent("scratch_\(UUID().uuidString).swift")
defer { try? FileManager.default.removeItem(at: url) }
try source.write(to: url, atomically: true, encoding: .utf8)
try model.load(from: url)
#expect(model.reevalState == .dirty)
}
}
#endif
@@ -0,0 +1,36 @@
// ReevalStateTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
@testable import LyrebirdLiveCompileUI
@Suite("ReevalState")
struct ReevalStateTests {
@Test
func canEvaluateFalseWhenEmptyOrCompiling() {
#expect(ReevalState.empty.canEvaluate == false)
#expect(ReevalState.compiling.canEvaluate == false)
}
@Test
func canEvaluateTrueWhenRunnable() {
#expect(ReevalState.dirty.canEvaluate == true)
#expect(ReevalState.clean.canEvaluate == true)
#expect(ReevalState.queued(untilBeat: 4.0).canEvaluate == true)
#expect(ReevalState.failed(diagnosticCount: 0).canEvaluate == true)
#expect(ReevalState.failed(diagnosticCount: 3).canEvaluate == true)
}
@Test
func failedCarriesDiagnosticCount() {
#expect(ReevalState.failed(diagnosticCount: 2) == .failed(diagnosticCount: 2))
#expect(ReevalState.failed(diagnosticCount: 2) != .failed(diagnosticCount: 5))
}
}
#endif
@@ -0,0 +1,51 @@
// ScratchModelCompletionTests.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
/// Integration: `LyrebirdScratchModel.completionItems` end-to-end through the
/// real `sourcekit-lsp`. Serialized (each launches a server).
@Suite("LyrebirdScratchModel completion", .serialized)
@MainActor
struct ScratchModelCompletionTests {
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), initialText: text)
}
@Test func swiftModeCompletesGeneratorMembers() async {
let model: LyrebirdScratchModel = makeModel(text: "let x = OscSin.")
let items: [LSPCompletionItem] = await model.completionItems(line: 0, character: 15)
let labels: Set<String> = Set(items.map { $0.label })
#expect(labels.contains("Audio"))
#expect(labels.contains("Control"))
}
@Test func graphDSLModeReturnsNoCompletions() async {
let model: LyrebirdScratchModel = makeModel(text: "OscSin.")
model.switchMode(to: .graphDSL)
// DSL mode needs no swiftc/LSP; completion is a no-op (and no server spawns).
let items: [LSPCompletionItem] = await model.completionItems(line: 0, character: 7)
#expect(items.isEmpty)
}
}
#endif
@@ -0,0 +1,47 @@
// ScratchModelEngineTests.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 engine toggle")
@MainActor
struct ScratchModelEngineTests {
private func makeModel() -> 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))
}
@Test func toggleStartsThenStopsEngine() throws {
let model: LyrebirdScratchModel = makeModel()
let engine: SynthesisEngine = model.session.engine
#expect(engine.isRunning == false)
model.toggleEngine()
#expect(engine.isRunning)
#expect(model.statusMessage == "Engine started.")
model.toggleEngine()
#expect(engine.isRunning == false)
#expect(model.statusMessage == "Engine stopped.")
}
}
#endif
@@ -0,0 +1,153 @@
// ScratchModelGraphDSLTests.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 graph-DSL mode")
@MainActor
struct ScratchModelGraphDSLTests {
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 defaultsToSwiftMode() {
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: makeSession())
#expect(model.evalMode == .swift)
}
@Test
func graphDSLPlaceholderIsGraphOnly() {
let placeholder: String = LyrebirdScratchModel.graphDSLPlaceholder
#expect(placeholder.contains("OscSin.Audio"))
// No `context` API in the DSL surface.
#expect(!placeholder.contains("context"))
}
@Test
func switchModeSwapsUntouchedPlaceholder() {
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: makeSession())
// Buffer still holds the untouched Swift placeholder.
model.switchMode(to: .graphDSL)
#expect(model.evalMode == .graphDSL)
#expect(model.text == LyrebirdScratchModel.graphDSLPlaceholder)
}
@Test
func switchModePreservesEditedBuffer() {
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: makeSession(),
initialText: "OscSin(freq: 440) * 0.1"
)
model.switchMode(to: .graphDSL)
#expect(model.evalMode == .graphDSL)
#expect(model.text == "OscSin(freq: 440) * 0.1")
}
@Test
func switchModeToSameModeIsNoOp() {
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: makeSession())
let before: String = model.text
model.switchMode(to: .swift)
#expect(model.text == before)
}
@Test
func switchModeClearsStaleDiagnostics() async {
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: makeSession(),
initialText: "NotAGenerator(freq: 1)"
)
model.switchMode(to: .graphDSL)
_ = await model.run(additive: false)
#expect(!model.diagnostics.isEmpty)
// Switching modes must not leave the old run's gutter markers behind.
model.switchMode(to: .swift)
#expect(model.diagnostics.isEmpty)
}
@Test
func switchModeDropsRunBaselineSoBufferReadsDirty() async {
// A buffer that matches the last Swift run must NOT read as `.clean`
// after switching to the DSL evaluator, which never ran it.
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: makeSession(),
initialText: "OscSin(freq: 440) * 0.1"
)
model.switchMode(to: .graphDSL)
_ = await model.run(additive: false)
#expect(model.reevalState == .clean)
// Back to Swift with the same text: the Swift evaluator hasn't run it.
model.switchMode(to: .swift)
#expect(model.reevalState == .dirty)
}
@Test
func runValidGraphDSLReachesCleanAndTracks() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "OscSin(freq: 440) * 0.1"
)
model.switchMode(to: .graphDSL)
let ok: Bool = await model.run(additive: false)
#expect(ok)
#expect(model.reevalState == .clean)
#expect(model.trackedSynthCount == 1)
#expect(model.diagnostics.isEmpty)
}
@Test
func runBrokenGraphDSLFailsWithDiagnostics() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "NotAGenerator(freq: 1)"
)
model.switchMode(to: .graphDSL)
let ok: Bool = await model.run(additive: false)
#expect(!ok)
#expect(!model.diagnostics.isEmpty)
if case .failed = model.reevalState {} else {
Issue.record("expected .failed, got \(model.reevalState)")
}
}
@Test
func brokenReRunKeepsPriorGraphPlaying() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "OscSin(freq: 440) * 0.1"
)
model.switchMode(to: .graphDSL)
_ = await model.run(additive: false)
#expect(model.trackedSynthCount == 1)
model.text = "Nope(freq: 1)"
let ok: Bool = await model.run(additive: false)
#expect(!ok)
// The prior graph is untouched — a bad edit never drops audio.
#expect(model.trackedSynthCount == 1)
}
}
#endif
@@ -0,0 +1,68 @@
// ScratchModelMemoryTests.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 snippet memory")
@MainActor
struct ScratchModelMemoryTests {
private func makeModel() -> 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))
}
@Test func freshModelMirrorsZeroMappedSnippets() {
let model: LyrebirdScratchModel = makeModel()
#expect(model.loadedSnippetCount == 0)
#expect(model.snippetMemoryHint == nil)
}
@Test func hintIsNilBelowThreshold() {
let below: Int = LyrebirdScratchModel.snippetRestartThreshold - 1
#expect(LyrebirdScratchModel.snippetMemoryHint(count: 0) == nil)
#expect(LyrebirdScratchModel.snippetMemoryHint(count: below) == nil)
}
@Test func hintAppearsAtAndAboveThreshold() {
let at: Int = LyrebirdScratchModel.snippetRestartThreshold
let atHint: String? = LyrebirdScratchModel.snippetMemoryHint(count: at)
#expect(atHint != nil)
#expect(atHint?.contains("\(at)") == true)
#expect(LyrebirdScratchModel.snippetMemoryHint(count: at + 100) != nil)
}
@Test func clearTrackedRefreshesSnippetMirror() {
// resetAll (behind clearTracked) does not reclaim dylibs, so the mirror
// stays in sync with the session — 0 on a fresh session.
let model: LyrebirdScratchModel = makeModel()
model.clearTracked()
#expect(model.loadedSnippetCount == 0)
}
@Test func hintMentionsRestartAndDSLAlternative() {
let hint: String = LyrebirdScratchModel.snippetMemoryHint(
count: LyrebirdScratchModel.snippetRestartThreshold) ?? ""
#expect(hint.lowercased().contains("restart"))
#expect(hint.contains("Graph DSL"))
}
}
#endif
@@ -0,0 +1,101 @@
// ScratchSwiftTokenizerTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import Foundation
@testable import LyrebirdLiveCompileUI
@Suite("ScratchSwiftTokenizer")
struct ScratchSwiftTokenizerTests {
/// The token kind covering the first occurrence of `substring`, or `nil` if
/// no token exactly covers it. Verifies the range maps back to `substring`.
private func kind(of substring: String, in source: String) -> ScratchSwiftTokenizer.Kind? {
let ns: NSString = source as NSString
let target: NSRange = ns.range(of: substring)
for token: ScratchSwiftTokenizer.Token in ScratchSwiftTokenizer.tokens(in: source) {
if NSEqualRanges(token.range, target) { return token.kind }
}
return nil
}
@Test func keywordsAndTypesAndPlainIdentifiers() {
let src: String = "let osc = OscSin.Audio(freq: 440)"
#expect(kind(of: "let", in: src) == .keyword)
#expect(kind(of: "OscSin", in: src) == .type)
// Lowercase identifiers produce no token.
#expect(kind(of: "osc", in: src) == nil)
#expect(kind(of: "freq", in: src) == nil)
}
@Test func numbers() {
#expect(kind(of: "440", in: "freq: 440") == .number)
#expect(kind(of: "0.15", in: "mul: 0.15") == .number)
#expect(kind(of: "0xFF", in: "let x = 0xFF") == .number)
}
@Test func numberDoesNotEatRangeOperator() {
// `1...5` must not be swallowed into one number token — the `.` is only
// consumed when followed by a digit.
let src: String = "for i in 1...5 {}"
#expect(kind(of: "1", in: src) == .number)
#expect(kind(of: "5", in: src) == .number)
}
@Test func strings() {
#expect(kind(of: "\"hello\"", in: "reportMessage(\"hello\")") == .string)
// Escaped quote stays inside the string.
let esc: String = "let s = \"a\\\"b\""
#expect(kind(of: "\"a\\\"b\"", in: esc) == .string)
}
@Test func lineAndBlockComments() {
#expect(kind(of: "// hello", in: "let x = 1 // hello") == .comment)
// Nested block comment closes at the outer `*/`.
let nested: String = "/* a /* b */ c */"
#expect(kind(of: nested, in: nested) == .comment)
}
@Test func attributesColorAsKeyword() {
#expect(kind(of: "@MainActor", in: "@MainActor func f() {}") == .keyword)
}
@Test func utf16RangesSurviveMultiUnitCharacters() {
// An emoji (2 UTF-16 units) before a keyword: the keyword's NSRange must
// still line up with the NSString substring.
let src: String = "// 🎹\nlet x = 1"
#expect(kind(of: "let", in: src) == .keyword)
#expect(kind(of: "1", in: src) == .number)
}
@Test func emptyStringProducesNoTokens() {
#expect(ScratchSwiftTokenizer.tokens(in: "").isEmpty)
}
// Regression: a lone trailing backslash inside an unterminated string used to
// overrun the UTF-16 offset table and trap. Tokenizing must not crash, for
// both single-line and triple-quoted strings.
@Test func trailingBackslashAtEndOfBufferDoesNotCrash() {
_ = ScratchSwiftTokenizer.tokens(in: "\"\\") // opening " then \
_ = ScratchSwiftTokenizer.tokens(in: "\"\"\"\\") // triple-open then \
_ = ScratchSwiftTokenizer.tokens(in: "let s = \"abc\\") // realistic edit
// A backslash as the very last character overall.
_ = ScratchSwiftTokenizer.tokens(in: "\\")
}
@Test func signedExponentIsOneNumberToken() {
#expect(kind(of: "1e-10", in: "let x = 1e-10") == .number)
#expect(kind(of: "2.5E+3", in: "let y = 2.5E+3") == .number)
}
@Test func concurrencyKeywords() {
#expect(kind(of: "actor", in: "actor A {}") == .keyword)
#expect(kind(of: "nonisolated", in: "nonisolated func f() {}") == .keyword)
}
}
#endif
@@ -0,0 +1,54 @@
// ScratchSyntaxHighlighterTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import AppKit
@testable import LyrebirdLiveCompileUI
@Suite("ScratchSyntaxHighlighter")
@MainActor
struct ScratchSyntaxHighlighterTests {
private func color(_ storage: NSTextStorage, at index: Int) -> NSColor? {
storage.attribute(.foregroundColor, at: index, effectiveRange: nil) as? NSColor
}
@Test func paintsTokenColorsOntoStorage() {
let source: String = "let x = 1 // note"
let storage: NSTextStorage = NSTextStorage(string: source)
let base: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor.labelColor]
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
let ns: NSString = source as NSString
// Keyword, number, comment each get their kind's color.
#expect(color(storage, at: ns.range(of: "let").location)
== ScratchSyntaxHighlighter.color(for: .keyword))
#expect(color(storage, at: ns.range(of: "1").location)
== ScratchSyntaxHighlighter.color(for: .number))
#expect(color(storage, at: ns.range(of: "// note").location)
== ScratchSyntaxHighlighter.color(for: .comment))
// A plain identifier keeps the base color.
#expect(color(storage, at: ns.range(of: "x").location) == NSColor.labelColor)
}
@Test func reapplyNormalizesAwayStaleColors() {
// Edit the source so a previously-colored keyword becomes a plain
// identifier; re-applying must reset it to the base color, not leave the
// old keyword color behind.
let storage: NSTextStorage = NSTextStorage(string: "let value = 1")
let base: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor.labelColor]
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
// "let" -> "lot" (no longer a keyword).
let ns0: NSString = "let value = 1" as NSString
storage.replaceCharacters(in: ns0.range(of: "let"), with: "lot")
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
let ns1: NSString = storage.string as NSString
#expect(color(storage, at: ns1.range(of: "lot").location) == NSColor.labelColor)
}
}
#endif
@@ -0,0 +1,51 @@
// ScratchTextViewTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import AppKit
@testable import LyrebirdLiveCompileUI
@Suite("ScratchTextView.rangeForUserCompletion")
@MainActor
struct ScratchTextViewTests {
private func makeTextView(_ text: String, caret: Int) -> ScratchTextView {
let tv: ScratchTextView = ScratchTextView(frame: .zero)
tv.string = text
tv.setSelectedRange(NSRange(location: caret, length: 0))
return tv
}
/// Right after a `.`, the completion range is EMPTY at the caret — so a
/// member completion inserts after the dot instead of replacing the
/// receiver expression (the `context.` → erases `context` bug).
@Test func afterDotRangeIsEmptyAtCaret() {
let tv: ScratchTextView = makeTextView("context.", caret: 8)
let range: NSRange = tv.rangeForUserCompletion
#expect(range == NSRange(location: 8, length: 0))
}
/// A dotted member expression: completing after the second dot must not
/// reach back over `context.engine`.
@Test func afterNestedDotRangeIsEmptyAtCaret() {
let text: String = "context.engine."
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
let range: NSRange = tv.rangeForUserCompletion
#expect(range == NSRange(location: text.utf16.count, length: 0))
}
/// Mid-identifier (no preceding dot) falls through to the default behavior,
/// which covers the whole partial word so it gets replaced on completion.
@Test func partialIdentifierUsesDefaultWordRange() {
let tv: ScratchTextView = makeTextView("OscSi", caret: 5)
let range: NSRange = tv.rangeForUserCompletion
// Default range spans the partial word `OscSi` (length 5 from offset 0).
#expect(range == NSRange(location: 0, length: 5))
}
}
#endif
+23
View File
@@ -22,6 +22,7 @@ let package = Package(
// never reference this product — they use `Lyrebird` (static) above.
.library(name: "LyrebirdDynamic", type: .dynamic, targets: ["LyrebirdSynth"]),
.library(name: "LyrebirdUI", targets: ["LyrebirdUI"]),
.library(name: "LyrebirdGraphDSL", targets: ["LyrebirdGraphDSL"]),
.executable(name: "LyrebirdCLI", targets: ["LyrebirdCLI"]),
],
dependencies: [
@@ -110,6 +111,16 @@ let package = Package(
path: "Sources/LyrebirdBenchmark",
swiftSettings: [.unsafeFlags(["-O"])]
),
// Interpreted graph-DSL. Pure Swift over core `LyrebirdSynth` types —
// no swiftc, no AppKit — so it is cross-platform (iOS included). The
// `DSLBuiltin` registry it consumes is emitted by the separate
// `DSLRegistryGen` code-gen tool (the only thing that depends on
// swift-syntax); this shipped target does not.
.target(
name: "LyrebirdGraphDSL",
dependencies: ["LyrebirdSynth"],
path: "Sources/LyrebirdGraphDSL"
),
.testTarget(
name: "LyrebirdTests",
dependencies: ["LyrebirdSynth"],
@@ -127,6 +138,18 @@ let package = Package(
],
path: "Tests/LyrebirdUITests"
),
.testTarget(
name: "LyrebirdGraphDSLTests",
dependencies: [
"LyrebirdGraphDSL",
"LyrebirdSynth",
],
path: "Tests/LyrebirdGraphDSLTests",
linkerSettings: [
.linkedFramework("AudioToolbox"),
.linkedFramework("Accelerate"),
]
),
.testTarget(
name: "LyrebirdCLITests",
dependencies: ["LyrebirdCLI"],
+3
View File
@@ -122,6 +122,8 @@ The REPL is text-only and works from any project that depends on Lyrebird; the s
**Read [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md)** — it covers the eight demo projects, how to open the workspace, where to add synthesizers, and the gotchas that will bite you.
**New to Swift itself?** [`docs/learning-swift/`](docs/learning-swift/README.md) is a four-part intro to Swift written for Lyrebird users (not iOS developers): a Hello-World tone, Swift basics and best practices, the type system and functional style applied to synthesis graphs, and Xcode / packages / Debug-vs-Release / debugging.
---
## Requirements
@@ -337,6 +339,7 @@ swift package --disable-sandbox preview-documentation --target Lyrebird
| Topic | Doc |
|---|---|
| **Start here / demo projects** | [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) |
| **New to Swift? Intro for Lyrebird users** | [`docs/learning-swift/README.md`](docs/learning-swift/README.md) |
| **What's new / release notes** | [`RELEASES.md`](RELEASES.md) |
| Engine setup and Core Audio | `docs/engine/synthesis-engine.md` |
| Bus memory / In / Out | `docs/engine/bus-system.md` |
+137
View File
@@ -7,6 +7,143 @@ functionality in a backward-compatible way.
---
## 1.4.1 — "Learning Swift for Lyrebird" intro guide
A documentation-only release, continuing the doc improvements begun in 1.3. No
source or public-API changes. Adds a four-part introduction to Swift written
specifically for Lyrebird users coming from SuperCollider, Max/MSP, Csound, and
similar tools — people who want just enough Swift to be productive without
wading through iOS-development tutorials.
### New — `docs/learning-swift/`
Four short guides, meant to be read in order, each grounded in audio examples
rather than app-building:
1. **Hello, World** — from a one-line `print` to a working 440 Hz tone, every
line of a Lyrebird program explained (engine → synthesizer → generator graph
→ output bus).
2. **Swift Basics & Best Practices** — `let`/`var`, the scalar types, optionals
(and why Lyrebird forbids force-unwrap `!`), control flow, functions, error
handling, and `struct` vs `class`.
3. **Types & Functional Programming** — enums, protocols, operator overloading,
closures, and `map`/`filter`/`reduce` applied to building synthesis graphs;
`expand` as `map` for multichannel generators.
4. **Xcode, Packages & Debugging** — Xcode vs. SwiftPM, adding Lyrebird as a
package, **Debug vs. Release** build configurations (and why Debug audio can
glitch), and breakpoints — including the rule to never break or `print` on
the real-time render thread, using `debugTap`/`debugTag` instead.
Throughout, examples use explicit **type annotations** on every binding — the
same practice the Lyrebird codebase enforces — for readability and faster
compilation on large, generic audio-graph expressions.
Linked from `README.md` and `LYREBIRD_START_HERE.md` for discovery.
---
## 1.4.0 — Live-coding scratch editor, interpreted Graph DSL, `ClosureSynthesizer` + `SampleLoop`
A minor release. Fully backward-compatible — no changes to existing public API.
Adds a live-coding editor and an interpreted graph language on the tooling side,
two new core building blocks (`ClosureSynthesizer`, `SampleLoop`), and one
real-time correctness fix in the disk recorder.
### New — `ClosureSynthesizer`: play a graph without a subclass
The shortest path from a generator graph to sound. Instead of declaring a
`SynthesizerBase` subclass and overriding `build()`, hand a closure that returns
the output graph:
```swift
try engine.add(ClosureSynthesizer { OscSin.Audio(freq: 440, mul: 0.1) })
try engine.add(ClosureSynthesizer(bus: 0) { Pan2(input: saw, pan: 0) })
```
The closure runs once, inside `build()`, on the main thread when the synth is
added — so each instance builds its own graph (the usual
graph-copy-per-instance rule). A multi-channel source fans out across
consecutive buses from `bus`, exactly as `output(bus:source:)` does. This is
also the primitive the scratch editor's "play a bare graph" and Graph DSL paths
build on.
### New — `SampleLoop`: inline per-sample DSP + single-sample feedback
The RT-safe escape hatch for custom sample-accurate DSP — including
**single-sample feedback loops** (one-pole filters, waveguides, comb/allpass
structures) — without declaring a whole new `Generator` type.
- **No per-block allocation.** `SampleLoop` owns its pre-allocated output buffer
(inherited `_result`) and resolves its inputs once per block via the fan-out
cache, then hands both to your closure to fill the whole block in one pass —
unlike `Closure`, which allocates a fresh `[Double]` and evaluates one sample
at a time.
- **Typed `inout` feedback state.** State is built by `makeState(numChannels)`
and passed `inout` to the body, so a filter can carry `y[n-1]` across samples
and blocks correctly.
- **Channel inference + broadcast.** Output width is inferred from the inputs
(`max` of their channel counts, or `1` with none); each input is broadcast up
to that width, so the same body scales to any channel count. Mismatched
multi-row inputs precondition-trap at construction, matching
`BinaryOpGenerator`'s policy.
### New — Live-coding scratch editor (`LyrebirdLiveCompile`, macOS)
An interactive scratch pad that compiles and plays Swift snippets against a
running engine, with hot-swap and safety scaffolding built in:
- **Bare-graph & subclass play** — `context.play { … }` for a graph,
`context.play(synth)` for a declared `Synthesizer`.
- **Named slots (Pdef-style hot-swap)** — re-running a `play(slot:)` replaces
just that voice in place; other slots keep playing. Swaps can quantize to the
next beat/bar for glitch-free, on-grid transitions.
- **Re-evaluation readiness** — a status badge (empty / dirty / compiling /
clean / queued / failed) gates the Run controls.
- **Syntax highlighting** and a line-number gutter.
- **Code completion** via the toolchain's `sourcekit-lsp`: typing `.` resolves
the real symbols the snippet would see at compile time — `LyrebirdSynth`
generators (`OscSin.` → `Audio`, `Control`), the injected `context`, and the
standard library.
- **Fast first sound** — the module cache is prewarmed at launch, so the first
⌘↩ is ~0.1 s instead of a ~2 s cold build.
- **Snippet-memory safety** — each compiled snippet maps a dylib that can't be
safely unloaded; the editor surfaces a live "snippets: N" count and nudges a
restart (or a switch to the leak-free Graph DSL mode) past a threshold.
### New — Interpreted Graph DSL (`LyrebirdGraphDSL`, cross-platform)
A small text→graph language that plays **instantly — no swiftc, no dylib, no
leak** — and is the structural answer to the snippet-dylib cost:
```
bass = OscSawtooth.Audio(freq: 55, mul: 0.15)
Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0)
```
- **304 built-in generators**, code-generated from generator init signatures, so
new generators appear automatically. Audio- and control-rate variants and
buffer resources are supported.
- **Paste-compatible** — the rate suffix is the exact Swift nested-class name
(`OscSin.Control`), so a graph expression written in the editor pastes into a
Lyrebird project unchanged.
- A mode toggle in the scratch editor runs the buffer through this path on the
same track/slot machinery as the Swift path, with errors in the same gutter.
### Fixed — `DiskOut` real-time data race
`DiskOut`'s ring buffer was a Swift `[[Float]]` shared between the real-time
render thread (writer) and its background disk-writer thread (reader). Even at
disjoint frame ranges, Swift `Array` access is not race-free — the subscript and
`withUnsafeMutableBufferPointer` touch the array's shared storage pointer and
copy-on-write / refcount bookkeeping, which the frame-counter atomics did not
fence. Under load this corrupted the heap (surfacing as retain-count aborts).
The ring is now backed by raw contiguous `UnsafeMutableBufferPointer<Float>`
storage, so the existing release/acquire frame-counter fence alone makes the
single-producer/single-consumer handoff correct. Confirmed with ThreadSanitizer;
also eliminated the long-standing parallel-`swift test` teardown crash.
---
## 1.3.0 — Graceful-release fix, quickstart template, documentation accuracy pass
A minor release. Backward-compatible: one real-time behavior fix, one new
@@ -38,6 +38,22 @@ open class GeneratorBase {
/// resize after `init`; never touch this from the RT thread except to write samples.
public var _result: [[Double]]
/// Optional human-readable label for this generator, for debugging only.
///
/// Set from `build()` (or right after construction) to identify an inner node in the
/// debugger — an LLDB conditional breakpoint can then key on the tag instead of a raw
/// pointer, e.g. break in `_computeSamples` when `self.debugTag == "mod"`. Never read
/// on the RT thread by framework code; it exists purely so a debugger and hand-written
/// debug taps can recognise a specific instance.
///
/// `nonisolated(unsafe)`: a plain optional written on the main thread before the add
/// barrier and inspected only from a debugger — never read on the RT thread. Present in
/// all build configurations (a nil `String?` costs one pointer per instance) so that
/// `.debugTag` references and DocC symbol links resolve unconditionally.
///
/// See <doc:Debugging> for the breakpoint recipes that key on this tag.
public nonisolated(unsafe) var debugTag: String?
/// Default channel count — `1`. Multi-row generators MUST override.
///
/// See `Generator.outputChannelCount` for the contract. The default returns mono so
@@ -32,8 +32,11 @@ public enum DiskOut {
/// disposes the file handle.
///
/// **Thread safety** (`@unchecked Sendable` — manually verified):
/// - RT writes to `_ringBuffer[ch][(wHead + i) & _ringMask]`.
/// BG reads from `_ringBuffer[ch][rHead & _ringMask]`.
/// - The ring is raw storage (`_ringStorage`), not a Swift `[[Float]]`, so
/// concurrent RT-write / BG-read access carries no shared array metadata to
/// race on — only the sample slots, which the frame-counter fence orders.
/// - RT writes to `_ringStorage[ch * _ringSize + ((wHead + i) & _ringMask)]`.
/// BG reads from `_ringStorage[ch * _ringSize + (rHead & _ringMask)]`.
/// The overflow guard (`used + count <= _ringSize`) ensures indices never alias.
/// - `_framesWritten` is stored by RT with `.releasing`; BG loads with `.acquiring`.
/// - `_framesRead` is stored by BG with `.releasing`; RT loads with `.acquiring`.
@@ -71,7 +74,21 @@ public enum DiskOut {
// MARK: - Ring buffer (RT writes, BG reads)
private var _ringBuffer: [[Float]] // [channel][frame % _ringSize]
/// Contiguous ring storage, channel-major: frame `pos` of channel `ch`
/// lives at `_ringStorage[ch * _ringSize + pos]`.
///
/// RAW memory, deliberately **not** a Swift `[[Float]]`. The RT writer
/// (`_computeSamples`) and the background drainer (`_drainAndWrite`) touch
/// the ring concurrently — at disjoint frame ranges, fenced by the
/// `_framesWritten` / `_framesRead` release-acquire pair. Swift `Array`
/// access is **not** race-free under concurrency even at disjoint indices:
/// the subscript (and any mutating use, e.g. `withUnsafeMutableBufferPointer`,
/// which temporarily empties the array) reads/writes the array's shared
/// storage pointer and CoW / refcount bookkeeping. That shared metadata —
/// not the sample data — was the data race ThreadSanitizer flagged. Raw
/// pointers carry no such metadata, so the frame-counter fence alone makes
/// the handoff correct. Allocated in `init`, freed in `deinit`.
private let _ringStorage: UnsafeMutableBufferPointer<Float>
private let _ringSize: Int // == bufferFrames (power of two)
private let _ringMask: Int // == _ringSize − 1
@@ -142,10 +159,9 @@ public enum DiskOut {
self._ringSize = bufferFrames
self._ringMask = bufferFrames - 1
_ringBuffer = Array(
repeating: [Float](repeating: 0, count: bufferFrames),
count: channelCount
)
let ringCapacity: Int = bufferFrames * channelCount
_ringStorage = UnsafeMutableBufferPointer<Float>.allocate(capacity: ringCapacity)
_ringStorage.initialize(repeating: 0)
_interleavedWriteBuf = [Float](repeating: 0,
count: bufferFrames * channelCount)
@@ -191,6 +207,11 @@ public enum DiskOut {
&rawRef
)
guard createStatus == noErr, let rawRef: ExtAudioFileRef else {
// These guards throw before `super.init()`, so `deinit` will not
// run — free the raw ring storage explicitly or it leaks. (The
// former `[[Float]]` ring was ARC-managed and torn down here for
// free; raw memory is not.)
_ringStorage.deallocate()
throw DiskOutError.cannotCreateFile(createStatus)
}
_fileRef = rawRef
@@ -218,6 +239,8 @@ public enum DiskOut {
guard setFmtStatus == noErr else {
ExtAudioFileDispose(rawRef)
_fileRef = nil
// Pre-`super.init()` throw — `deinit` won't run; free the ring.
_ringStorage.deallocate()
throw DiskOutError.cannotSetFormat(setFmtStatus)
}
@@ -253,6 +276,11 @@ public enum DiskOut {
// is not being accessed concurrently; direct disposal is safe.
if let ref: ExtAudioFileRef = _fileRef { ExtAudioFileDispose(ref) }
}
// Free the raw ring storage. Safe here for the same reason the file
// disposal is: the BG loop upgrades its `[weak self]` to a strong
// reference for the whole iteration, so `deinit` cannot run while
// `_drainAndWrite` is mid-read of the ring.
_ringStorage.deallocate()
}
// MARK: - Background internals
@@ -292,7 +320,7 @@ public enum DiskOut {
for f: Int in 0..<toWrite {
let pos: Int = (rHead + totalDrained + f) & _ringMask
for ch: Int in 0..<channelCount {
_interleavedWriteBuf[f * channelCount + ch] = _ringBuffer[ch][pos]
_interleavedWriteBuf[f * channelCount + ch] = _ringStorage[ch * _ringSize + pos]
}
}
_interleavedWriteBuf.withUnsafeMutableBufferPointer { ptr in
@@ -346,14 +374,17 @@ public enum DiskOut {
// Mono fast path — dominant case for streaming recorders. Single per-sample
// loop fuses ring-buffer write with `_result` pass-through, both lifted to
// raw pointers via `withUnsafe(Mutable)BufferPointer`. The input row enters
// the closure tree only when present — no RT-path heap allocation in the
// degenerate `inputChannels == 0` branch.
// raw pointers. Channel 0 of the ring is `_ringStorage`'s base (offset 0);
// the input row enters the closure tree only when present — no RT-path heap
// allocation in the degenerate `inputChannels == 0` branch.
if chCount == 1 {
_ringBuffer[0].withUnsafeMutableBufferPointer { (rb: inout UnsafeMutableBufferPointer<Float>) in
guard let rbP: UnsafeMutablePointer<Float> = rb.baseAddress else { return }
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
guard let rbP: UnsafeMutablePointer<Float> = _ringStorage.baseAddress else {
for i: Int in 0..<count { _result[0][i] = 0 }
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
if inputChannels > 0 {
inputSamples[0].withUnsafeBufferPointer { (src: UnsafeBufferPointer<Double>) in
guard let p: UnsafePointer<Double> = src.baseAddress else {
@@ -394,7 +425,6 @@ public enum DiskOut {
}
}
}
}
if canWrite {
_framesWritten.store(wHead + count, ordering: .releasing)
}
@@ -412,7 +442,7 @@ public enum DiskOut {
let pos: Int = (wHead + i) & mask
for ch: Int in 0..<chCount {
let v: Double = ch < inputChannels ? inputSamples[ch][i] : 0
_ringBuffer[ch][pos] = Float(v)
_ringStorage[ch * _ringSize + pos] = Float(v)
_result[ch][i] = v
}
}
@@ -0,0 +1,231 @@
// SampleLoop.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// MARK: - SampleLoop
/// A user-supplied per-sample DSP body with pre-allocated output and typed feedback state.
///
/// `SampleLoop` is the RT-safe escape hatch for custom sample-accurate DSP — including
/// **single-sample feedback loops** (one-pole filters, waveguides, comb/allpass structures)
/// — without declaring a whole new `Generator` type. It owns its output buffer (inherited
/// `_result`), resolves its inputs once per block via the fan-out cache, and hands both to
/// your closure to fill.
///
/// Unlike ``Closure`` — which allocates a fresh `[Double]` every block and evaluates one
/// sample at a time through a value-returning body — `SampleLoop` performs **no per-block
/// allocation** and lets you write the whole block in one pass with your own inner loop.
///
/// ## Channels
/// The output channel count is **inferred from the inputs** — `max` over each input's
/// `outputChannelCount`, or `1` when there are no inputs — and passed to the body as
/// `numChannels`. Pass an explicit `channels:` to override (a pure multi-channel source has
/// no input to infer from; an up-mix wants more channels than its input). Each input is
/// **broadcast up to `numChannels` rows** (mono spreads to every channel), so `inputs[k][ch]`
/// is always valid inside the body and the same body scales to any width. An input whose
/// channel count is neither `1` nor `numChannels` `precondition`-traps at construction —
/// matching ``BinaryOpGenerator``'s policy.
///
/// ## Feedback state
/// State is built by `makeState(numChannels)` and passed `inout` to the body. Sizing it from
/// `numChannels` keeps per-channel state (e.g. `[Double]`, one slot per channel) correct even
/// when the width is inferred. Because `build()` runs once per Synthesizer instance
/// (graph-copy-per-instance), each voice gets its own `SampleLoop` with its own `state` — no
/// shared mutable state, no retain cycle from capturing the enclosing Synthesizer.
///
/// ```swift
/// // Per-channel one-pole feedback lowpass — works for mono, stereo, or N-channel input.
/// let coefficient: Double = 0.85
/// let lowpass = SampleLoop(
/// makeState: { channelCount in [Double](repeating: 0.0, count: channelCount) },
/// inputs: [signal]
/// ) { previousOutput, inputs, channelCount, output, sampleCount, _ in
/// for sample: Int in 0..<sampleCount {
/// for channel: Int in 0..<channelCount {
/// let filtered: Double = (1 - coefficient) * inputs[0][channel][sample]
/// + coefficient * previousOutput[channel]
/// output[channel][sample] = filtered
/// previousOutput[channel] = filtered
/// }
/// }
/// }
/// ```
///
/// - Parameters:
/// - makeState: Builds the initial feedback / memory state from the resolved output channel
/// count. Size per-channel state from it; ignore the argument for scalar state.
/// - inputs: Signals read inside the body, `inputs[k]` in call order. `[]` for a pure source.
/// - channels: Output channel count; `nil` infers `max` over the inputs (or `1` if none).
/// - mul: Output multiplier applied after the body. Defaults to `1.0`.
/// - add: Output offset applied after the body. Defaults to `0.0`.
/// - body: The per-sample DSP closure. See ``Body``.
///
/// - Warning: The body runs on the **RT render thread**. It obeys the same rules as any
/// `_computeSamples`: no allocation, locks, `print`, or `String` construction. The type
/// guarantees an allocation-free frame (buffer + input resolution); the body's contents
/// are your responsibility. Do **not** capture the `SampleLoop` (or its enclosing
/// Synthesizer) inside the body — the instance stores the body, so capturing itself forms a
/// strong reference cycle; drive feedback through the `inout State` argument instead.
/// Prototype here, then promote hot paths to a concrete `AudioGenerator` when you want
/// parameters, Quick Help, reuse, and raw-pointer speed.
///
/// See <doc:Debugging> for inspecting a live `SampleLoop`'s state and output.
public final class SampleLoop<State>: GeneratorBase, AudioGenerator {
/// The per-sample DSP body.
///
/// - Parameters:
/// - state: Feedback / memory state, mutated in place across samples and blocks.
/// - inputs: `inputs[input][channel][sample]`. Every input is broadcast to `numChannels`
/// rows, so `channel` is always valid up to `numChannels`.
/// - numChannels: Output channel count for this instance (also the row count of every
/// `inputs[input]` and of `output`).
/// - output: Output buffers, `numChannels` rows. Pre-zeroed each block, so a body that
/// writes fewer than `sampleCount` samples leaves silence — never stale data — in the
/// gaps. Writes go straight into the pre-allocated result; no allocation.
/// - sampleCount: Samples to produce this segment.
/// - graph: The current synthesis graph (for `graph.engine.sampleRate`, buses, etc.).
public typealias Body = (
_ state: inout State,
_ inputs: [[[Double]]],
_ numChannels: Int,
_ output: inout [[Double]],
_ sampleCount: Int,
_ graph: SynthGraph
) -> Void
/// Typed feedback / memory state, passed `inout` to the body each block.
public var state: State
/// Fixed output channel count, set at `init`. See ``outputChannelCount``.
private let channels: Int
/// Resolved inputs, pulled once per block.
private let inputs: [any ValidGeneratorInput]
/// Whether each resolved input is a `Generator` (block-rate `calculatedSamples`) or a
/// scalar (block-constant `floatValue`). Classified once at `init` — never `is`-tested on
/// the RT thread. Scalars must not go through `calculatedSamples`, which allocates a fresh
/// block for a bare `Double` every call.
private let inputIsGenerator: [Bool]
/// Each input's channel count, captured at `init` (`1` ⇒ broadcast, else `== channels`).
private let inputChannels: [Int]
/// Privately-owned `[input][channel][sample]` scratch, each row pre-allocated to
/// `lyrebirdDefaultResultBufferSize` at `init`. Input samples are **copied** into it each
/// block — never aliased — so no reference to an upstream generator's `_result` survives
/// across blocks (which would force a copy-on-write allocation inside that generator's
/// next in-place write). Copying into these uniquely-owned rows is allocation-free.
private var _resolvedInputs: [[[Double]]]
/// The user-supplied per-sample DSP body.
private let body: Body
/// Post-body output scaling (`mul` / `add`), applied only when non-identity.
private let _mulAdd: MulAddSpec
public override var outputChannelCount: Int { channels }
/// - Parameters:
/// - makeState: Builds the initial feedback / memory state, given the resolved output
/// channel count. Size per-channel state from it (e.g. `{ n in [Double](repeating: 0, count: n) }`);
/// for a scalar state ignore the argument (`{ _ in 0.0 }`).
/// - inputs: Signals read inside the body, exposed as `inputs[k]` in call order. Pass `[]`
/// for a pure source. Scalars and generators are both accepted; each is broadcast to
/// `numChannels` rows.
/// - channels: Output channel count. `nil` (default) infers `max` over the inputs'
/// channel counts, or `1` when there are no inputs. Provide explicitly for a pure
/// multi-channel source or an up-mix.
/// - mul: Output multiplier applied after the body. Defaults to `1.0`.
/// - add: Output offset applied after the body. Defaults to `0.0`.
/// - body: The per-sample DSP closure. See ``Body``.
public init(
makeState: (_ numChannels: Int) -> State,
inputs: [any ValidGeneratorInput] = [],
channels: Int? = nil,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0,
body: @escaping Body
) {
let resolved: [any ValidGeneratorInput] = inputs.map { $0._resolvedInput() }
let genFlags: [Bool] = resolved.map { $0 is any Generator }
let perInputChannels: [Int] = resolved.map { ($0 as? any Generator)?.outputChannelCount ?? 1 }
let outChannels: Int = channels ?? (perInputChannels.max() ?? 1)
precondition(outChannels >= 1, "SampleLoop channels must be >= 1, got \(outChannels).")
for idx: Int in 0..<perInputChannels.count {
let ch: Int = perInputChannels[idx]
precondition(
ch == 1 || ch == outChannels,
"SampleLoop input \(idx) has \(ch) channels; must be mono or \(outChannels)."
)
}
self.channels = outChannels
self.inputs = resolved
self.inputIsGenerator = genFlags
self.inputChannels = perInputChannels
self._resolvedInputs = resolved.map { _ in
(0..<outChannels).map { _ in makeSampleBuffer() }
}
self.body = body
self._mulAdd = MulAddSpec(mul: mul, add: add)
self.state = makeState(outChannels)
super.init(channels: outChannels)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
// Copy inputs into privately-owned scratch, broadcasting mono inputs across channels.
// Copying (not aliasing) keeps every upstream `_result` uniquely owned across blocks,
// and routing scalars through `floatValue` avoids the per-block block allocation a bare
// `Double.calculatedSamples` would incur. Both keep the RT path allocation-free.
for k: Int in 0..<inputs.count {
if inputIsGenerator[k] {
let block: [[Double]] = inputs[k].calculatedSamples(graph: graph, count: count)
if inputChannels[k] == 1 {
copyBroadcast(block.first ?? [], into: k, count: count)
} else {
for ch: Int in 0..<channels {
let src: [Double] = ch < block.count ? block[ch] : []
copyRow(src, into: k, channel: ch, count: count)
}
}
} else {
fillScalar(inputs[k].floatValue(graph: graph), into: k, count: count)
}
}
// Pre-zero the live region of every output channel: gaps read as silence. A body that
// writes all `count` samples per channel overwrites this immediately — the cost is the
// price of the safety for partial-write bodies.
for ch: Int in 0..<channels {
for i: Int in 0..<count { _result[ch][i] = 0.0 }
}
body(&state, _resolvedInputs, channels, &_result, count, graph)
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
/// Copy `src` into scratch channel `channel` of input `k`, zero-padding past `src`.
private func copyRow(_ src: [Double], into k: Int, channel: Int, count: Int) {
let m: Int = Swift.min(count, src.count)
for i: Int in 0..<m { _resolvedInputs[k][channel][i] = src[i] }
for i: Int in m..<count { _resolvedInputs[k][channel][i] = 0.0 }
}
/// Copy one `src` row into every channel of input `k` (mono broadcast).
private func copyBroadcast(_ src: [Double], into k: Int, count: Int) {
for ch: Int in 0..<channels { copyRow(src, into: k, channel: ch, count: count) }
}
/// Fill every channel of input `k` with the block-constant scalar `value`.
private func fillScalar(_ value: Double, into k: Int, count: Int) {
for ch: Int in 0..<channels {
for i: Int in 0..<count { _resolvedInputs[k][ch][i] = value }
}
}
}
+206
View File
@@ -0,0 +1,206 @@
# Debugging Synthesizers and Generators
Inspect live RT-thread state — output samples, inner-node values, per-sample
compute — without breaking real-time safety.
## Overview
Two problems bring you here:
- **A Synthesizer subclass produces wrong or no output.** You want to see what a
specific voice — often one instance out of a polyphonic pool — is actually
emitting, and what its internal generators are doing.
- **A new Generator's `_computeSamples` is off.** You want to step the compute
loop for one instance and watch its state and output evolve.
Both run on the **RT render thread**, where the usual rules apply: no allocation,
locks, `print`, or `String` construction (see <doc:SignalFlow> and the
`SynthesisEngine` contract). A *breakpoint* is safe — it halts the thread and you
inspect at leisure. Any *code* you add to a debug hook is not exempt from the RT
rules. This article covers both: setting instance-scoped breakpoints, and reading
state safely.
The tap's **invocation** is compiled out of release builds (the call site in
`evaluate(graph:count:)` is wrapped in `#if DEBUG`), and it is gated per-instance, so
nothing you add for debugging runs in shipping audio. The `debugTap` method and the
`debugTapEnabled` flag still exist in release — an override compiles unconditionally — but
the hook is simply never called there.
## The debug tap — a per-instance breakpoint
``SynthesizerBase/evaluate(graph:count:)`` is `final`, so you cannot hook it
directly. Instead override ``SynthesizerBase/debugTap(graph:count:outputs:)`` — an
`open` no-op the engine calls once per scheduling segment, **after** every output
generator has run, but only when ``SynthesizerBase/debugTapEnabled`` is set on that
instance.
```swift
final class FMTone: SynthesizerBase {
@LiveParam var carrierFreq: Double = 440.0
override func build() {
let mod: any Generator = OscSin.Audio(freq: 220.0) * 660.0
output(bus: 0, source: OscSin.Audio(freq: $carrierFreq + mod) * 0.18)
}
override func debugTap(
graph: SynthGraph,
count: Int,
outputs: [any Generator]
) {
// Breakpoint here. The RT thread halts with self, outputs, and graph
// in scope:
// po self.carrierFreq
// po outputs.first?._cachedResult // Out's samples this block
// po outputs.first?._result[0].prefix(8) // first 8 samples
let block: Int = count
_ = block
}
}
```
Enable it per instance — flip only the voice you want to inspect:
```swift
let voice: FMTone = FMTone()
#if DEBUG
voice.debugTapEnabled = true // main thread, before add — only this voice taps
#endif
try engine.add(voice)
```
In a polyphonic pool, gate the flag so a single note breaks:
```swift
for note: Int in chord {
let v: FMTone = FMTone()
v.debugTapEnabled = (note == 60) // break only middle C
try engine.add(v)
}
```
### What is in scope when it halts
| In scope | Holds |
|---|---|
| `self` | Every `let` / `@LiveParam` on the voice. |
| `outputs` | This instance's registered output-generator tree (roots only — typically `Out` / `ReplaceOut`). Each generator's `_cachedResult` / `_result` = samples just computed for this block. |
| `graph.engine` | Sample rate, block size, bus pool — read a bus mid-render. |
| `count` | Samples in this **scheduling segment** (`≤ 512`). The engine splits an audio block at sample-accurate scheduled-event boundaries, so a block containing scheduled events fires the tap once per segment — `count` is the segment length, not necessarily the full block. |
## Inspecting inner nodes
`outputs` gives you the **roots** only. Every generator stores its inputs
`private` (`BinaryOpGenerator.lhs` / `rhs`, oscillator freq inputs, …), so you
**cannot walk the tree down** to an interior node like the `mod` above from
outside. To inspect an inner node, keep a reference to it in `build()`:
```swift
final class FMTone: SynthesizerBase {
@LiveParam var carrierFreq: Double = 440.0
#if DEBUG
// nonisolated(unsafe): written in build() on main before the add barrier,
// read on the RT thread in debugTap — same happens-before as outputGenerators.
private nonisolated(unsafe) var _dbgMod: (any Generator)?
#endif
override func build() {
let mod: any Generator = OscSin.Audio(freq: 220.0) * 660.0
output(bus: 0, source: OscSin.Audio(freq: $carrierFreq + mod) * 0.18)
#if DEBUG
_dbgMod = mod
(mod as? GeneratorBase)?.debugTag = "mod"
#endif
}
override func debugTap(
graph: SynthGraph,
count: Int,
outputs: [any Generator]
) {
#if DEBUG
let modOut: [Double]? = _dbgMod?._cachedResult.first
_ = modOut // po modOut?.prefix(8) — mod's samples this block
#endif
}
}
```
### `_cachedResult` vs `_result`, and why the read is free
The tap fires **after** the generator loop, so `mod` has already run this block —
the fan-out cache (see <doc:GeneratorProtocol>) holds its output. Reading
`_dbgMod?._cachedResult` is a post-hoc read of that cache; it does **not**
recompute. Calling `_dbgMod?.calculatedSamples(graph:count:)` again would also just
return the cache (same `_segmentSerial`), so it will not re-enter the compute loop
either. For a mono generator `_cachedResult[0]` shares backing storage with
`_result[0]` — either is fine to read.
### `debugTag` for identifying an instance
``GeneratorBase/debugTag`` (DEBUG-only) is a human-readable label you set in
`build()` so a debugger can recognise one specific instance among many that share
the same class. It is never read by framework code on the RT thread — it exists
purely for LLDB conditions and hand-written taps, as shown next.
## Stepping into a Generator's compute loop
The tap is post-hoc: it shows results, not the live per-sample computation. To step
the actual loop for one instance, breakpoint the generator's own
`_computeSamples` (see <doc:WritingGenerators>) and **scope it to your instance** —
otherwise you stop on every oscillator/multiply in the program.
Using `debugTag`:
```
(lldb) b BinaryOpGenerator._computeSamples
(lldb) breakpoint modify -c 'self.debugTag == "mod"'
```
Or, if you did not set a tag, capture identity from the tap and match on the
pointer:
```
(lldb) p _dbgMod! // hit the tap first
(lldb) breakpoint modify -c 'ObjectIdentifier(self) == ObjectIdentifier(<ref>)'
```
Continue — you now step the multiply loop for that one `mod`, sample by sample. To
step into the modulator oscillator instead, hold and tag *it* too (`let modOsc =
OscSin.Audio(...)`; `modOsc.debugTag = "modOsc"`) and breakpoint
`OscSin.Audio._computeSamples` with the same condition.
> Note: `_computeSamples` may run several times per audio block in sub-block mode
> (`ControlGenerator`) — `count` is the sub-block length, not the full block. See
> <doc:WritingGenerators> for when the sub-block loop runs.
## RT rules while debugging
- A **breakpoint** anywhere on the RT thread is fine — it stops everything and you
look. This is the primary technique.
- **Code** inside ``SynthesizerBase/debugTap(graph:count:outputs:)`` (or any RT
path) still obeys the RT rules: no allocation, locks, `print`, or `String`
construction. Reading a pre-computed buffer and comparing numbers is fine;
formatting a log line is not.
- Want **continuous** inspection without halting? Snapshot the values you care
about into a **pre-allocated** ring buffer inside the tap, and drain/format them
on the main thread. This is exactly how `NodeTreeMirror` publishes RT state to
the UI — see <doc:DiagnosticsGuide>.
## When to reach for other tools
| Symptom | Tool |
|---|---|
| Need user-visible runtime messages, or a live node-tree view | <doc:DiagnosticsGuide> (`LyrebirdMessage`, `NodeTreeMirror`) |
| Want to inspect a whole signal offline, sample by sample | <doc:NRTGuide> — render to a buffer/file and analyse the samples |
| Verifying scheduling / timing | <doc:Scheduling> |
| A new Generator is structurally wrong (not just numerically) | <doc:WritingGenerators> testing checklist |
## Topics
### Related
- <doc:SynthesizerProtocol>
- <doc:GeneratorProtocol>
- <doc:WritingGenerators>
- <doc:DiagnosticsGuide>
@@ -22,6 +22,10 @@ you need to react to RT lifecycle events from the UI, the existing
``SynthesisEngineListener`` hook is the only fan-out the engine exposes
today.
> Note: This guide covers user-visible runtime surfaces. For **developer-side**
> inspection — breakpointing a specific voice on the RT thread, reading a
> generator's live output and inner state — see <doc:Debugging>.
---
## Part 1 — `LyrebirdMessage`
@@ -179,6 +179,10 @@ addOutputGenerator(outR)
Implement `_computeSamples` in your generators, not `calculatedSamples`. The cache is managed
automatically. See <doc:WritingGenerators> for the full pattern.
> Tip: Because the cache holds a generator's last output for the current segment, you can
> read an inner node's samples post-block from a Synthesizer debug tap without recomputing.
> See <doc:Debugging>.
## Pre-Allocated Output Buffer Pattern
Every generator pre-allocates `_result` to `lyrebirdDefaultResultBufferSize` (512) samples in
@@ -215,6 +215,16 @@ let speakers = zip(speakerAzDeg.degreesToRadians(), [0.0, 0.0, 0.0, 0.0])
The `Pan2` / `PanN` / `PanXY` family takes normalised positions in `[-1, 1]`,
not radians — those generators apply their own internal `× π/2` or `× π/4` scale.
## Custom multi-channel DSP — `SampleLoop`
``SampleLoop`` — the closure escape hatch for custom per-sample DSP — is channel-aware on
both ends. Its output channel count is inferred as `max` over its inputs' `outputChannelCount`
(or set explicitly via `channels:`), each input is broadcast up to that width (mono spreads;
a channel count that is neither `1` nor the output width `precondition`-traps, matching
``BinaryOpGenerator``), and the body receives `numChannels` so one width-agnostic loop covers
mono, stereo, or N-channel signals. Per-channel feedback state is sized from `numChannels` via
its `makeState` argument. See ``SampleLoop`` for the full contract.
## See Also
- <doc:BusSystem>
@@ -6,6 +6,12 @@
A step-by-step guide to implementing correct, RT-safe generators in Lyrebird.
> Before you write a whole type: for one-off custom sample-accurate DSP — especially a
> **single-sample feedback loop** (one-pole, waveguide, comb/allpass) — reach for
> ``SampleLoop`` first. It gives you an RT-safe, allocation-free per-sample body with typed
> feedback state and channel inference, no new `Generator` declaration. Promote to a full
> generator (this guide) when you want parameters, Quick Help, reuse, and raw-pointer speed.
## 1. Protocol Choice — AudioGenerator vs ControlGenerator
| Criterion | Use `AudioGenerator` | Use `ControlGenerator` |
@@ -497,3 +503,11 @@ override func build() {
```
See <doc:MultiChannel> for the full multi-channel expansion guide.
## Debugging a New Generator
When a generator's `_computeSamples` produces the wrong numbers, you need to step
its compute loop for one instance and watch its state. Tag the instance with
``GeneratorBase/debugTag`` and set an LLDB conditional breakpoint on
`_computeSamples`, or read its post-block output from a Synthesizer's debug tap.
See <doc:Debugging> for the full workflow.
@@ -33,6 +33,7 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass
- <doc:WritingGenerators>
- <doc:MultiChannel>
- ``GeneratorEnum``
- ``SampleLoop``
### Oscillators and Noise
@@ -173,6 +174,10 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass
- <doc:RoutineTask>
- ``LyrebirdClock``
### Debugging Tools
- <doc:Debugging>
### Diagnostics
- <doc:DiagnosticsGuide>
@@ -72,6 +72,10 @@ class SineTone: SynthesizerBase {
- `evaluate(graph:count:)` is `final` — the engine drives it automatically.
- Do not override `evaluate` in subclasses; override `build` instead.
> Tip: To inspect a specific instance's output and inner state on the RT thread —
> or to set a breakpoint on one voice out of a pool — override
> ``SynthesizerBase/debugTap(graph:count:outputs:)``. See <doc:Debugging>.
## Parameters
Declare live parameters as `@LiveParam` (or `@UIParam` for SwiftUI binding) properties on
@@ -0,0 +1,58 @@
// ClosureSynthesizer.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// A `SynthesizerBase` whose signal graph is supplied by a closure instead of a
// `build()` override. The escape hatch for "just play this generator graph"
// without declaring a named `Synthesizer` subclass — the fastest path from a
// bare graph to audible sound (scratchpads, demos, tests, one-off voices).
/// A `SynthesizerBase` that builds its output graph from a closure.
///
/// Skips the usual "declare a subclass, override `build()`" ceremony when all
/// you want is to hear a generator graph:
///
/// ```swift
/// try engine.add(ClosureSynthesizer { OscSin.Audio(freq: 440, mul: 0.1) })
/// try engine.add(ClosureSynthesizer(bus: 0) { Pan2(input: saw, pan: 0) })
/// ```
///
/// The closure runs inside ``build()`` — once, on the main thread, when the
/// synthesizer is added to an engine. Each instance is its own graph, so
/// **construct the generators inside the closure** rather than handing it
/// generator instances shared with another synthesizer (the same
/// graph-copy-per-instance rule that applies to any `SynthesizerBase`).
///
/// A multi-channel source (e.g. a `Pan2`) fans out across consecutive buses
/// starting at `bus`, exactly as ``SynthesizerBase/output(bus:source:)`` does.
///
/// - Parameters:
/// - bus: The output bus the graph is written to. A multi-channel source
/// continues into the following buses. Defaults to `0`.
/// - make: Builds and returns the output graph. Called once per instance,
/// inside `build()`.
public final class ClosureSynthesizer: SynthesizerBase {
private let outputBus: any ValidBus
private let make: () -> any ValidGeneratorInput
/// - Parameters:
/// - bus: The output bus the graph is written to. A multi-channel source
/// continues into the following buses. Defaults to `0`.
/// - make: Builds and returns the output graph. Called once per instance,
/// inside `build()`. Construct the generators inside the closure.
public init(
bus: any ValidBus = 0,
_ make: @escaping () -> any ValidGeneratorInput
) {
self.outputBus = bus
self.make = make
super.init()
}
public override func build() {
output(bus: outputBus, source: make())
}
}
@@ -433,8 +433,69 @@ open class SynthesizerBase: Synthesizer {
for generator: any Generator in outputGenerators {
_ = generator.calculatedSamples(graph: localGraph, count: count)
}
#if DEBUG
if debugTapEnabled {
debugTap(graph: localGraph, count: count, outputs: outputGenerators)
}
#endif
}
// MARK: - Debug tap (RT thread)
/// Lock-free backing store for ``debugTapEnabled``.
private nonisolated let _debugTapEnabled: Atomic<Bool> = Atomic<Bool>(false)
/// Enable the per-instance debug tap.
///
/// Set from the main thread — typically right after constructing the voice, though it is
/// safe to toggle on an already-added, already-playing instance too. The RT thread reads
/// it as a single relaxed atomic load per scheduling segment. Off by default — only the
/// instances you flip pay for ``debugTap(graph:count:outputs:)``.
///
/// Backed by an `Atomic<Bool>` so the main-thread write and the RT-thread read never race:
/// a plain `Bool` toggled on an already-running voice would be an unsynchronised access.
/// The `Atomic` load also carries no data-race hazard for a flag flipped mid-render — a
/// stale read only mis-fires (or mis-skips) the no-op default hook for one segment.
///
/// - Note: The tap's *invocation* is compiled out of release builds (`#if DEBUG` around the
/// call site in ``evaluate(graph:count:)``). This property and ``debugTap(graph:count:outputs:)``
/// still exist in release so an override compiles unconditionally, but in a release build
/// the hook is never called regardless of this flag.
public nonisolated var debugTapEnabled: Bool {
get { _debugTapEnabled.load(ordering: .relaxed) }
set { _debugTapEnabled.store(newValue, ordering: .relaxed) }
}
/// Debug hook fired once per scheduling segment, after every output generator has run.
///
/// Default is a no-op. Override in a subclass to inspect the live signal graph
/// mid-render — the canonical place to set a breakpoint on a specific instance.
///
/// - Parameters:
/// - graph: The `SynthGraph` used for this segment. Reaches `graph.engine`
/// (sample rate, block size) and the bus pool.
/// - count: Samples in this segment. `≤ 512`. The engine splits an audio block into
/// separate scheduling segments at sample-accurate scheduled-event boundaries, so a
/// block that contains scheduled events fires this hook once per segment — `count` is
/// the segment length, not necessarily the full block size.
/// - outputs: This instance's registered output-generator tree. Each generator's
/// `_cachedResult` / `_result` holds the samples just computed for this block.
/// - Warning: Runs on the RT render thread. A breakpoint here is fine — it halts
/// the thread with `self`, `outputs`, and `graph` in scope. Any *code* you add
/// obeys the RT rules: no allocation, locks, `print`, or `String` construction.
/// For continuous inspection without halting, snapshot into a pre-allocated
/// ring and drain it on the main thread instead.
/// - Note: Invoked only in `#if DEBUG` builds — the call site in ``evaluate(graph:count:)``
/// is compiled out of release. An override still compiles in release; it simply never runs.
///
/// See <doc:Debugging> for the full workflow, including inspecting inner nodes
/// and stepping a generator's compute loop.
nonisolated open func debugTap(
graph: SynthGraph,
count: Int,
outputs: [any Generator]
) {}
// MARK: - Bus / Input-Output convenience helpers
/// Create an `Out` generator for the given audio bus and register it as an output.
+116
View File
@@ -0,0 +1,116 @@
// DSLArgument.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Coercion helpers used by the generated registry to turn a bound DSL argument
// (a `DSLValue`) into the concrete type a generator's Swift init expects.
//
// A `.signal` argument (number or graph) feeds an `any ValidGeneratorInput`
// parameter straight through, or coerces to `Double`/`Int`/`Float` when the init
// wants a literal (delay times, table sizes, …) — throwing when handed a graph.
// A `.buffer` argument feeds a `LyrebirdBuffer` parameter. The generated code
// supplies each parameter's Swift default (as a `.signal`) via `?? …` for
// optional parameters; a required parameter is passed `nil` and throws.
import LyrebirdSynth
/// Argument coercion for generated `DSLBuiltin.make` closures.
public enum DSLArgument {
/// A required signal-or-number parameter.
public static func input(
_ value: DSLValue?,
_ builtin: String,
_ label: String
) throws -> any ValidGeneratorInput {
switch value {
case .signal(let s):
return s
case .buffer:
throw DSLBuildError.expectedSignal(builtin: builtin, label: label)
case nil:
throw DSLBuildError.missingArgument(builtin: builtin, label: label)
}
}
/// A parameter that must be a literal number. Throws when the DSL supplied a
/// signal (a generator) or a resource, or when a required value is absent.
public static func double(
_ value: DSLValue?,
_ builtin: String,
_ label: String
) throws -> Double {
guard case .signal(let s)? = value else {
if value == nil {
throw DSLBuildError.missingArgument(builtin: builtin, label: label)
}
throw DSLBuildError.expectedNumber(builtin: builtin, label: label)
}
// DSL number literals are `Double` or `Int` — `Float` is not a
// `ValidGeneratorInput`, so it never reaches here.
if let d: Double = s as? Double { return d }
if let i: Int = s as? Int { return Double(i) }
throw DSLBuildError.expectedNumber(builtin: builtin, label: label)
}
/// `Int` variant of ``double(_:_:_:)``. Truncates a fractional literal, and
/// throws ``DSLBuildError/numberOutOfRange(builtin:label:)`` rather than
/// trapping when the value is non-finite or outside the `Int` range.
public static func int(
_ value: DSLValue?,
_ builtin: String,
_ label: String
) throws -> Int {
let d: Double = try double(value, builtin, label)
guard d.isFinite, d >= Double(Int.min), d <= Double(Int.max) else {
throw DSLBuildError.numberOutOfRange(builtin: builtin, label: label)
}
return Int(d)
}
/// `Float` variant of ``double(_:_:_:)``.
public static func float(
_ value: DSLValue?,
_ builtin: String,
_ label: String
) throws -> Float {
Float(try double(value, builtin, label))
}
/// A parameter that must be a buffer resource.
public static func buffer(
_ value: DSLValue?,
_ builtin: String,
_ label: String
) throws -> LyrebirdBuffer {
switch value {
case .buffer(let b):
return b
case .signal:
throw DSLBuildError.expectedBuffer(builtin: builtin, label: label)
case nil:
throw DSLBuildError.missingArgument(builtin: builtin, label: label)
}
}
/// An optional buffer parameter (`LyrebirdBuffer?`): `nil` when the argument
/// is omitted, otherwise the buffer. (The code-gen only emits this for
/// parameters whose Swift default is `nil`, so passing `nil` on omission
/// matches that default.)
public static func optionalBuffer(
_ value: DSLValue?,
_ builtin: String,
_ label: String
) throws -> LyrebirdBuffer? {
switch value {
case .buffer(let b):
return b
case .signal:
throw DSLBuildError.expectedBuffer(builtin: builtin, label: label)
case nil:
return nil
}
}
}
@@ -0,0 +1,91 @@
// DSLBuildError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Errors raised while binding DSL arguments and constructing a generator graph.
// Surfaced to the editor as diagnostics.
/// A failure encountered building a graph from parsed DSL source.
public enum DSLBuildError: Error, Equatable, Sendable, CustomStringConvertible {
/// No builtin is registered under this name.
case unknownBuiltin(String)
/// The name exists but not at the requested rate (`audio`/`control`).
case rateUnavailable(builtin: String, rate: String)
/// The builtin has no parameter with this label.
case unknownArgument(builtin: String, label: String)
/// More positional arguments were supplied than the builtin has parameters.
case tooManyArguments(builtin: String, max: Int)
/// The same parameter was bound twice (a positional then a label, or two
/// labels).
case duplicateArgument(builtin: String, label: String)
/// A parameter without a default was not supplied.
case missingArgument(builtin: String, label: String)
/// A parameter needs a plain number (it maps to a `Double`/`Int`/`Float` on
/// the Swift init), but the DSL supplied a signal/graph or a resource.
case expectedNumber(builtin: String, label: String)
/// A parameter needs a signal (`any ValidGeneratorInput`), but the DSL
/// supplied a resource (a buffer).
case expectedSignal(builtin: String, label: String)
/// A bare identifier names a generator — the author likely forgot its `()`.
case referenceIsGenerator(String)
/// A number was supplied for an integer parameter but is outside the
/// representable `Int` range (or otherwise non-finite).
case numberOutOfRange(builtin: String, label: String)
/// A parameter needs a buffer resource, but the DSL supplied a signal.
case expectedBuffer(builtin: String, label: String)
/// A bare identifier resolved to no registered resource.
case unknownReference(String)
/// A `+ - * /` operator was applied to a resource (only signals combine).
case operatorRequiresSignal
/// A top-level statement produced a resource, which cannot be played.
case cannotPlayResource
public var description: String {
switch self {
case .unknownBuiltin(let name):
return "unknown generator '\(name)'"
case .rateUnavailable(let builtin, let rate):
return "'\(builtin)' has no \(rate)-rate variant"
case .unknownArgument(let builtin, let label):
return "'\(builtin)' has no parameter '\(label)'"
case .tooManyArguments(let builtin, let max):
return "'\(builtin)' takes at most \(max) argument(s)"
case .duplicateArgument(let builtin, let label):
return "'\(builtin)' argument '\(label)' was given twice"
case .missingArgument(let builtin, let label):
return "'\(builtin)' requires '\(label)'"
case .expectedNumber(let builtin, let label):
return "'\(builtin)' parameter '\(label)' needs a number literal"
case .expectedSignal(let builtin, let label):
return "'\(builtin)' parameter '\(label)' needs a signal, not a buffer"
case .referenceIsGenerator(let name):
return "'\(name)' is a generator — did you mean '\(name)(…)'?"
case .numberOutOfRange(let builtin, let label):
return "'\(builtin)' parameter '\(label)' number is out of range"
case .expectedBuffer(let builtin, let label):
return "'\(builtin)' parameter '\(label)' needs a buffer, not a signal"
case .unknownReference(let name):
return "unknown resource '\(name)'"
case .operatorRequiresSignal:
return "operators apply to signals, not resources"
case .cannotPlayResource:
return "a resource cannot be played on its own"
}
}
}
+57
View File
@@ -0,0 +1,57 @@
// DSLBuiltin.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// One entry in the interpreted graph-DSL's builtin registry: a named generator
// the DSL can construct. Each builtin knows its parameter labels (for binding
// positional + named arguments and for diagnostics) and carries a closure that
// calls the real Swift generator init. The registry is produced by the
// `DSLRegistryGen` code-gen tool; this file only defines the contract the
// generated table conforms to, so the parser/builder are independent of how the
// table is populated.
import LyrebirdSynth
/// A generator the DSL can construct by name.
///
/// The graph builder binds a call's positional and named arguments to
/// ``parameters`` (positional first, then labelled), validates that every label
/// is known and every required parameter is present, and then invokes ``make``
/// with the bound arguments keyed by label. `make` calls the real Swift init,
/// applying its own defaults for any omitted optional parameter.
public struct DSLBuiltin: Sendable {
/// The name used in DSL source (`OscSin`, `Pan2`, …).
public let name: String
/// The rate this builtin evaluates at. A name may exist at both rates; the
/// registry keys by `(name, rate)`.
public let rate: DSLRate
/// Declared parameters, in positional order.
public let parameters: [DSLParameter]
/// Construct the generator from arguments already bound to parameter labels.
/// Only labels present in ``parameters`` appear; omitted optional parameters
/// are absent (the closure applies the Swift init's default). Each argument
/// is a ``DSLValue`` — a signal or a resource — from which the closure pulls
/// the concrete type its init needs via ``DSLArgument``.
///
/// `@Sendable` so the registry can be a `static let` — the generated
/// closures capture nothing.
public let make: @Sendable ([String: DSLValue]) throws -> any ValidGeneratorInput
public init(
name: String,
rate: DSLRate,
parameters: [DSLParameter],
make: @escaping @Sendable ([String: DSLValue]) throws -> any ValidGeneratorInput
) {
self.name = name
self.rate = rate
self.parameters = parameters
self.make = make
}
}
@@ -0,0 +1,45 @@
// DSLBuiltinRegistry.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Lookup surface over the generated builtin table. The table itself lives in
// `Generated/GeneratedDSLRegistry.swift`, emitted by Tools/DSLRegistryGen from
// the generator sources — this file only provides name+rate lookup over it, so
// the graph builder never depends on how the table is populated.
/// The generators the DSL can construct, by name and rate.
public enum DSLBuiltinRegistry {
/// All builtins, in generated (alphabetical, then rate) order.
public static let all: [DSLBuiltin] = generated
/// Builtin lookup keyed by name then rate. Built once.
public static let byName: [String: [DSLRate: DSLBuiltin]] = {
var table: [String: [DSLRate: DSLBuiltin]] = [:]
for builtin: DSLBuiltin in generated {
table[builtin.name, default: [:]][builtin.rate] = builtin
}
return table
}()
/// The builtin registered under `name` at `rate` (default audio).
/// - Throws: ``DSLBuildError/unknownBuiltin(_:)`` when no generator exists at
/// that name, or ``DSLBuildError/rateUnavailable(builtin:rate:)`` when the
/// name exists but not at the requested rate.
public static func lookup(_ name: String, rate: DSLRate = .audio) throws -> DSLBuiltin {
guard let rates: [DSLRate: DSLBuiltin] = byName[name] else {
throw DSLBuildError.unknownBuiltin(name)
}
guard let builtin: DSLBuiltin = rates[rate] else {
throw DSLBuildError.rateUnavailable(builtin: name, rate: rate.rawValue)
}
return builtin
}
/// The rates a generator name is available at.
public static func rates(of name: String) -> Set<DSLRate> {
Set((byName[name] ?? [:]).keys)
}
}
+55
View File
@@ -0,0 +1,55 @@
// DSLExpr.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// The DSL expression AST: number literals, generator calls, and the binary math
// operators, plus the call-argument node.
/// A DSL expression.
public indirect enum DSLExpr: Equatable, Sendable {
/// A binary math operator (`+ - * /`).
public enum BinaryOp: String, Equatable, Sendable {
case add = "+"
case subtract = "-"
case multiply = "*"
case divide = "/"
}
/// One argument to a call: an optional label and a value expression.
public struct Argument: Equatable, Sendable {
public let label: String?
public let value: DSLExpr
public let span: DSLSpan
public init(label: String?, value: DSLExpr, span: DSLSpan) {
self.label = label
self.value = value
self.span = span
}
}
/// A numeric literal.
case number(Double, DSLSpan)
/// A bare identifier referencing a host resource (a buffer).
case reference(name: String, DSLSpan)
/// A generator call: `Name(arg, …)` or `Name.Audio(…)` / `Name.Control(…)`.
/// `rate` is the explicit rate from an `.Audio`/`.Control` suffix (the exact
/// Swift nested-class names), or `nil` for the default (audio-preferred)
/// resolution.
case call(name: String, rate: DSLRate?, arguments: [Argument], DSLSpan)
/// A binary operation.
case binary(op: BinaryOp, lhs: DSLExpr, rhs: DSLExpr, DSLSpan)
/// The source span covering this expression.
public var span: DSLSpan {
switch self {
case .number(_, let s): return s
case .reference(_, let s): return s
case .call(_, _, _, let s): return s
case .binary(_, _, _, let s): return s
}
}
}
@@ -0,0 +1,138 @@
// DSLGraphBuilder.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Turns a parsed `DSLExpr` into a `Generator` graph by resolving each call
// against the builtin registry and binding its arguments. Numbers become
// scalars, `+ - * /` become the corresponding generator operators, and a call
// invokes the generated `make` closure. Construction happens on the caller's
// thread (main, in the host) — no RT-thread involvement, same as any Swift
// `build()`.
import LyrebirdSynth
/// Builds a generator graph from a DSL expression.
public enum DSLGraphBuilder {
/// Build `expr` into a signal graph (its top-level value must be a signal,
/// not a resource). Convenience over ``build(_:resources:)`` for expressions
/// that reference no resources.
/// - Throws: ``DSLBuildError`` for an unknown generator, a bad argument, or
/// a type mismatch.
public static func build(_ expr: DSLExpr) throws -> any ValidGeneratorInput {
try signal(from: try build(expr, resources: DSLEmptyResources()))
}
/// Build `expr` into a ``DSLValue`` (a signal or a resource), resolving bare
/// identifiers through `resources`.
public static func build(
_ expr: DSLExpr,
resources: DSLResourceResolver
) throws -> DSLValue {
switch expr {
case .number(let value, _):
return .signal(value)
case .reference(let name, _):
guard let buffer: LyrebirdBuffer = resources.buffer(named: name) else {
// A better hint when the bare identifier is actually a generator
// missing its call parentheses.
if !DSLBuiltinRegistry.rates(of: name).isEmpty {
throw DSLBuildError.referenceIsGenerator(name)
}
throw DSLBuildError.unknownReference(name)
}
return .buffer(buffer)
case .binary(let op, let lhs, let rhs, _):
let l: any ValidGeneratorInput = try signal(from: try build(lhs, resources: resources))
let r: any ValidGeneratorInput = try signal(from: try build(rhs, resources: resources))
return .signal(apply(op, l, r))
case .call(let name, let rate, let arguments, _):
let builtin: DSLBuiltin = try resolve(name, rate: rate)
let bound: [String: DSLValue] = try bind(arguments, to: builtin, resources: resources)
return .signal(try builtin.make(bound))
}
}
/// Unwrap a signal, rejecting a resource used where a signal is required.
private static func signal(from value: DSLValue) throws -> any ValidGeneratorInput {
guard case .signal(let s) = value else {
throw DSLBuildError.operatorRequiresSignal
}
return s
}
/// Resolve a name (and optional explicit rate) to a builtin.
///
/// With an explicit rate (`.Audio`/`.Control`), looks up exactly that rate and
/// throws ``DSLBuildError/rateUnavailable(builtin:rate:)`` if the name has
/// no such variant. Without one, prefers audio and falls back to a name's
/// sole rate (so a control-only generator like `MouseX` is reachable).
private static func resolve(_ name: String, rate: DSLRate?) throws -> DSLBuiltin {
let rates: Set<DSLRate> = DSLBuiltinRegistry.rates(of: name)
guard !rates.isEmpty else { throw DSLBuildError.unknownBuiltin(name) }
if let rate: DSLRate = rate {
return try DSLBuiltinRegistry.lookup(name, rate: rate)
}
if rates.contains(.audio) {
return try DSLBuiltinRegistry.lookup(name, rate: .audio)
}
return try DSLBuiltinRegistry.lookup(name, rate: .control)
}
/// Bind call arguments to parameter labels: positional arguments fill
/// parameters in declaration order; labelled arguments bind by label.
private static func bind(
_ arguments: [DSLExpr.Argument],
to builtin: DSLBuiltin,
resources: DSLResourceResolver
) throws -> [String: DSLValue] {
let labels: [String] = builtin.parameters.map { $0.label }
var bound: [String: DSLValue] = [:]
var nextPositional: Int = 0
for argument: DSLExpr.Argument in arguments {
let value: DSLValue = try build(argument.value, resources: resources)
let targetLabel: String
if let label: String = argument.label {
guard labels.contains(label) else {
throw DSLBuildError.unknownArgument(builtin: builtin.name, label: label)
}
targetLabel = label
} else {
// Advance past parameters already filled (labelled or positional).
while nextPositional < labels.count, bound[labels[nextPositional]] != nil {
nextPositional += 1
}
guard nextPositional < labels.count else {
throw DSLBuildError.tooManyArguments(builtin: builtin.name, max: labels.count)
}
targetLabel = labels[nextPositional]
nextPositional += 1
}
// A parameter bound twice (a positional then a label, or two labels)
// is an error, not a silent overwrite.
guard bound[targetLabel] == nil else {
throw DSLBuildError.duplicateArgument(builtin: builtin.name, label: targetLabel)
}
bound[targetLabel] = value
}
return bound
}
private static func apply(
_ op: DSLExpr.BinaryOp,
_ lhs: any ValidGeneratorInput,
_ rhs: any ValidGeneratorInput
) -> any ValidGeneratorInput {
switch op {
case .add: return lhs + rhs
case .subtract: return lhs - rhs
case .multiply: return lhs * rhs
case .divide: return lhs / rhs
}
}
}
@@ -0,0 +1,41 @@
// DSLInterpreter.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// The one-call front door: lex + parse + build DSL source into playable outputs.
// Instant (no swiftc), pure Swift over core types — the whole point of the
// interpreted path.
import LyrebirdSynth
/// Evaluates DSL source into playable graphs.
public enum DSLInterpreter {
/// Lex, parse, and build `source` into one ``DSLOutput`` per statement,
/// resolving bare-identifier resource references through `resources`.
///
/// - Throws: ``DSLParseError`` for a lex/parse failure, or ``DSLBuildError``
/// for an unknown generator / bad argument / unresolved resource. Both
/// carry enough to surface a diagnostic.
public static func evaluate(
_ source: String,
resources: DSLResourceResolver = DSLEmptyResources()
) throws -> [DSLOutput] {
let program: DSLProgram = try DSLParser.parse(source)
return try program.statements.map { statement in
let (slot, expr): (String?, DSLExpr)
switch statement {
case .assignment(let name, let value, _): (slot, expr) = (name, value)
case .expression(let e): (slot, expr) = (nil, e)
}
// A top-level statement must produce a signal — you cannot play a
// bare buffer.
guard case .signal(let graph) = try DSLGraphBuilder.build(expr, resources: resources) else {
throw DSLBuildError.cannotPlayResource
}
return DSLOutput(slot: slot, graph: graph)
}
}
}
+98
View File
@@ -0,0 +1,98 @@
// DSLLexer.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Turns DSL source into a flat token stream. Whitespace is skipped, `#` runs to
// end of line as a comment, and runs of blank lines collapse to one `newline`
// separator. Spans are character offsets into the source.
/// Lexes DSL source into ``DSLToken``s.
public enum DSLLexer {
/// Tokenize `source`, ending with a single `.eof` token.
/// - Throws: ``DSLParseError`` on a character that starts no valid token.
public static func tokenize(_ source: String) throws -> [DSLToken] {
let chars: [Character] = Array(source)
let count: Int = chars.count
var i: Int = 0
var tokens: [DSLToken] = []
func punct(_ kind: DSLToken.Kind) {
tokens.append(DSLToken(kind: kind, text: "", span: DSLSpan(start: i, end: i + 1)))
i += 1
}
while i < count {
let c: Character = chars[i]
// Horizontal whitespace.
if c == " " || c == "\t" || c == "\r" {
i += 1
continue
}
// Comment to end of line.
if c == "#" {
while i < count, chars[i] != "\n" { i += 1 }
continue
}
// Newline(s) collapse to one separator.
if c == "\n" {
let start: Int = i
while i < count, chars[i] == "\n" || chars[i] == " " || chars[i] == "\t" || chars[i] == "\r" {
i += 1
}
tokens.append(DSLToken(kind: .newline, text: "", span: DSLSpan(start: start, end: i)))
continue
}
// Number: ASCII digits with optional fraction / exponent. (ASCII so
// `½`/`²`/other Unicode numerics don't lex as a number then fail.)
if isASCIIDigit(c) {
let start: Int = i
while i < count, isASCIIDigit(chars[i]) || chars[i] == "_" { i += 1 }
if i < count, chars[i] == ".", i + 1 < count, isASCIIDigit(chars[i + 1]) {
i += 1
while i < count, isASCIIDigit(chars[i]) || chars[i] == "_" { i += 1 }
}
if i < count, chars[i] == "e" || chars[i] == "E" {
i += 1
if i < count, chars[i] == "+" || chars[i] == "-" { i += 1 }
while i < count, isASCIIDigit(chars[i]) { i += 1 }
}
let text: String = String(chars[start..<i])
tokens.append(DSLToken(kind: .number, text: text, span: DSLSpan(start: start, end: i)))
continue
}
// Identifier.
if c.isLetter || c == "_" {
let start: Int = i
while i < count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" { i += 1 }
let text: String = String(chars[start..<i])
tokens.append(DSLToken(kind: .identifier, text: text, span: DSLSpan(start: start, end: i)))
continue
}
// Punctuation.
switch c {
case "(": punct(.leftParen)
case ")": punct(.rightParen)
case ",": punct(.comma)
case ":": punct(.colon)
case ".": punct(.dot)
case "=": punct(.equals)
case "+": punct(.plus)
case "-": punct(.minus)
case "*": punct(.star)
case "/": punct(.slash)
default:
throw DSLParseError(kind: .unexpectedCharacter(c), span: DSLSpan(start: i, end: i + 1))
}
}
tokens.append(DSLToken(kind: .eof, text: "", span: DSLSpan.point(count)))
return tokens
}
private static func isASCIIDigit(_ c: Character) -> Bool {
c >= "0" && c <= "9"
}
}
+24
View File
@@ -0,0 +1,24 @@
// DSLOutput.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// One built statement from a DSL program: a graph, and the slot name it should
// play into (nil for an anonymous output). The host turns these into
// `context.play` / `context.play(slot:)` calls.
import LyrebirdSynth
/// A built DSL statement ready for the host to play.
public struct DSLOutput {
/// The named slot to play into, or `nil` for an anonymous output.
public let slot: String?
/// The built generator graph.
public let graph: any ValidGeneratorInput
public init(slot: String?, graph: any ValidGeneratorInput) {
self.slot = slot
self.graph = graph
}
}
@@ -0,0 +1,26 @@
// DSLParameter.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// One declared parameter of a `DSLBuiltin`.
/// A single declared parameter of a ``DSLBuiltin``.
///
/// `label` is the argument label as written in the DSL (`freq`, `mul`, …).
/// `hasDefault` is `true` when the underlying Swift init supplies a default the
/// DSL can rely on, so the argument may be omitted; a parameter without one is
/// required.
public struct DSLParameter: Equatable, Sendable {
public let label: String
public let hasDefault: Bool
public init(
label: String,
hasDefault: Bool
) {
self.label = label
self.hasDefault = hasDefault
}
}
@@ -0,0 +1,47 @@
// DSLParseError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Errors from lexing / parsing DSL source, each carrying the span to blame.
/// A lexing or parsing failure, with the source span to point at.
public struct DSLParseError: Error, Equatable, Sendable, CustomStringConvertible {
public enum Kind: Equatable, Sendable {
/// A character that starts no valid token.
case unexpectedCharacter(Character)
/// A malformed number literal.
case invalidNumber(String)
/// Expected `expected` but found `found`.
case expected(String, found: String)
/// A call argument list or parenthesised group was left open.
case unclosedParen
/// Expression nesting exceeded the parser's depth ceiling.
case tooDeeplyNested
/// A rate suffix other than `.Audio` / `.Control`.
case invalidRate(String)
}
public let kind: Kind
public let span: DSLSpan
public init(kind: Kind, span: DSLSpan) {
self.kind = kind
self.span = span
}
public var description: String {
let detail: String
switch kind {
case .unexpectedCharacter(let c): detail = "unexpected character '\(c)'"
case .invalidNumber(let s): detail = "invalid number '\(s)'"
case .expected(let e, let f): detail = "expected \(e), found \(f)"
case .unclosedParen: detail = "unclosed '('"
case .tooDeeplyNested: detail = "expression nested too deeply"
case .invalidRate(let r): detail = "unknown rate '.\(r)' (use .Audio or .Control)"
}
return "\(detail) (at \(span.start))"
}
}
+253
View File
@@ -0,0 +1,253 @@
// DSLParser.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Recursive-descent parser producing a `DSLProgram` from a token stream.
//
// Grammar (v1):
// program = { line }
// line = [ statement ] newline
// statement = ( ident "=" expr ) | expr
// expr = term { ("+"|"-") term }
// term = factor { ("*"|"/") factor }
// factor = "-" factor | number | call | "(" expr ")"
// call = ident "(" [ args ] ")"
// args = arg { "," arg }
// arg = [ ident ":" ] expr
/// Parses DSL tokens into a ``DSLProgram``.
public struct DSLParser {
private let tokens: [DSLToken]
private var pos: Int = 0
/// Recursion-depth ceiling — pathological or generated input (deeply nested
/// parens / calls) throws instead of overflowing the stack and crashing the
/// host process.
private static let maxDepth: Int = 128
public init(tokens: [DSLToken]) {
self.tokens = tokens
}
/// Lex + parse `source` in one step.
public static func parse(_ source: String) throws -> DSLProgram {
var parser: DSLParser = DSLParser(tokens: try DSLLexer.tokenize(source))
return try parser.parseProgram()
}
// MARK: - Cursor
private var current: DSLToken { tokens[pos] }
@discardableResult
private mutating func advance() -> DSLToken {
let t: DSLToken = tokens[pos]
if pos < tokens.count - 1 { pos += 1 }
return t
}
private func check(_ kind: DSLToken.Kind) -> Bool { current.kind == kind }
@discardableResult
private mutating func match(_ kind: DSLToken.Kind) -> Bool {
if check(kind) { advance(); return true }
return false
}
private mutating func expect(_ kind: DSLToken.Kind, _ label: String) throws -> DSLToken {
guard check(kind) else {
throw DSLParseError(kind: .expected(label, found: describe(current)),
span: current.span)
}
return advance()
}
private func describe(_ token: DSLToken) -> String {
switch token.kind {
case .eof: return "end of input"
case .newline: return "end of line"
case .identifier, .number: return "'\(token.text)'"
default: return "'\(punctText(token.kind))'"
}
}
private func punctText(_ kind: DSLToken.Kind) -> String {
switch kind {
case .leftParen: return "("
case .rightParen: return ")"
case .comma: return ","
case .colon: return ":"
case .dot: return "."
case .equals: return "="
case .plus: return "+"
case .minus: return "-"
case .star: return "*"
case .slash: return "/"
default: return "?"
}
}
// MARK: - Grammar
private mutating func parseProgram() throws -> DSLProgram {
var statements: [DSLProgram.Statement] = []
while !check(.eof) {
// Skip blank separators.
if match(.newline) { continue }
statements.append(try parseStatement())
// Statement must end at a newline or eof.
if !check(.eof) {
_ = try expect(.newline, "end of line")
}
}
return DSLProgram(statements: statements)
}
private mutating func parseStatement() throws -> DSLProgram.Statement {
// `ident =` → assignment; else an expression.
if check(.identifier), tokens[pos + 1].kind == .equals {
let name: DSLToken = advance()
advance() // '='
let value: DSLExpr = try parseExpr(depth: 0)
return .assignment(name: name.text, value: value,
DSLSpan(start: name.span.start, end: value.span.end))
}
return .expression(try parseExpr(depth: 0))
}
private mutating func parseExpr(depth: Int) throws -> DSLExpr {
guard depth <= DSLParser.maxDepth else {
throw DSLParseError(kind: .tooDeeplyNested, span: current.span)
}
var lhs: DSLExpr = try parseTerm(depth: depth)
while check(.plus) || check(.minus) {
let op: DSLExpr.BinaryOp = check(.plus) ? .add : .subtract
advance()
let rhs: DSLExpr = try parseTerm(depth: depth)
lhs = Self.fold(op, lhs, rhs)
}
return lhs
}
private mutating func parseTerm(depth: Int) throws -> DSLExpr {
var lhs: DSLExpr = try parseFactor(depth: depth)
while check(.star) || check(.slash) {
let op: DSLExpr.BinaryOp = check(.star) ? .multiply : .divide
advance()
let rhs: DSLExpr = try parseFactor(depth: depth)
lhs = Self.fold(op, lhs, rhs)
}
return lhs
}
private mutating func parseFactor(depth: Int) throws -> DSLExpr {
guard depth <= DSLParser.maxDepth else {
throw DSLParseError(kind: .tooDeeplyNested, span: current.span)
}
// Unary minus — folded into a negative literal when the operand is a
// number, so numeric-literal-only parameters accept `-0.5`.
if check(.minus) {
let minus: DSLToken = advance()
let operand: DSLExpr = try parseFactor(depth: depth + 1)
let span: DSLSpan = DSLSpan(start: minus.span.start, end: operand.span.end)
if case .number(let n, _) = operand {
return .number(-n, span)
}
let zero: DSLExpr = .number(0, DSLSpan.point(minus.span.start))
return .binary(op: .subtract, lhs: zero, rhs: operand, span)
}
if check(.number) {
let t: DSLToken = advance()
guard let value: Double = Double(t.text.replacingOccurrences(of: "_", with: "")) else {
throw DSLParseError(kind: .invalidNumber(t.text), span: t.span)
}
return .number(value, t.span)
}
if check(.leftParen) {
let open: DSLToken = advance()
let inner: DSLExpr = try parseExpr(depth: depth + 1)
guard check(.rightParen) else {
throw DSLParseError(kind: .unclosedParen, span: open.span)
}
advance()
return inner
}
if check(.identifier) {
// `Name(` or `Name.` → a call; a bare identifier → a resource reference.
let next: DSLToken.Kind = tokens[pos + 1].kind
if next == .leftParen || next == .dot {
return try parseCall(depth: depth)
}
let ident: DSLToken = advance()
return .reference(name: ident.text, ident.span)
}
throw DSLParseError(kind: .expected("a number, name, or '('", found: describe(current)),
span: current.span)
}
private mutating func parseCall(depth: Int) throws -> DSLExpr {
let name: DSLToken = advance()
// Optional rate suffix — the *exact* Swift nested-class names so a DSL
// graph expression is paste-compatible with a Lyrebird project:
// `OscSin.Control(freq: 4)` reads and constructs identically in both.
var rate: DSLRate? = nil
if match(.dot) {
let rateToken: DSLToken = try expect(.identifier, "'Audio' or 'Control'")
switch rateToken.text {
case "Audio": rate = .audio
case "Control": rate = .control
default:
throw DSLParseError(kind: .invalidRate(rateToken.text), span: rateToken.span)
}
}
let open: DSLToken = try expect(.leftParen, "(")
var arguments: [DSLExpr.Argument] = []
if !check(.rightParen) {
repeat {
arguments.append(try parseArgument(depth: depth + 1))
} while match(.comma)
}
guard check(.rightParen) else {
throw DSLParseError(kind: .unclosedParen, span: open.span)
}
let close: DSLToken = advance()
return .call(name: name.text, rate: rate, arguments: arguments,
DSLSpan(start: name.span.start, end: close.span.end))
}
private mutating func parseArgument(depth: Int) throws -> DSLExpr.Argument {
guard depth <= DSLParser.maxDepth else {
throw DSLParseError(kind: .tooDeeplyNested, span: current.span)
}
// `ident :` → labelled argument.
if check(.identifier), tokens[pos + 1].kind == .colon {
let label: DSLToken = advance()
advance() // ':'
let value: DSLExpr = try parseExpr(depth: depth)
return DSLExpr.Argument(label: label.text, value: value,
span: DSLSpan(start: label.span.start, end: value.span.end))
}
let value: DSLExpr = try parseExpr(depth: depth)
return DSLExpr.Argument(label: nil, value: value, span: value.span)
}
/// Constant-fold a binary op over two number literals so computed constants
/// (`220 * 2`, `-0.5`) stay usable where a numeric literal is required.
/// Division by zero is left un-folded (built as a generator node).
private static func fold(_ op: DSLExpr.BinaryOp, _ lhs: DSLExpr, _ rhs: DSLExpr) -> DSLExpr {
let span: DSLSpan = DSLSpan(start: lhs.span.start, end: rhs.span.end)
if case .number(let a, _) = lhs, case .number(let b, _) = rhs {
switch op {
case .add: return .number(a + b, span)
case .subtract: return .number(a - b, span)
case .multiply: return .number(a * b, span)
case .divide where b != 0: return .number(a / b, span)
case .divide: break
}
}
return .binary(op: op, lhs: lhs, rhs: rhs, span)
}
}
+26
View File
@@ -0,0 +1,26 @@
// DSLProgram.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// A parsed DSL program: a sequence of statements, each either an anonymous
// output expression or a named-slot assignment.
/// A parsed DSL program.
public struct DSLProgram: Equatable, Sendable {
/// One top-level statement.
public enum Statement: Equatable, Sendable {
/// `name = expr` — bind the graph to a named slot.
case assignment(name: String, value: DSLExpr, DSLSpan)
/// A bare expression — an anonymous output.
case expression(DSLExpr)
}
public let statements: [Statement]
public init(statements: [Statement]) {
self.statements = statements
}
}
+18
View File
@@ -0,0 +1,18 @@
// DSLRate.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// The evaluation rate of a builtin — audio-rate (per-sample) or control-rate
// (per-block). A generator name can exist at both rates (`OscSin` audio and
// control); the registry keys builtins by name AND rate.
/// The rate at which a ``DSLBuiltin`` evaluates.
/// (`Equatable`/`Hashable` are synthesized for the `String`-raw enum.)
public enum DSLRate: String, Sendable, CaseIterable {
/// Audio rate — the `.Audio` generator variant (per-sample).
case audio
/// Control rate — the `.Control` generator variant (per-block).
case control
}
@@ -0,0 +1,34 @@
// DSLResourceResolver.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// How the DSL resolves a bare identifier (`PlayBuffer(buffer: kick)`) to a host
// resource. The host implements this to register the buffers a snippet may name.
import LyrebirdSynth
/// Resolves DSL resource references (bare identifiers) to host objects.
public protocol DSLResourceResolver {
/// The buffer registered under `name`, or `nil` if there is none.
func buffer(named name: String) -> LyrebirdBuffer?
}
/// A resolver with no resources — every reference is unresolved. The default for
/// ``DSLInterpreter/evaluate(_:resources:)``.
public struct DSLEmptyResources: DSLResourceResolver {
public init() {}
public func buffer(named name: String) -> LyrebirdBuffer? { nil }
}
/// A resolver backed by a name→buffer dictionary — convenient for hosts and tests.
public struct DSLBufferTable: DSLResourceResolver {
private let buffers: [String: LyrebirdBuffer]
public init(_ buffers: [String: LyrebirdBuffer]) {
self.buffers = buffers
}
public func buffer(named name: String) -> LyrebirdBuffer? { buffers[name] }
}
+24
View File
@@ -0,0 +1,24 @@
// DSLSpan.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// A half-open character range into DSL source, carried by tokens and AST nodes
// so parse/build errors can point at the offending text.
/// A `[start, end)` range in *character* offsets into the DSL source string.
public struct DSLSpan: Equatable, Sendable {
public let start: Int
public let end: Int
public init(start: Int, end: Int) {
self.start = start
self.end = end
}
/// A zero-length span at `offset` (for end-of-input / synthetic positions).
public static func point(_ offset: Int) -> DSLSpan {
DSLSpan(start: offset, end: offset)
}
}
+43
View File
@@ -0,0 +1,43 @@
// DSLToken.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// A lexed token: a kind, the source text it covers, and its span.
/// One token produced by ``DSLLexer``.
public struct DSLToken: Equatable, Sendable {
/// The lexical categories the DSL recognises.
public enum Kind: Equatable, Sendable {
case identifier
case number
case leftParen
case rightParen
case comma
case colon
case dot
case equals
case plus
case minus
case star
case slash
/// A statement separator (one or more newlines collapsed).
case newline
/// End of input.
case eof
}
public let kind: Kind
/// The exact source text (identifier name, number literal, …). Empty for
/// punctuation / newline / eof.
public let text: String
public let span: DSLSpan
public init(kind: Kind, text: String, span: DSLSpan) {
self.kind = kind
self.text = text
self.span = span
}
}
+27
View File
@@ -0,0 +1,27 @@
// DSLValue.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// The runtime value of a built DSL expression. Most expressions are a *signal*
// (a number or a generator graph, both `any ValidGeneratorInput`); a bare
// identifier resolves to a *resource* the host registered — currently a buffer.
// A generator init parameter pulls the shape it needs out of a `DSLValue` via
// `DSLArgument`.
import LyrebirdSynth
/// A value produced while building a DSL expression.
///
/// Not `Sendable` — it carries `any ValidGeneratorInput` / `LyrebirdBuffer`,
/// neither of which is. It flows through ``DSLBuiltin/make`` (a `@Sendable`
/// closure so the registry can be a `static let`), but only during synchronous,
/// single-thread graph construction: the generated closures capture nothing, so
/// no value actually crosses a concurrency boundary.
public enum DSLValue {
/// A number or generator graph.
case signal(any ValidGeneratorInput)
/// A host-registered buffer (from a bare identifier reference).
case buffer(LyrebirdBuffer)
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,46 @@
// DSLArgumentTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdSynth
import LyrebirdGraphDSL
@Suite("DSLArgument")
struct DSLArgumentTests {
@Test func doubleFromDoubleAndInt() throws {
#expect(try DSLArgument.double(sig(2.5), "G", "x") == 2.5)
#expect(try DSLArgument.double(sig(3), "G", "x") == 3.0)
}
@Test func doubleRejectsSignal() throws {
let signal: any ValidGeneratorInput = OscSin.Audio(freq: 440)
#expect(throws: DSLBuildError.expectedNumber(builtin: "G", label: "x")) {
_ = try DSLArgument.double(sig(signal), "G", "x")
}
}
@Test func missingRequiredThrows() {
#expect(throws: DSLBuildError.missingArgument(builtin: "G", label: "x")) {
_ = try DSLArgument.double(nil, "G", "x")
}
}
@Test func intTruncatesFraction() throws {
#expect(try DSLArgument.int(sig(3.9), "G", "x") == 3)
#expect(try DSLArgument.int(sig(-2.9), "G", "x") == -2)
}
@Test func intOutOfRangeThrowsInsteadOfTrapping() {
#expect(throws: DSLBuildError.numberOutOfRange(builtin: "G", label: "x")) {
_ = try DSLArgument.int(sig(1e30), "G", "x")
}
}
@Test func floatCoerces() throws {
#expect(try DSLArgument.float(sig(0.5), "G", "x") == Float(0.5))
}
}
@@ -0,0 +1,48 @@
// DSLBuiltinTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdSynth
import LyrebirdGraphDSL
@MainActor
@Suite("DSLBuiltin")
struct DSLBuiltinTests {
/// A `DSLBuiltin` wrapping `OscSin` — the exact shape the code-gen tool will
/// emit — constructs a real generator that renders audio through the engine.
/// Locks the registry contract that the parser/builder will consume.
@Test func builtinConstructsAndRendersGenerator() throws {
let builtin: DSLBuiltin = DSLBuiltin(
name: "OscSin",
rate: .audio,
parameters: [
DSLParameter(label: "freq", hasDefault: false),
DSLParameter(label: "mul", hasDefault: true),
DSLParameter(label: "add", hasDefault: true),
],
make: { args in
OscSin.Audio(
freq: try DSLArgument.input(args["freq"], "OscSin", "freq"),
mul: try DSLArgument.input(args["mul"] ?? .signal(1.0), "OscSin", "mul"),
add: try DSLArgument.input(args["add"] ?? .signal(0.0), "OscSin", "add")
)
}
)
#expect(builtin.name == "OscSin")
#expect(builtin.parameters.first == DSLParameter(label: "freq", hasDefault: false))
let graph: any ValidGeneratorInput = try builtin.make(["freq": sig(440.0), "mul": sig(0.1)])
let engine: SynthesisEngine = makeDSLTestEngine()
try engine.start()
try engine.add(ClosureSynthesizer { graph })
engine.processBlock(inputSamples: [])
let anyNonZero: Bool = (0..<engine.blockSize).contains { engine.audioBuses[0][$0] != 0.0 }
#expect(anyNonZero)
}
}
@@ -0,0 +1,140 @@
// DSLInterpreterTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdSynth
import LyrebirdGraphDSL
@MainActor
@Suite("DSLInterpreter")
struct DSLInterpreterTests {
/// Add each built output to the engine and render one block.
private func render(_ outputs: [DSLOutput]) throws -> SynthesisEngine {
let engine: SynthesisEngine = makeDSLTestEngine()
try engine.start()
for output: DSLOutput in outputs {
try engine.add(ClosureSynthesizer { output.graph })
}
engine.processBlock(inputSamples: [])
return engine
}
@Test func evaluatesAndRendersASineTimesGain() throws {
let outputs: [DSLOutput] = try DSLInterpreter.evaluate("OscSin(freq: 440) * 0.1")
#expect(outputs.count == 1)
#expect(outputs[0].slot == nil)
let engine: SynthesisEngine = try render(outputs)
#expect(busHasSignal(engine, bus: 0))
}
@Test func slotAssignmentCarriesTheSlotName() throws {
let outputs: [DSLOutput] = try DSLInterpreter.evaluate("bass = OscSin(freq: 55) * 0.2")
#expect(outputs[0].slot == "bass")
let engine: SynthesisEngine = try render(outputs)
#expect(busHasSignal(engine, bus: 0))
}
@Test func nestedGraphRendersStereo() throws {
let outputs: [DSLOutput] = try DSLInterpreter.evaluate(
"Pan2(input: OscSin(freq: 440) * 0.1, pan: 0)"
)
let engine: SynthesisEngine = try render(outputs)
#expect(busHasSignal(engine, bus: 0))
#expect(busHasSignal(engine, bus: 1))
}
@Test func positionalArgumentsBind() throws {
// OscSin(freq) positionally.
let outputs: [DSLOutput] = try DSLInterpreter.evaluate("OscSin(440) * 0.1")
let engine: SynthesisEngine = try render(outputs)
#expect(busHasSignal(engine, bus: 0))
}
@Test func multipleStatementsProduceMultipleOutputs() throws {
let outputs: [DSLOutput] = try DSLInterpreter.evaluate(
"bass = OscSin(freq: 55) * 0.2\nlead = OscSin(freq: 440) * 0.1"
)
#expect(outputs.count == 2)
#expect(outputs.map { $0.slot } == ["bass", "lead"])
}
@Test func unknownGeneratorThrows() {
#expect(throws: DSLBuildError.unknownBuiltin("NotAGenerator")) {
_ = try DSLInterpreter.evaluate("NotAGenerator(freq: 1)")
}
}
@Test func unknownArgumentThrows() {
#expect(throws: DSLBuildError.unknownArgument(builtin: "OscSin", label: "nope")) {
_ = try DSLInterpreter.evaluate("OscSin(nope: 1)")
}
}
@Test func missingRequiredArgumentThrows() {
// OscSin.freq is required.
#expect(throws: DSLBuildError.missingArgument(builtin: "OscSin", label: "freq")) {
_ = try DSLInterpreter.evaluate("OscSin(mul: 0.1)")
}
}
@Test func controlOnlyGeneratorResolvesViaFallback() throws {
// MouseX is control-only; the builder falls back to its sole rate.
let outputs: [DSLOutput] = try DSLInterpreter.evaluate("MouseX()")
#expect(outputs.count == 1)
}
@Test func explicitControlRateSelectsControlVariant() throws {
// `.Control` requests the control-rate OscSin driving an audio OscSin's freq.
let outputs: [DSLOutput] = try DSLInterpreter.evaluate(
"OscSin(freq: OscSin.Control(freq: 4, mul: 50, add: 440), mul: 0.1)"
)
let engine: SynthesisEngine = try render(outputs)
#expect(busHasSignal(engine, bus: 0))
}
@Test func explicitRateOnUnavailableVariantThrows() {
// Pan2 is audio-only; `.Control` must fail rather than silently pick audio.
#expect(throws: DSLBuildError.rateUnavailable(builtin: "Pan2", rate: "control")) {
_ = try DSLInterpreter.evaluate("Pan2.Control(input: OscSin(freq: 1), pan: 0)")
}
}
@Test func invalidRateSuffixThrows() {
#expect(throws: DSLParseError.self) {
_ = try DSLInterpreter.evaluate("OscSin.xyz(freq: 440)")
}
}
/// Paste-compatibility: the exact Swift form `OscSin.Audio(freq: 440) * 0.1`
/// — capitalized nested-class name and all — evaluates and renders in the
/// DSL, so a graph expression copied to/from a Lyrebird `build()` is spelled
/// the same in both places.
@Test func swiftFormGraphExpressionEvaluates() throws {
let outputs: [DSLOutput] = try DSLInterpreter.evaluate(
"Pan2(input: OscSin.Audio(freq: 440) * 0.1, pan: 0)"
)
let engine: SynthesisEngine = try render(outputs)
#expect(busHasSignal(engine, bus: 0))
#expect(busHasSignal(engine, bus: 1))
}
@Test func duplicateArgumentThrows() {
// A parameter bound twice (positional then label) is an error.
#expect(throws: DSLBuildError.duplicateArgument(builtin: "OscSin", label: "freq")) {
_ = try DSLInterpreter.evaluate("OscSin(440, freq: 550)")
}
}
@Test func foldedConstantSatisfiesNumericParameter() throws {
// DelayLine.delay is a Double (numeric-literal-only). A folded computed
// constant must reach it as a number, not a signal — build must succeed
// (an un-folded `0.1 * 2` would be a generator and throw expectedNumber).
_ = try DSLInterpreter.evaluate(
"DelayLine(input: OscSin(freq: 440) * 0.1, maxDelay: 0.5, delay: 0.1 * 2)"
)
}
}
@@ -0,0 +1,51 @@
// DSLLexerTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdGraphDSL
@Suite("DSLLexer")
struct DSLLexerTests {
private func kinds(_ source: String) throws -> [DSLToken.Kind] {
try DSLLexer.tokenize(source).map { $0.kind }
}
@Test func tokenizesACall() throws {
#expect(try kinds("OscSin(freq: 440)") == [
.identifier, .leftParen, .identifier, .colon, .number, .rightParen, .eof,
])
}
@Test func tokenizesOperatorsAndParens() throws {
#expect(try kinds("(a + b) * 0.5") == [
.leftParen, .identifier, .plus, .identifier, .rightParen, .star, .number, .eof,
])
}
@Test func skipsCommentsAndCollapsesNewlines() throws {
#expect(try kinds("a # comment\n\n\nb") == [
.identifier, .newline, .identifier, .eof,
])
}
@Test func numberFormsAndUnderscores() throws {
let toks: [DSLToken] = try DSLLexer.tokenize("440 0.15 2e3 44_100")
let numbers: [String] = toks.filter { $0.kind == .number }.map { $0.text }
#expect(numbers == ["440", "0.15", "2e3", "44_100"])
}
@Test func unexpectedCharacterThrows() {
#expect(throws: DSLParseError.self) {
_ = try DSLLexer.tokenize("a @ b")
}
}
@Test func spansCoverSourceText() throws {
let toks: [DSLToken] = try DSLLexer.tokenize("OscSin")
#expect(toks.first?.span == DSLSpan(start: 0, end: 6))
}
}
@@ -0,0 +1,112 @@
// DSLParserTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdGraphDSL
@Suite("DSLParser")
struct DSLParserTests {
@Test func parsesAnonymousCall() throws {
let program: DSLProgram = try DSLParser.parse("OscSin(freq: 440, mul: 0.1)")
#expect(program.statements.count == 1)
guard case .expression(let expr) = program.statements[0],
case .call(let name, _, let args, _) = expr else {
Issue.record("expected a call expression"); return
}
#expect(name == "OscSin")
#expect(args.map { $0.label } == ["freq", "mul"])
}
@Test func parsesSlotAssignment() throws {
let program: DSLProgram = try DSLParser.parse("bass = OscSin(freq: 55)")
guard case .assignment(let name, _, _) = program.statements[0] else {
Issue.record("expected an assignment"); return
}
#expect(name == "bass")
}
@Test func operatorPrecedenceMultiplyBeforeAdd() throws {
// a + b * c ==> a + (b * c)
let program: DSLProgram = try DSLParser.parse("A(freq: 1) + B(freq: 2) * C(freq: 3)")
guard case .expression(let expr) = program.statements[0],
case .binary(let op, _, let rhs, _) = expr else {
Issue.record("expected a binary add"); return
}
#expect(op == .add)
guard case .binary(let innerOp, _, _, _) = rhs else {
Issue.record("rhs should be the multiply"); return
}
#expect(innerOp == .multiply)
}
@Test func parensOverridePrecedence() throws {
// (a + b) * c ==> multiply at the top
let program: DSLProgram = try DSLParser.parse("(A(freq: 1) + B(freq: 2)) * C(freq: 3)")
guard case .expression(let expr) = program.statements[0],
case .binary(let op, _, _, _) = expr else {
Issue.record("expected a binary"); return
}
#expect(op == .multiply)
}
@Test func nestedCallAsArgument() throws {
let program: DSLProgram = try DSLParser.parse("Pan2(input: OscSin(freq: 440), pan: 0)")
guard case .expression(.call(_, _, let args, _)) = program.statements[0],
case .call(let innerName, _, _, _) = args[0].value else {
Issue.record("expected a nested call argument"); return
}
#expect(innerName == "OscSin")
}
@Test func multipleStatementsAcrossLines() throws {
let program: DSLProgram = try DSLParser.parse("bass = A(freq: 1)\nlead = B(freq: 2)")
#expect(program.statements.count == 2)
}
@Test func trailingGarbageThrows() {
#expect(throws: DSLParseError.self) {
_ = try DSLParser.parse("OscSin(freq: 440) 123")
}
}
@Test func deeplyNestedInputThrowsInsteadOfCrashing() {
// Pathological / generated input must not overflow the stack.
let deep: String = String(repeating: "(", count: 1000) + "1"
+ String(repeating: ")", count: 1000)
#expect(throws: DSLParseError.self) {
_ = try DSLParser.parse(deep)
}
}
@Test func unclosedParenThrowsSpecificError() throws {
do {
_ = try DSLParser.parse("OscSin(freq: 440")
Issue.record("expected unclosedParen")
} catch let error as DSLParseError {
#expect(error.kind == .unclosedParen)
}
}
@Test func constantFoldingProducesNumberNodes() throws {
// 220 * 2 folds to a single number literal.
let program: DSLProgram = try DSLParser.parse("Osc(freq: 220 * 2)")
guard case .expression(.call(_, _, let args, _)) = program.statements[0],
case .number(let n, _) = args[0].value else {
Issue.record("expected a folded number"); return
}
#expect(n == 440)
}
@Test func unaryMinusFoldsToNegativeNumber() throws {
let program: DSLProgram = try DSLParser.parse("Osc(add: -0.5)")
guard case .expression(.call(_, _, let args, _)) = program.statements[0],
case .number(let n, _) = args[0].value else {
Issue.record("expected a negative number literal"); return
}
#expect(n == -0.5)
}
}
@@ -0,0 +1,93 @@
// DSLResourceTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdSynth
import LyrebirdGraphDSL
@MainActor
@Suite("DSL resources (buffers)")
struct DSLResourceTests {
/// A short buffer filled with a constant so a PlayBuffer read is audible.
private func makeBuffer() -> LyrebirdBuffer {
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 64)
buffer.fill(with: 0.5)
return buffer
}
/// A bare identifier resolves to the registered buffer as a `.buffer`
/// `DSLValue` — the resolution the DSL adds. (Constructing a buffer generator
/// like PlayBuffer and rendering it is the core buffer tests' job; doing it
/// here only re-tests that RT path, and a mapped buffer held in a torn-down
/// test engine races ARC at teardown — a known core buffer-lifecycle issue.)
@Test func bufferReferenceResolvesToBufferValue() throws {
let buffer: LyrebirdBuffer = makeBuffer()
let resources: DSLBufferTable = DSLBufferTable(["kick": buffer])
let value: DSLValue = try DSLGraphBuilder.build(
.reference(name: "kick", DSLSpan.point(0)),
resources: resources
)
guard case .buffer(let resolved) = value else {
Issue.record("expected the reference to resolve to a buffer"); return
}
#expect(resolved === buffer)
}
@Test func bufferParameterIsExposedOnBufferBuiltins() throws {
// The code-gen emits buffer generators with a `buffer` parameter.
let playBuffer: DSLBuiltin = try DSLBuiltinRegistry.lookup("PlayBuffer")
#expect(playBuffer.parameters.contains { $0.label == "buffer" && !$0.hasDefault })
}
@Test func unknownReferenceThrows() {
#expect(throws: DSLBuildError.unknownReference("missing")) {
_ = try DSLInterpreter.evaluate(
"PlayBuffer(buffer: missing, rate: 1)",
resources: DSLBufferTable([:])
)
}
}
@Test func signalWhereBufferExpectedThrows() {
let resources: DSLBufferTable = DSLBufferTable(["kick": makeBuffer()])
// Handing a signal (a number) to the buffer parameter must fail.
#expect(throws: DSLBuildError.expectedBuffer(builtin: "PlayBuffer", label: "buffer")) {
_ = try DSLInterpreter.evaluate("PlayBuffer(buffer: 440, rate: 1)", resources: resources)
}
}
@Test func bufferUsedAsSignalThrows() {
let resources: DSLBufferTable = DSLBufferTable(["kick": makeBuffer()])
// A buffer can't be multiplied or played on its own.
#expect(throws: DSLBuildError.operatorRequiresSignal) {
_ = try DSLInterpreter.evaluate("kick * 0.5", resources: resources)
}
}
@Test func topLevelBareBufferCannotBePlayed() {
let resources: DSLBufferTable = DSLBufferTable(["kick": makeBuffer()])
#expect(throws: DSLBuildError.cannotPlayResource) {
_ = try DSLInterpreter.evaluate("kick", resources: resources)
}
}
@Test func bufferInSignalSlotThrowsExpectedSignal() {
let resources: DSLBufferTable = DSLBufferTable(["kick": makeBuffer()])
// OscSin.freq is a signal parameter; a buffer there is the wrong kind.
#expect(throws: DSLBuildError.expectedSignal(builtin: "OscSin", label: "freq")) {
_ = try DSLInterpreter.evaluate("OscSin(freq: kick)", resources: resources)
}
}
@Test func forgottenCallParensHintsItIsAGenerator() {
// A bare generator name (no parens) is a reference the resolver can't
// find — but it is a known generator, so hint that.
#expect(throws: DSLBuildError.referenceIsGenerator("OscSin")) {
_ = try DSLInterpreter.evaluate("OscSin")
}
}
}
@@ -0,0 +1,33 @@
// DSLTestSupport.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdGraphDSL
/// Shared offline engine for DSL round-trip tests.
@MainActor
func makeDSLTestEngine() -> SynthesisEngine {
SynthesisEngine(
blockSize: 16,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
}
/// `true` when any sample in bus `bus` of `engine` is non-zero.
@MainActor
func busHasSignal(_ engine: SynthesisEngine, bus: Int) -> Bool {
(0..<engine.blockSize).contains { engine.audioBuses[bus][$0] != 0.0 }
}
/// Wrap a signal value as a `DSLValue` for direct `DSLBuiltin.make` calls.
func sig(_ value: any ValidGeneratorInput) -> DSLValue { .signal(value) }
@@ -0,0 +1,176 @@
// GeneratedRegistryTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import LyrebirdSynth
import LyrebirdGraphDSL
@MainActor
@Suite("GeneratedDSLRegistry")
struct GeneratedRegistryTests {
/// Floor on the generated table size — a regression that halved the registry
/// (e.g. a scanner change) would trip this rather than pass silently.
private static let minimumBuiltinCount: Int = 150
@Test func registryIsPopulatedAndUnique() {
#expect(DSLBuiltinRegistry.all.count >= GeneratedRegistryTests.minimumBuiltinCount)
// Each (name, rate) is unique — no entry collapsed in the lookup table.
let totalEntries: Int = DSLBuiltinRegistry.byName.values.reduce(0) { $0 + $1.count }
#expect(totalEntries == DSLBuiltinRegistry.all.count)
}
@Test func generatorsAvailableAtBothRates() throws {
// OscSin exists at audio and control; lookup defaults to audio.
#expect(DSLBuiltinRegistry.rates(of: "OscSin") == Set([.audio, .control]))
let audio: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
#expect(audio.rate == .audio)
let control: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin", rate: .control)
#expect(control.rate == .control)
}
/// A doubly-nested control-only type (`Mouse.X.Control`) is registered under
/// its joined path name (`MouseX`), not the bare inner enum (`X`), and
/// constructs via the full `Mouse.X.Control` path.
@Test func doublyNestedTypeUsesJoinedNameAndFullConstructor() throws {
#expect(DSLBuiltinRegistry.rates(of: "MouseX") == Set([.control]))
// The bare inner name must NOT leak into the flat DSL namespace.
#expect(DSLBuiltinRegistry.rates(of: "X").isEmpty)
let mouseX: DSLBuiltin = try DSLBuiltinRegistry.lookup("MouseX", rate: .control)
#expect(mouseX.rate == .control)
// Constructs without throwing (no args; reads the mouse input registry).
_ = try mouseX.make([:])
}
@Test func unavailableRateThrows() throws {
// Pan2 is audio-only (no ControlGenerator variant).
#expect(DSLBuiltinRegistry.rates(of: "Pan2") == Set([.audio]))
#expect(throws: DSLBuildError.rateUnavailable(builtin: "Pan2", rate: "control")) {
_ = try DSLBuiltinRegistry.lookup("Pan2", rate: .control)
}
}
@Test func controlRateBuiltinRenders() throws {
// A control-rate OscSin drives an audio OscSin's frequency — the kind of
// modulation nesting the DSL will produce.
let lfoControl: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin", rate: .control)
let audio: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
let lfo: any ValidGeneratorInput = try lfoControl.make(["freq": sig(4.0), "mul": sig(50.0), "add": sig(440.0)])
let graph: any ValidGeneratorInput = try audio.make(["freq": sig(lfo), "mul": sig(0.1)])
let engine: SynthesisEngine = makeDSLTestEngine()
try engine.start()
try engine.add(ClosureSynthesizer { graph })
engine.processBlock(inputSamples: [])
#expect(busHasSignal(engine, bus: 0))
}
@Test func wellKnownGeneratorsArePresent() throws {
for name: String in ["OscSin", "OscSawtooth", "OscSquare", "WhiteNoise", "Pan2"] {
let builtin: DSLBuiltin = try DSLBuiltinRegistry.lookup(name)
#expect(builtin.name == name)
}
}
@Test func lookupOfUnknownNameThrows() {
#expect(throws: DSLBuildError.unknownBuiltin("NotAGenerator")) {
_ = try DSLBuiltinRegistry.lookup("NotAGenerator")
}
}
@Test func requiredParameterIsReportedAndEnforced() throws {
// OscSin's `freq` has no default, so it is required.
let osc: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
let freq: DSLParameter? = osc.parameters.first { $0.label == "freq" }
#expect(freq?.hasDefault == false)
#expect(throws: DSLBuildError.missingArgument(builtin: "OscSin", label: "freq")) {
_ = try osc.make([:])
}
}
/// The generated closure builds a real generator that renders audio.
@Test func generatedBuiltinRendersAudio() throws {
let osc: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
let graph: any ValidGeneratorInput = try osc.make(["freq": sig(440.0), "mul": sig(0.1)])
let engine: SynthesisEngine = makeDSLTestEngine()
try engine.start()
try engine.add(ClosureSynthesizer { graph })
engine.processBlock(inputSamples: [])
let anyNonZero: Bool = (0..<engine.blockSize).contains { engine.audioBuses[0][$0] != 0.0 }
#expect(anyNonZero)
}
/// A generator taking a signal input builds when handed another generator —
/// the nesting the DSL parser will produce.
@Test func nestedGeneratorArgumentBuilds() throws {
let osc: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
let pan: DSLBuiltin = try DSLBuiltinRegistry.lookup("Pan2")
let source: any ValidGeneratorInput = try osc.make(["freq": sig(440.0), "mul": sig(0.1)])
let graph: any ValidGeneratorInput = try pan.make(["input": sig(source), "pan": sig(0.0)])
let engine: SynthesisEngine = makeDSLTestEngine()
try engine.start()
try engine.add(ClosureSynthesizer { graph })
engine.processBlock(inputSamples: [])
// Pan2 is stereo — both buses should carry signal.
let leftNonZero: Bool = (0..<engine.blockSize).contains { engine.audioBuses[0][$0] != 0.0 }
let rightNonZero: Bool = (0..<engine.blockSize).contains { engine.audioBuses[1][$0] != 0.0 }
#expect(leftNonZero)
#expect(rightNonZero)
}
/// A parameter typed `Double` on the Swift init rejects a signal, since a
/// literal number is required there.
@Test func numericParameterRejectsSignal() throws {
let osc: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
let signal: any ValidGeneratorInput = try osc.make(["freq": sig(440.0)])
let delay: DSLBuiltin = try DSLBuiltinRegistry.lookup("DelayLine")
// `maxDelay` is a Double on the init — handing it a generator must throw.
#expect(throws: DSLBuildError.expectedNumber(builtin: "DelayLine", label: "maxDelay")) {
_ = try delay.make(["input": sig(signal), "maxDelay": sig(signal), "delay": sig(0.1)])
}
}
/// A generated builtin with a positional Swift argument (`Abs(_ signal:)`)
/// binds its unlabeled argument correctly through the emitted call.
@Test func positionalBuiltinBindsAndRenders() throws {
let osc: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
let abs: DSLBuiltin = try DSLBuiltinRegistry.lookup("Abs")
let source: any ValidGeneratorInput = try osc.make(["freq": sig(440.0), "mul": sig(0.5)])
let graph: any ValidGeneratorInput = try abs.make(["signal": sig(source)])
let engine: SynthesisEngine = makeDSLTestEngine()
try engine.start()
try engine.add(ClosureSynthesizer { graph })
engine.processBlock(inputSamples: [])
#expect(busHasSignal(engine, bus: 0))
}
/// A parameter whose Swift default is a named internal constant
/// (`LeakDC.coef = leakDCDefaultAudioCoef`) is exposed with a default and
/// builds when omitted — proves the code-gen's constant inlining works.
@Test func namedConstantDefaultIsUsable() throws {
let leak: DSLBuiltin = try DSLBuiltinRegistry.lookup("LeakDC")
let coef: DSLParameter? = leak.parameters.first { $0.label == "coef" }
#expect(coef?.hasDefault == true)
let osc: DSLBuiltin = try DSLBuiltinRegistry.lookup("OscSin")
let source: any ValidGeneratorInput = try osc.make(["freq": sig(440.0), "mul": sig(0.5)])
// `coef` omitted — must not throw a missing-argument error.
let graph: any ValidGeneratorInput = try leak.make(["input": sig(source)])
let engine: SynthesisEngine = makeDSLTestEngine()
try engine.start()
try engine.add(ClosureSynthesizer { graph })
engine.processBlock(inputSamples: [])
#expect(busHasSignal(engine, bus: 0))
}
/// Lock in which overload of a multi-init class the generator exposes.
/// `RBJBandPass` declares its `bandwidth:` init first, so that is the one
/// shipped; a future reorder that silently flipped it to `q:` trips here.
@Test func multiInitClassExposesFirstOverload() throws {
let bp: DSLBuiltin = try DSLBuiltinRegistry.lookup("RBJBandPass")
let labels: [String] = bp.parameters.map { $0.label }
#expect(labels.contains("bandwidth"))
#expect(!labels.contains("q"))
}
}
@@ -0,0 +1,75 @@
// ClosureSynthesizerTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable import LyrebirdSynth
/// Reference box so a closure can record how many times it ran.
private final class CallCounter {
var count: Int = 0
}
@MainActor
@Suite("ClosureSynthesizer")
struct ClosureSynthesizerTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
init() throws {
try engine.start()
}
@Test func closureGraphWritesToBusZero() throws {
let synth: ClosureSynthesizer = ClosureSynthesizer { 0.5 }
try engine.add(synth)
engine.processBlock(inputSamples: [])
for i: Int in 0..<engine.blockSize {
#expect(abs(engine.audioBuses[0][i] - 0.5) < 1e-6)
}
}
@Test func busParameterSelectsOutputBus() throws {
let synth: ClosureSynthesizer = ClosureSynthesizer(bus: 2) { 0.7 }
try engine.add(synth)
engine.processBlock(inputSamples: [])
#expect(abs(engine.audioBuses[2][0] - 0.7) < 1e-6)
#expect(engine.audioBuses[0][0] == 0.0)
}
@Test func closureRunsExactlyOncePerInstanceAtAdd() throws {
let counter: CallCounter = CallCounter()
let synth: ClosureSynthesizer = ClosureSynthesizer {
counter.count += 1
return 0.25
}
// build() — and thus the closure — runs synchronously inside add.
try engine.add(synth)
#expect(counter.count == 1)
engine.processBlock(inputSamples: [])
// Rendering does not re-run the closure.
#expect(counter.count == 1)
}
@Test func bareOscillatorGraphProducesAudio() throws {
let synth: ClosureSynthesizer = ClosureSynthesizer {
OscSin.Audio(freq: 440, mul: 0.1)
}
try engine.add(synth)
engine.processBlock(inputSamples: [])
let anyNonZero: Bool = (0..<engine.blockSize).contains { engine.audioBuses[0][$0] != 0.0 }
#expect(anyNonZero)
}
@Test func multiChannelSourceFansAcrossBuses() throws {
// A stereo Pan2 source writes bus 0 and bus 1.
let synth: ClosureSynthesizer = ClosureSynthesizer {
Pan2(input: 0.5, pan: 0)
}
try engine.add(synth)
engine.processBlock(inputSamples: [])
#expect(engine.audioBuses[0][0] != 0.0)
#expect(engine.audioBuses[1][0] != 0.0)
}
}
+104
View File
@@ -0,0 +1,104 @@
// DebugTapTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Synchronization
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// The debug tap's invocation is compiled out of release builds (`#if DEBUG` around the
// call site in `SynthesizerBase.evaluate`). These tests assert the tap fires, so they are
// meaningful only in a debug configuration — which is how `swift test` runs by default.
#if DEBUG
/// Records every `debugTap` invocation and the arguments it received.
///
/// Counters use `Atomic` because `debugTap` runs on the render thread; the offline driver
/// processes synchronously in-test, but atomics keep the fixture race-free regardless.
private final class DebugTapProbe: SynthesizerBase {
let bus: Int
let tapCount: Atomic<Int> = Atomic<Int>(0)
let lastOutputCount: Atomic<Int> = Atomic<Int>(-1)
let lastCount: Atomic<Int> = Atomic<Int>(-1)
init(bus: Int = 0) {
self.bus = bus
super.init()
}
override func build() {
// `output(bus:source:)` registers exactly once (Out.Audio self-registers via
// RootRegistering); an explicit `addOutputGenerator(Out.Audio(...))` would double-count.
output(bus: bus, source: 0.25)
}
override func debugTap(
graph: SynthGraph,
count: Int,
outputs: [any Generator]
) {
_ = tapCount.wrappingAdd(1, ordering: .relaxed)
lastOutputCount.store(outputs.count, ordering: .relaxed)
lastCount.store(count, ordering: .relaxed)
}
}
@MainActor
@Suite("SynthesizerBase debug tap")
struct DebugTapTests {
let engine: SynthesisEngine = makeTestEngine()
init() throws {
try engine.start()
}
@Test func tapDoesNotFireWhenDisabled() throws {
let probe: DebugTapProbe = DebugTapProbe()
try engine.add(probe)
engine.processBlock(inputSamples: [])
#expect(probe.tapCount.load(ordering: .relaxed) == 0)
}
@Test func tapFiresWhenEnabled() throws {
let probe: DebugTapProbe = DebugTapProbe()
probe.debugTapEnabled = true
try engine.add(probe)
engine.processBlock(inputSamples: [])
#expect(probe.tapCount.load(ordering: .relaxed) >= 1)
}
@Test func tapReceivesOutputsAndFullBlockCount() throws {
let probe: DebugTapProbe = DebugTapProbe()
probe.debugTapEnabled = true
try engine.add(probe)
engine.processBlock(inputSamples: [])
// One `Out.Audio` was registered in build().
#expect(probe.lastOutputCount.load(ordering: .relaxed) == 1)
// No scheduled events this block, so the segment spans the whole block.
#expect(probe.lastCount.load(ordering: .relaxed) == engine.blockSize)
}
@Test func gatingIsPerInstance() throws {
let on: DebugTapProbe = DebugTapProbe(bus: 0)
let off: DebugTapProbe = DebugTapProbe(bus: 1)
on.debugTapEnabled = true
try engine.add(on)
try engine.add(off)
engine.processBlock(inputSamples: [])
#expect(on.tapCount.load(ordering: .relaxed) >= 1)
#expect(off.tapCount.load(ordering: .relaxed) == 0)
}
@Test func flagRoundTripsThroughAtomicProperty() throws {
let probe: DebugTapProbe = DebugTapProbe()
#expect(probe.debugTapEnabled == false)
probe.debugTapEnabled = true
#expect(probe.debugTapEnabled == true)
probe.debugTapEnabled = false
#expect(probe.debugTapEnabled == false)
}
}
#endif
+18
View File
@@ -664,4 +664,22 @@ struct DiskInOutTests {
diskOut.close() // second call must not crash or deadlock
#expect(FileManager.default.fileExists(atPath: outURL.path))
}
/// A `DiskOut.Audio` whose output path is unwritable must throw from `init`
/// rather than construct a half-built recorder. This throw happens before
/// `super.init()`, so the ring storage is freed by an explicit
/// `deallocate()` on the throw path (Swift does not run `deinit` for an
/// initializer that throws before `super.init()`).
@Test func diskOutInvalidURLThrows() {
// A path under a directory that does not exist — ExtAudioFileCreateWithURL fails.
let badURL: URL = URL(fileURLWithPath: "/nonexistent-dir-\(UUID().uuidString)/out.wav")
#expect(throws: DiskOutError.self) {
_ = try DiskOut.Audio(source: 0.0 as Double,
channelCount: 2,
url: badURL,
sampleRate: 44100,
format: .wav,
bufferFrames: 8192)
}
}
}
@@ -76,8 +76,8 @@ struct AutoFreeOnDoneTests {
/// Drive engine.processBlock in tight bursts so engine-time runs many
/// multiples of wall-time. Same pattern as `LyrebirdEventListTests`.
private final class TestBlockDriver: @unchecked Sendable {
private var _thread: Thread?
private let _running: Atomic<Bool> = Atomic<Bool>(false)
private let _done: DispatchSemaphore = DispatchSemaphore(value: 0)
private let _engine: SynthesisEngine
private static let blocksPerBurst: Int = 32
private static let wallSleepSeconds: TimeInterval = 0.001
@@ -91,12 +91,17 @@ struct AutoFreeOnDoneTests {
}
Thread.sleep(forTimeInterval: Self.wallSleepSeconds)
}
self._done.signal()
}
thread.qualityOfService = .userInteractive
thread.start()
_thread = thread
}
func stop() { _running.store(false, ordering: .relaxed) }
/// Stop and **join** the pump thread so no `processBlock` runs after
/// `stop()` returns to race the engine's own `stop()`. Idempotent.
func stop() {
guard _running.exchange(false, ordering: .relaxed) else { return }
_done.wait()
}
}
// MARK: - Tests
@@ -46,8 +46,8 @@ private func sustainedEnvelope() -> Envelope {
/// Drives `engine.processBlock` in bursts so engine-time advances faster than wall-time.
private final class TestBlockDriver: @unchecked Sendable {
private var _thread: Thread?
private let _running: Atomic<Bool> = Atomic<Bool>(false)
private let _done: DispatchSemaphore = DispatchSemaphore(value: 0)
private let _engine: SynthesisEngine
// 32 × 64 samples @ 44.1 kHz ≈ 46 ms audio per 1 ms wall sleep → ~46× realtime.
// Headroom absorbs scheduler jitter so wall-clock test timeouts don't expire
@@ -66,13 +66,20 @@ private final class TestBlockDriver: @unchecked Sendable {
}
Thread.sleep(forTimeInterval: Self.wallSleepSeconds)
}
self._done.signal()
}
thread.qualityOfService = .userInteractive
thread.start()
_thread = thread
}
func stop() { _running.store(false, ordering: .relaxed) }
/// Stop and **join** the pump thread: blocks until the loop has finished its
/// in-flight block and exited, so no `processBlock` can run after `stop()`
/// returns to race the engine's own `stop()`. Idempotent and safe if never
/// started (the `true → false` transition is the one that joins).
func stop() {
guard _running.exchange(false, ordering: .relaxed) else { return }
_done.wait()
}
}
/// Thread-safe one-shot fulfillment token.
@@ -76,8 +76,8 @@ private func makeSimpleEventList(
/// Drives `engine.processBlock` in bursts so engine-time advances faster than wall-time.
private final class TestBlockDriver: @unchecked Sendable {
private var _thread: Thread?
private let _running: Atomic<Bool> = Atomic<Bool>(false)
private let _done: DispatchSemaphore = DispatchSemaphore(value: 0)
private let _engine: SynthesisEngine
// 32 × 64 samples @ 44.1 kHz ≈ 46 ms audio per 1 ms wall sleep → ~46× realtime.
// Headroom absorbs scheduler jitter so wall-clock test timeouts don't expire
@@ -96,13 +96,20 @@ private final class TestBlockDriver: @unchecked Sendable {
}
Thread.sleep(forTimeInterval: Self.wallSleepSeconds)
}
self._done.signal()
}
thread.qualityOfService = .userInteractive
thread.start()
_thread = thread
}
func stop() { _running.store(false, ordering: .relaxed) }
/// Stop and **join** the pump thread: blocks until the loop has finished its
/// in-flight block and exited, so no `processBlock` can run after `stop()`
/// returns to race the engine's own `stop()`. Idempotent and safe if never
/// started (the `true → false` transition is the one that joins).
func stop() {
guard _running.exchange(false, ordering: .relaxed) else { return }
_done.wait()
}
}
// MARK: - Helpers
@@ -7,6 +7,7 @@
import Testing
import Foundation
import AudioToolbox
import Synchronization
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Private test fixtures
@@ -35,25 +36,34 @@ private func shortAutoEnvelope() -> Envelope {
/// Drives `engine.processBlock` at ~1 ms intervals while `_running` is true.
private final class TimelineTestBlockDriver: @unchecked Sendable {
private var _running: Bool = false
private let _running: Atomic<Bool> = Atomic<Bool>(false)
private let _done: DispatchSemaphore = DispatchSemaphore(value: 0)
private let _engine: SynthesisEngine
private static let blockIntervalSeconds: Double = 0.001
init(engine: SynthesisEngine) { _engine = engine }
func start() {
_running = true
_running.store(true, ordering: .relaxed)
let t: Thread = Thread { [self] in
while self._running {
while self._running.load(ordering: .relaxed) {
self._engine.processBlock(inputSamples: [])
Thread.sleep(forTimeInterval: TimelineTestBlockDriver.blockIntervalSeconds)
}
self._done.signal()
}
t.qualityOfService = .userInteractive
t.start()
}
func stop() { _running = false }
/// Stop and **join** the pump thread: blocks until the loop has finished its
/// in-flight block and exited, so no `processBlock` can run after `stop()`
/// returns to race the engine's own `stop()`. Idempotent and safe if never
/// started (the `true → false` transition is the one that joins).
func stop() {
guard _running.exchange(false, ordering: .relaxed) else { return }
_done.wait()
}
}
/// Returns a temporary directory. Caller is responsible for cleanup.
@@ -64,8 +64,8 @@ private func makeProcessTestEngine() -> SynthesisEngine {
/// The `OfflineDriver` does not generate its own render callbacks, so tests that
/// rely on envelope completion must drive the engine themselves.
private final class TestBlockDriver: @unchecked Sendable {
private var _thread: Thread?
private let _running: Atomic<Bool> = Atomic<Bool>(false)
private let _done: DispatchSemaphore = DispatchSemaphore(value: 0)
private let _engine: SynthesisEngine
// 32 × 64 samples @ 44.1 kHz ≈ 46 ms audio per 1 ms wall sleep → ~46× realtime.
// Headroom absorbs scheduler jitter so wall-clock test timeouts don't expire
@@ -86,14 +86,19 @@ private final class TestBlockDriver: @unchecked Sendable {
}
Thread.sleep(forTimeInterval: Self.wallSleepSeconds)
}
self._done.signal()
}
thread.qualityOfService = .userInteractive
thread.start()
_thread = thread
}
/// Stop and **join** the pump thread: blocks until the loop has finished its
/// in-flight block and exited, so no `processBlock` can run after `stop()`
/// returns to race the engine's own `stop()`. Idempotent and safe if never
/// started (the `true → false` transition is the one that joins).
func stop() {
_running.store(false, ordering: .relaxed)
guard _running.exchange(false, ordering: .relaxed) else { return }
_done.wait()
}
}
+207
View File
@@ -0,0 +1,207 @@
// SampleLoopTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SampleLoop")
struct SampleLoopTests {
/// y[n] = x[n] + a·y[n-1] with a constant input converges to x/(1-a).
@Test func singlePoleFeedbackConverges() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
try engine.start()
let a: Double = 0.5
let node: SampleLoop<[Double]> = SampleLoop(
makeState: { n in [Double](repeating: 0.0, count: n) },
inputs: [1.0]
) { z, ins, numChannels, out, n, _ in
for i: Int in 0..<n {
for ch: Int in 0..<numChannels {
let y: Double = ins[0][ch][i] + a * z[ch]
z[ch] = y
out[ch][i] = y
}
}
}
let block: [Double] = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 8)[0]
#expect(abs(block[0] - 1.0) < 1e-12) // 1 + 0.5·0
#expect(abs(block[1] - 1.5) < 1e-12) // 1 + 0.5·1
#expect(abs(block[2] - 1.75) < 1e-12) // 1 + 0.5·1.5
#expect(block[7] > 1.98 && block[7] < 2.0) // → 2.0
}
/// Feedback state carries across block boundaries.
@Test func statePersistsAcrossBlocks() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 4)
try engine.start()
let node: SampleLoop<[Double]> = SampleLoop(
makeState: { n in [Double](repeating: 0.0, count: n) },
inputs: [1.0]
) { z, ins, numChannels, out, n, _ in
for i: Int in 0..<n {
for ch: Int in 0..<numChannels {
let y: Double = ins[0][ch][i] + 0.5 * z[ch]
z[ch] = y
out[ch][i] = y
}
}
}
let block1: [Double] = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)[0]
advanceBlock(engine)
let block2: [Double] = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)[0]
#expect(abs(block2[0] - (1.0 + 0.5 * block1[3])) < 1e-12)
#expect(abs(node.state[0] - block2[3]) < 1e-12)
}
/// Output channel count is inferred from the widest input, and a mono input broadcasts
/// to every output channel.
@Test func infersChannelsAndBroadcastsMonoInput() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 4)
try engine.start()
let stereoIn: Pan2 = Pan2(input: 1.0, pan: 0.0) // 2-row generator
let node: SampleLoop<Int> = SampleLoop(
makeState: { _ in 0 },
inputs: [stereoIn, 3.0] // stereo + mono scalar
) { _, ins, numChannels, out, n, _ in
for i: Int in 0..<n {
for ch: Int in 0..<numChannels {
out[ch][i] = ins[0][ch][i] + ins[1][ch][i] // mono input 1 broadcast to both
}
}
}
#expect(node.outputChannelCount == 2)
let result: [[Double]] = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)
#expect(result.count == 2)
// Pan2 at pan 0 → equal-power ≈ 0.707 per channel; + 3.0 broadcast mono.
#expect(abs(result[0][0] - (result[1][0])) < 1e-9) // symmetric channels
#expect(result[0][0] > 3.0 && result[0][0] < 4.0)
}
/// An explicit `channels:` up-mixes a pure source with no inputs to infer from.
@Test func explicitChannelsForPureSource() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 4)
try engine.start()
let node: SampleLoop<Int> = SampleLoop(
makeState: { _ in 0 },
inputs: [],
channels: 3
) { _, _, numChannels, out, n, _ in
for ch: Int in 0..<numChannels {
for i: Int in 0..<n { out[ch][i] = Double(ch) }
}
}
#expect(node.outputChannelCount == 3)
let result: [[Double]] = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)
#expect(result.count == 3)
#expect(result[0][0] == 0.0 && result[1][0] == 1.0 && result[2][0] == 2.0)
}
/// Two instances keep independent state (graph-copy-per-instance model).
@Test func instancesAreIndependent() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 4)
try engine.start()
func makeCounter() -> SampleLoop<[Double]> {
SampleLoop(makeState: { n in [Double](repeating: 0.0, count: n) }, inputs: []) { s, _, _, out, n, _ in
for i: Int in 0..<n {
s[0] += 1.0
out[0][i] = s[0]
}
}
}
let a: SampleLoop<[Double]> = makeCounter()
let b: SampleLoop<[Double]> = makeCounter()
_ = a.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)
advanceBlock(engine)
_ = a.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4) // a advanced twice
_ = b.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4) // b advanced once
#expect(abs(a.state[0] - 8.0) < 1e-12)
#expect(abs(b.state[0] - 4.0) < 1e-12)
}
/// `mul` / `add` scale the body's output after the fact.
@Test func mulAddScalesOutput() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 4)
try engine.start()
let node: SampleLoop<Int> = SampleLoop(
makeState: { _ in 0 },
inputs: [3.0],
mul: 2.0,
add: 1.0
) { _, ins, numChannels, out, n, _ in
for i: Int in 0..<n {
for ch: Int in 0..<numChannels { out[ch][i] = ins[0][ch][i] } // 3.0
}
}
let block: [Double] = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)[0]
#expect(Array(block.prefix(4)) == [7.0, 7.0, 7.0, 7.0]) // 3·2 + 1
}
/// Regression: a `Generator` input's own `_result` buffer must not be copied-on-write
/// across blocks. Aliasing the input row in a stored property (instead of copying into
/// private scratch) would leave the row referenced twice at the input's next in-place
/// write, reallocating its buffer — a per-block RT-thread allocation. A stable base
/// address across blocks proves no reallocation occurred.
@Test func generatorInputIsNotCopiedOnWriteAcrossBlocks() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
try engine.start()
let osc: OscSin.Audio = OscSin.Audio(freq: 100.0)
let node: SampleLoop<Int> = SampleLoop(makeState: { _ in 0 }, inputs: [osc]) { _, ins, nc, out, n, _ in
for i: Int in 0..<n {
for ch: Int in 0..<nc { out[ch][i] = ins[0][ch][i] }
}
}
func oscRowBase() -> UnsafeRawPointer? {
osc._result[0].withUnsafeBufferPointer { UnsafeRawPointer($0.baseAddress) }
}
_ = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 8)
let base1: UnsafeRawPointer? = oscRowBase()
advanceBlock(engine)
_ = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 8)
let base2: UnsafeRawPointer? = oscRowBase()
#expect(base1 != nil)
#expect(base1 == base2) // no CoW reallocation of the input's buffer
}
/// Regression: the private input scratch and the output buffer are never reallocated
/// across blocks (both pre-allocated at init).
@Test func scratchAndOutputBuffersStableAcrossBlocks() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
try engine.start()
let node: SampleLoop<Int> = SampleLoop(makeState: { _ in 0 }, inputs: [0.5]) { _, ins, nc, out, n, _ in
for i: Int in 0..<n {
for ch: Int in 0..<nc { out[ch][i] = ins[0][ch][i] }
}
}
func outBase() -> UnsafeRawPointer? {
node._result[0].withUnsafeBufferPointer { UnsafeRawPointer($0.baseAddress) }
}
_ = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 8)
let base1: UnsafeRawPointer? = outBase()
advanceBlock(engine)
_ = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 8)
let base2: UnsafeRawPointer? = outBase()
#expect(base1 != nil)
#expect(base1 == base2)
}
/// The output buffer is pre-zeroed: a body that writes only part of the block leaves
/// silence in the gaps, never stale data from the previous block.
@Test func outputPreZeroedBetweenBlocks() throws {
let engine: SynthesisEngine = makeTestEngine(blockSize: 4)
try engine.start()
let node: SampleLoop<Int> = SampleLoop(makeState: { _ in 0 }, inputs: []) { call, _, _, out, n, _ in
let writeCount: Int = (call == 0) ? n : 1
for i: Int in 0..<writeCount { out[0][i] = 9.0 }
call += 1
}
_ = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)
advanceBlock(engine)
let block2: [Double] = node.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 4)[0]
#expect(Array(block2.prefix(4)) == [9.0, 0.0, 0.0, 0.0])
}
}
+15
View File
@@ -0,0 +1,15 @@
{
"originHash" : "6af3e8d671d9174391c6e00ce7b43f22373b57aa528394f7ca9641ede96f515d",
"pins" : [
{
"identity" : "swift-syntax",
"kind" : "remoteSourceControl",
"location" : "https://github.com/swiftlang/swift-syntax",
"state" : {
"revision" : "79e4b74a295b6eb74a8b585e3a39d29e70c1dbd1",
"version" : "603.0.2"
}
}
],
"version" : 3
}
+40
View File
@@ -0,0 +1,40 @@
// swift-tools-version: 6.0
// Package.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Build-time code generator for the interpreted graph-DSL's builtin registry.
//
// Deliberately a SEPARATE package under `Tools/` rather than a target in the
// main package: it depends on swift-syntax, which is large and would otherwise
// be resolved and built on every `swift build` of Lyrebird itself. The shipped
// `LyrebirdGraphDSL` target has no such dependency — it only consumes the Swift
// file this tool emits.
//
// Run via `bash scripts/generate-dsl-registry.sh` (which shells
// `swift run --package-path Tools/DSLRegistryGen`).
import PackageDescription
let package = Package(
name: "DSLRegistryGen",
platforms: [.macOS(.v13)],
dependencies: [
.package(
url: "https://github.com/swiftlang/swift-syntax",
"600.0.0"..<"700.0.0"
),
],
targets: [
.executableTarget(
name: "DSLRegistryGen",
dependencies: [
.product(name: "SwiftSyntax", package: "swift-syntax"),
.product(name: "SwiftParser", package: "swift-syntax"),
],
path: "Sources/DSLRegistryGen"
),
]
)
@@ -0,0 +1,571 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Scans the Lyrebird generator sources and emits the interpreted graph-DSL's
// builtin registry (a `[DSLBuiltin]` table) as Swift source.
//
// Usage:
// DSLRegistryGen --generators <dir> [--constants <dir>] --output <file>
// DSLRegistryGen --generators <dir> [--constants <dir>] --report
// DSLRegistryGen --generators <dir> [--constants <dir>] --output <file> --check
//
// `--report` prints a classification summary; `--check` regenerates in memory
// and exits non-zero if it differs from the committed `--output` file (drift
// guard). Exactly one of `--output` / `--report` is required.
import Foundation
import SwiftParser
import SwiftSyntax
// MARK: - Model
/// A generator init parameter as written in source.
struct ScannedParameter {
let label: String
let typeText: String
let defaultText: String?
/// `true` when the Swift init declares the parameter positionally (`_ value:`).
let isPositional: Bool
/// Type text with optionality + whitespace normalised away.
var normalizedType: String {
var t: String = typeText.trimmingCharacters(in: .whitespaces)
if t.hasSuffix("?") { t.removeLast() }
return t.trimmingCharacters(in: .whitespaces)
}
/// How the DSL supplies this parameter: a signal/number/buffer, or nothing
/// (an enum, URL, bus, closure, array — not expressible in the DSL).
var kind: String {
switch normalizedType {
case "any ValidGeneratorInput": return "signal"
case "Double": return "double"
case "Int": return "int"
case "Float": return "float"
case "LyrebirdBuffer":
// A buffer with a non-nil Swift default can't be expressed (the DSL
// can only omit → nil, or supply a named buffer), so reject rather
// than silently override the default with nil.
if let d: String = defaultText, d.trimmingCharacters(in: .whitespaces) != "nil" {
return "unsupported"
}
return "buffer"
default: return "unsupported"
}
}
var isDSLExpressible: Bool { kind != "unsupported" }
/// `true` for an optional buffer (`LyrebirdBuffer?`), which the DSL may omit.
var isOptionalBuffer: Bool {
kind == "buffer" && typeText.trimmingCharacters(in: .whitespaces).hasSuffix("?")
}
var hasDefault: Bool { defaultText != nil }
}
/// A generator the scanner found, with the init it would be constructed from.
struct ScannedGenerator {
/// DSL name (`OscSin`, `Pan2`).
let name: String
/// `"audio"` or `"control"`.
let rate: String
/// Swift expression that constructs it (`OscSin.Audio`, `Pan2`).
let constructor: String
let parameters: [ScannedParameter]
let sourceFile: String
/// `true` when the class declared more than one usable init — only the first
/// was taken, so a human should confirm the right overload ships.
let hadMultipleInits: Bool
/// Constructible from the DSL only if every parameter is either
/// DSL-expressible or has a default we can omit.
var isConstructible: Bool {
parameters.allSatisfy { $0.isDSLExpressible || $0.hasDefault }
}
/// Parameters the DSL actually exposes.
var exposedParameters: [ScannedParameter] {
parameters.filter { $0.isDSLExpressible }
}
var rejectionReason: String? {
guard !isConstructible else { return nil }
let blocking: [String] = parameters
.filter { !$0.isDSLExpressible && !$0.hasDefault }
.map { "\($0.label): \($0.typeText)" }
return "required non-expressible parameter(s): " + blocking.joined(separator: ", ")
}
}
/// Internal plumbing `Generator` types that conform to `AudioGenerator` but are
/// not musical builtins a DSL author would reach for — excluded from the table.
let excludedGeneratorNames: Set<String> = [
"ConstantGeneratorInput",
]
// MARK: - Constant scanning (top-level, SwiftSyntax)
/// Collects module-level numeric constants (name → literal text): file-scope
/// `let`s and type-member `static let`s. Function-local bindings are ignored, so
/// a local `let minFreq = 1.0` cannot shadow a module constant.
final class ConstantScanner: SyntaxVisitor {
private(set) var constants: [(name: String, value: String)] = []
/// Nesting inside a function / init / closure body — locals here are ignored.
private var funcDepth: Int = 0
/// Nesting inside a type (class/struct/enum/extension) — a member here counts
/// only when `static`.
private var typeDepth: Int = 0
override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind { funcDepth += 1; return .visitChildren }
override func visitPost(_ node: FunctionDeclSyntax) { funcDepth -= 1 }
override func visit(_ node: InitializerDeclSyntax) -> SyntaxVisitorContinueKind { funcDepth += 1; return .visitChildren }
override func visitPost(_ node: InitializerDeclSyntax) { funcDepth -= 1 }
override func visit(_ node: ClosureExprSyntax) -> SyntaxVisitorContinueKind { funcDepth += 1; return .visitChildren }
override func visitPost(_ node: ClosureExprSyntax) { funcDepth -= 1 }
override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind { typeDepth += 1; return .visitChildren }
override func visitPost(_ node: ClassDeclSyntax) { typeDepth -= 1 }
override func visit(_ node: StructDeclSyntax) -> SyntaxVisitorContinueKind { typeDepth += 1; return .visitChildren }
override func visitPost(_ node: StructDeclSyntax) { typeDepth -= 1 }
override func visit(_ node: EnumDeclSyntax) -> SyntaxVisitorContinueKind { typeDepth += 1; return .visitChildren }
override func visitPost(_ node: EnumDeclSyntax) { typeDepth -= 1 }
override func visit(_ node: ExtensionDeclSyntax) -> SyntaxVisitorContinueKind { typeDepth += 1; return .visitChildren }
override func visitPost(_ node: ExtensionDeclSyntax) { typeDepth -= 1 }
override func visit(_ node: VariableDeclSyntax) -> SyntaxVisitorContinueKind {
// Never a function-local. In a type, only `static` members qualify.
guard funcDepth == 0 else { return .skipChildren }
let isStatic: Bool = node.modifiers.contains { $0.name.text == "static" }
guard typeDepth == 0 || isStatic else { return .skipChildren }
for binding: PatternBindingSyntax in node.bindings {
// `trimmedDescription` drops leading/trailing trivia, so a trailing
// `// comment` after the literal doesn't defeat the literal check.
guard let name: String = node.identifierName(binding),
let typeText: String = binding.typeAnnotation?.type.trimmedDescription,
typeText == "Double" || typeText == "Int" || typeText == "Float",
let value: String = binding.initializer?.value.trimmedDescription,
isNumericLiteral(value) else { continue }
constants.append((name, value))
}
return .skipChildren
}
private func isNumericLiteral(_ s: String) -> Bool {
s.range(of: #"^-?[0-9][0-9_]*(\.[0-9_]+)?([eE][-+]?[0-9]+)?$"#,
options: .regularExpression) != nil
}
}
extension VariableDeclSyntax {
func identifierName(_ binding: PatternBindingSyntax) -> String? {
binding.pattern.as(IdentifierPatternSyntax.self)?.identifier.text
}
}
/// Scan every file for file-scope numeric constants. Same name with different
/// values across files is a genuine ambiguity — recorded in `collisions` and
/// dropped from the table rather than silently overwritten.
func scanNumericConstants(files: [URL]) -> (table: [String: String], collisions: [String]) {
var table: [String: String] = [:]
var collisions: Set<String> = Set<String>()
for file: URL in files {
guard let text: String = try? String(contentsOf: file, encoding: .utf8) else { continue }
let tree: SourceFileSyntax = Parser.parse(source: text)
let scanner: ConstantScanner = ConstantScanner(viewMode: .sourceAccurate)
scanner.walk(tree)
for c: (name: String, value: String) in scanner.constants {
if let existing: String = table[c.name], existing != c.value {
collisions.insert(c.name)
} else {
table[c.name] = c.value
}
}
}
for name: String in collisions { table.removeValue(forKey: name) }
return (table, collisions.sorted())
}
// MARK: - Generator scanning
/// Collects generator declarations from one parsed file. Handles both shapes:
/// 1. `public enum Osc… { public final class Audio: … }` → `Osc….Audio`
/// 2. `public final class Pan2: GeneratorBase, AudioGenerator` → `Pan2`
final class GeneratorScanner: SyntaxVisitor {
private(set) var found: [ScannedGenerator] = []
private(set) var noDeclaredInit: [String] = []
/// Classes conforming to both generator protocols on one declaration — none
/// today, but flagged so a future one surfaces rather than being silently
/// classified audio-only.
private(set) var bothRateClasses: [String] = []
private let fileName: String
private var enumStack: [String] = []
init(fileName: String) {
self.fileName = fileName
super.init(viewMode: .sourceAccurate)
}
override func visit(_ node: EnumDeclSyntax) -> SyntaxVisitorContinueKind {
enumStack.append(node.name.text.trimmingCharacters(in: .whitespaces))
return .visitChildren
}
override func visitPost(_ node: EnumDeclSyntax) {
if !enumStack.isEmpty { enumStack.removeLast() }
}
override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind {
let className: String = node.name.text.trimmingCharacters(in: .whitespaces)
let isAudio: Bool = conforms(node, to: "AudioGenerator")
let isControl: Bool = conforms(node, to: "ControlGenerator")
if isAudio, isControl { bothRateClasses.append(className) }
let rate: String
if isAudio {
rate = "audio"
} else if isControl {
rate = "control"
} else {
return .visitChildren
}
let dslName: String
let constructor: String
if (className == "Audio" || className == "Control"), !enumStack.isEmpty {
// DSL name is the enclosing enum path joined (Mouse.X → "MouseX"),
// which for the common single-level case is just the owner (OscSin).
// Constructor is the full nesting path so a doubly-nested type
// (Mouse.X.Control) constructs correctly.
dslName = enumStack.joined()
constructor = (enumStack + [className]).joined(separator: ".")
} else if enumStack.isEmpty, !className.hasPrefix("_") {
dslName = className
constructor = className
} else {
return .visitChildren
}
guard !excludedGeneratorNames.contains(dslName) else { return .visitChildren }
let usableInits: [InitializerDeclSyntax] = designatedInits(in: node)
guard let initDecl: InitializerDeclSyntax = usableInits.first else {
noDeclaredInit.append("\(dslName) (\(fileName))")
return .visitChildren
}
let params: [ScannedParameter] = initDecl.signature.parameterClause.parameters.map { p in
let label: String = (p.firstName.text == "_"
? (p.secondName?.text ?? p.firstName.text)
: p.firstName.text)
.trimmingCharacters(in: .whitespaces)
return ScannedParameter(
label: label,
typeText: p.type.description.trimmingCharacters(in: .whitespacesAndNewlines),
defaultText: p.defaultValue?.value.description
.trimmingCharacters(in: .whitespacesAndNewlines),
isPositional: p.firstName.text == "_"
)
}
found.append(ScannedGenerator(
name: dslName,
rate: rate,
constructor: constructor,
parameters: params,
sourceFile: fileName,
hadMultipleInits: usableInits.count > 1
))
return .visitChildren
}
private func conforms(_ node: ClassDeclSyntax, to proto: String) -> Bool {
guard let inheritance: InheritanceClauseSyntax = node.inheritanceClause else { return false }
return inheritance.inheritedTypes.contains { inherited in
inherited.type.description.trimmingCharacters(in: .whitespaces) == proto
}
}
/// The class's usable designated inits — `public`/`internal`, not
/// `convenience`, not `private`, not failable. (The DSL constructs via the
/// designated init; a convenience or failable overload would mislead.)
private func designatedInits(in node: ClassDeclSyntax) -> [InitializerDeclSyntax] {
node.memberBlock.members.compactMap { member in
guard let initDecl: InitializerDeclSyntax = member.decl.as(InitializerDeclSyntax.self)
else { return nil }
if initDecl.optionalMark != nil { return nil } // failable
let modifiers: [String] = initDecl.modifiers.map { $0.name.text }
if modifiers.contains("convenience") || modifiers.contains("private") { return nil }
return initDecl
}
}
}
// MARK: - Driver: arguments + scanning
func parseArgument(_ name: String) -> String? {
let args: [String] = CommandLine.arguments
guard let i: Int = args.firstIndex(of: name), i + 1 < args.count else { return nil }
let value: String = args[i + 1]
// A following flag is not this flag's value.
return value.hasPrefix("--") ? nil : value
}
func fail(_ message: String) -> Never {
FileHandle.standardError.write(Data("DSLRegistryGen: \(message)\n".utf8))
exit(2)
}
func swiftFiles(under root: URL) -> [URL] {
guard let e: FileManager.DirectoryEnumerator = FileManager.default.enumerator(
at: root, includingPropertiesForKeys: nil
) else { return [] }
var out: [URL] = []
for case let url as URL in e where url.pathExtension == "swift" {
out.append(url)
}
return out.sorted { $0.path < $1.path }
}
guard let generatorsPath: String = parseArgument("--generators") else {
fail("usage: --generators <dir> [--constants <dir>] (--output <file> [--check] | --report)")
}
let wantReport: Bool = CommandLine.arguments.contains("--report")
let outputPath: String? = parseArgument("--output")
let wantCheck: Bool = CommandLine.arguments.contains("--check")
guard wantReport || outputPath != nil else {
fail("no mode given — pass --output <file> or --report")
}
let generatorFiles: [URL] = swiftFiles(under: URL(fileURLWithPath: generatorsPath))
let constantsPath: String = parseArgument("--constants") ?? generatorsPath
let constantFiles: [URL] = constantsPath == generatorsPath
? generatorFiles
: swiftFiles(under: URL(fileURLWithPath: constantsPath))
let (constants, constantCollisions): ([String: String], [String]) = scanNumericConstants(files: constantFiles)
var all: [ScannedGenerator] = []
var missingInit: [String] = []
var bothRateClasses: [String] = []
for file: URL in generatorFiles {
guard let text: String = try? String(contentsOf: file, encoding: .utf8) else { continue }
let tree: SourceFileSyntax = Parser.parse(source: text)
let scanner: GeneratorScanner = GeneratorScanner(fileName: file.lastPathComponent)
scanner.walk(tree)
all.append(contentsOf: scanner.found)
missingInit.append(contentsOf: scanner.noDeclaredInit)
bothRateClasses.append(contentsOf: scanner.bothRateClasses)
}
let constructible: [ScannedGenerator] = all.filter { $0.isConstructible }
let rejected: [ScannedGenerator] = all.filter { !$0.isConstructible }
// MARK: - Emitter
/// Default expressions the emitter could not reduce to a literal (so the
/// parameter became required in the DSL instead of defaulted). Single-threaded
/// tool; the isolation opt-out is safe.
nonisolated(unsafe) var unresolvedDefaults: Set<String> = Set<String>()
/// A default's text reduced to something the generated module can compile:
/// a literal as-is, a known file-scope numeric constant inlined, otherwise `nil`.
func resolvedDefault(_ text: String) -> String? {
let t: String = text.trimmingCharacters(in: .whitespaces)
if t.range(of: #"^-?[0-9][0-9_]*(\.[0-9_]+)?([eE][-+]?[0-9]+)?$"#,
options: .regularExpression) != nil {
return t
}
if let literal: String = constants[t] { return literal }
unresolvedDefaults.insert(t)
return nil
}
func effectiveHasDefault(_ p: ScannedParameter) -> Bool {
// An optional buffer is omittable even though its `nil` default isn't a
// numeric literal we inline.
if p.isOptionalBuffer { return true }
return p.defaultText.flatMap { resolvedDefault($0) } != nil
}
/// Reject a generator whose emitted call would drop a positional argument out
/// from under a later positional one (a defaulted non-expressible positional
/// param followed by an exposed positional). None exist in-tree today; this
/// guards against a future addition silently mis-binding.
func hasUnsafePositionalDrop(_ g: ScannedGenerator) -> Bool {
var droppedPositional: Bool = false
for p: ScannedParameter in g.parameters {
let exposed: Bool = p.isDSLExpressible
if !exposed {
if p.isPositional { droppedPositional = true }
} else if p.isPositional, droppedPositional {
return true
}
}
return false
}
func argumentExpression(_ p: ScannedParameter, builtin: String) -> String {
let key: String = "args[\"\(p.label)\"]"
let where_: String = "\"\(builtin)\", \"\(p.label)\""
// Buffers are resources. An optional buffer (`LyrebirdBuffer?`) may be
// omitted (Swift init default applies); a required one must be supplied.
if p.kind == "buffer" {
let fn: String = p.isOptionalBuffer ? "optionalBuffer" : "buffer"
return "try DSLArgument.\(fn)(\(key), \(where_))"
}
// Signal / number: pass the DSLValue through the coercion, supplying the
// Swift init's default (as a `.signal`) for an optional parameter.
let helper: String = (p.kind == "signal") ? "input" : p.kind
let def: String? = p.defaultText.flatMap { resolvedDefault($0) }
let source: String = def.map { "\(key) ?? .signal(\($0))" } ?? key
return "try DSLArgument.\(helper)(\(source), \(where_))"
}
func emitRegistry(_ generators: [ScannedGenerator]) -> String {
var out: String = """
// GeneratedDSLRegistry.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// GENERATED FILE — do not edit by hand.
// Produced by Tools/DSLRegistryGen from the generator sources.
// Regenerate with: bash scripts/generate-dsl-registry.sh
import LyrebirdSynth
extension DSLBuiltinRegistry {
/// Every generator the DSL can construct, emitted from the generator
/// sources. A generator appears here when all of its init parameters are
/// either DSL-expressible (a signal/number) or have a Swift default that
/// can be omitted.
static let generated: [DSLBuiltin] = [\n
"""
for g: ScannedGenerator in generators {
let exposed: [ScannedParameter] = g.exposedParameters
let paramList: String = exposed
.map { " DSLParameter(label: \"\($0.label)\", hasDefault: \(effectiveHasDefault($0))),\n" }
.joined()
let callArgs: String = exposed
.map { p in
let expr: String = argumentExpression(p, builtin: g.name)
let prefix: String = p.isPositional ? "" : "\(p.label): "
return " \(prefix)\(expr)"
}
.joined(separator: ",\n")
// Empty-argument constructors emit `Foo()`; otherwise a multi-line call.
let makeBody: String = exposed.isEmpty
? " \(g.constructor)()"
: " \(g.constructor)(\n\(callArgs)\n )"
out += """
DSLBuiltin(
name: "\(g.name)",
rate: .\(g.rate),
parameters: [
\(paramList) ],
make: { args in
\(makeBody)
}
),\n
"""
}
out += """
]
}
"""
return out
}
// De-duplicate by (DSL name, rate) (report collisions), stable order.
var seen: Set<String> = Set<String>()
var nameCollisions: [String] = []
let unique: [ScannedGenerator] = constructible
.sorted { ($0.name, $0.rate) < ($1.name, $1.rate) }
.filter { g in
if seen.insert("\(g.name)|\(g.rate)").inserted { return true }
nameCollisions.append("\(g.name) (\(g.rate))")
return false
}
let unsafeDrops: [ScannedGenerator] = unique.filter { hasUnsafePositionalDrop($0) }
let emittable: [ScannedGenerator] = unique.filter { !hasUnsafePositionalDrop($0) }
let source: String = emitRegistry(emittable) // also populates unresolvedDefaults
// MARK: - Modes
if let outputPath: String = outputPath {
if wantCheck {
let existing: String = (try? String(contentsOf: URL(fileURLWithPath: outputPath), encoding: .utf8)) ?? ""
if existing != source {
fail("registry is stale — run scripts/generate-dsl-registry.sh and commit \(outputPath)")
}
print("OK: DSL registry is up to date (\(emittable.count) builtins).")
} else {
do {
try source.write(toFile: outputPath, atomically: true, encoding: .utf8)
print("emitted \(emittable.count) builtins → \(outputPath)")
} catch {
fail("write failed: \(error)")
}
}
}
// Surface everything the human should know, regardless of mode.
func warn(_ label: String, _ items: [String]) {
guard !items.isEmpty else { return }
FileHandle.standardError.write(Data("warning: \(label): \(items.joined(separator: ", "))\n".utf8))
}
warn("dropped for unsafe positional argument order", unsafeDrops.map { $0.name })
warn("DSL-name collisions (kept first)", nameCollisions)
warn("ambiguous multi-init classes (first init used)",
emittable.filter { $0.hadMultipleInits }.map { $0.name })
warn("constant-name collisions (default dropped, param made required)", constantCollisions)
warn("classes conforming to both generator protocols (classified audio)", bothRateClasses)
/// The resource category blocking a rejected generator, for the surface map
/// that informs how the language will name non-numeric resources.
func blockingResourceKind(_ g: ScannedGenerator) -> String {
let types: [String] = g.parameters
.filter { !$0.isDSLExpressible && !$0.hasDefault }
.map { $0.typeText }
func any(_ needle: String) -> Bool { types.contains { $0.contains(needle) } }
if any("LyrebirdBuffer") { return "buffer" }
if any("ValidBus") || any("AudioBus") || any("ControlBus") { return "bus" }
if any("URL") { return "url" }
if types.contains(where: { $0.contains("->") || $0.contains("@escaping") }) { return "closure" }
return "other (\(types.joined(separator: ", ")))"
}
if wantReport {
let audio: Int = emittable.filter { $0.rate == "audio" }.count
let control: Int = emittable.filter { $0.rate == "control" }.count
print("scanned generator files: \(generatorFiles.count)")
print("generator classes (A+C): \(all.count)")
print("DSL-constructible: \(constructible.count)")
print("emitted (unique): \(emittable.count) (audio \(audio), control \(control))")
print("rejected (non-expressible required param): \(rejected.count)")
print("no declared init: \(missingInit.count)")
print("multi-init (first used): \(emittable.filter { $0.hadMultipleInits }.count)")
print("file-scope constants: \(constants.count)")
print("unresolved default exprs: \(unresolvedDefaults.count)")
print("")
print("— rejected by resource kind (the surface the language must reach) —")
var byKind: [String: [String]] = [:]
for g: ScannedGenerator in rejected {
byKind[blockingResourceKind(g), default: []].append("\(g.name)(\(g.rate))")
}
for kind: String in byKind.keys.sorted() {
let names: [String] = byKind[kind] ?? []
print(" \(kind): \(names.count) [\(names.prefix(6).joined(separator: ", "))\(names.count > 6 ? ", …" : "")]")
}
if !unresolvedDefaults.isEmpty {
print("")
print("— unresolved defaults (param made required) —")
for d: String in unresolvedDefaults.sorted().prefix(20) { print(" \(d)") }
}
}
+1 -1
View File
@@ -152,7 +152,7 @@ If Agent B returned "LGTM", say so in one line.
If the review agent reports no blocking findings, append a phase entry to the **phase history log** (NOT `MEMORY.md` — `MEMORY.md` is the index and stays small):
```
/Users/josh/.claude/projects/-Users-josh-Documents-LyrebirdII/memory/phase_history.md
/Users/josh/.claude/projects/-Users-josh-Documents-src-Lyrebird/memory/phase_history.md
```
Append at the end of the file. Phase entries follow this format:
-260
View File
@@ -1,260 +0,0 @@
# Working Order
Phases are ordered by dependency. Each phase should have tests before moving on.
Completed phases (1–34, 36–95, 96a, 97, 99, 101, 102a, 102b, 103, 104a, 104b, 104c, 104d, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 160, 161, 162, 163, 170, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 196, 197, 198, 88b, MCE-A, MCE-B, 85.5, 86.75a, 86.75b, LyrebirdBufferUpdates, 77-review-cleanup, 71b, 49b, 46, iOS-1–iOS-4, Score Phases A–D, 204, 222, GC-1–GC-9B, GC-11, GC-12, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239) are archived in `docs/01-completed-working-order.md`.
## Phase Completion Checklist
Before merging any phase branch to `main`:
1. All tests pass (`swift test --no-parallel` — the parallel runner has a known SIGABRT teardown flake)
2. If the phase touched a **public signature**, `.docc`, or doc comments: `bash scripts/check-docc.sh` (no new DocC warnings) **and** `bash scripts/check-doc-snippets.sh` (recorded doc examples still compile)
3. If the phase touched **`SynthesizerBase` / `Synthesizer` actor isolation**: `bash scripts/check-swift6-consumer.sh` — the test suite cannot catch isolation regressions (it doesn't build under `-default-isolation MainActor`)
4. Run `/lyrebird_review` — no blocking findings
5. Fix any blocking issues found; re-run `/lyrebird_review` until clean
6. Merge to `main` with a `--no-ff` merge commit
7. `/lyrebird_review` updates `MEMORY.md` automatically on a clean pass
8. Move the completed phase section from this file into `docs/01-completed-working-order.md` (append at the bottom) and update the summary table below
## Generator Authoring Rules
See `docs/protocols/writing-generators.md` for the full guide. Quick checklist:
- No RT allocation in `_computeSamples` — pre-allocate in `init`
- Open `_computeSamples` with `_checkCount(count)` (inherited from `GeneratorBase`)
- Inherit `GeneratorBase` — do NOT redeclare `_segmentSerial`/`_cachedResult`/`_subBlockBuffer`/`_result`
- `ControlGenerator.Control.init` must call `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels:N)` for multi-channel)
- Route `floatValue` through `calculatedSamples(blockSize)` for AudioGenerator; return scalar target directly for ControlGenerator
- Add `calculatedSamples` bypass override if the generator has per-audio-block state (phase accumulators, gain smoothers, buffer positions) — see Out.Control as the canonical pattern
- Apply `denormalsToZero()` to all IIR feedback state after each write
- Power-of-two table sizes enforced by `precondition`
---
## Completed Phases (summary)
Full details in `docs/01-completed-working-order.md`.
| Phase | Title | Tests at completion |
|-------|-------|---------------------|
| 1 | SynthesisEngine + Core Audio | 28 |
| 1b | Scheduling + NRT Rendering | — |
| 2 | Bus System | — |
| 3 | Generator Protocol | — |
| 4 | In / Out Generators | — |
| 5 | Synthesizer Protocol + Node Tree | — |
| 6 | Parameter System | 192 |
| 7 | REPL + LineNoise | — |
| 8 | Built-in Generator Stdlib | 319 |
| 8b | Buffer System + Shared Tables | 345 |
| 9 | lyrebird CLI + Project System | 416 |
| 10 | Swift Testing Suite | 447 |
| 11 | Interpret-then-Compile Polish | 447 |
| 12 | GUI System (LyrebirdUI) | 474 |
| 13 | Generator Fan-out / Shared Signal Semantics | 483 |
| 14 | Denormal Handling | 494 |
| 15 | AIFF / WAV File I/O for LyrebirdBuffer | 511 |
| 16 | Multichannel `LyrebirdBuffer` | 527 |
| 17 | Table-Lookup Generator Polish | 540 |
| 18 | Generator Authoring Guide | 540 |
| 19 | Bus / Output Ergonomics | 549 |
| 20 | LyrebirdBufferFileIO Channel-Count Validation | 556 |
| — | Operator overloads + ConstantGeneratorInput | 570 |
| 21 | Sample Rate Mismatch Detection | 671 |
| 22 | Audio-Rate Input Modulation (FM / AM / PM) | 593 |
| 23 | Full RBJ Cookbook Filters | 671 |
| 24 | Butterworth Filters | 692 |
| 25 | Resonating, Comb, and Allpass Filters | 752 |
| 26 | Multi-Channel Expansion (MCE) | 671 |
| 27 | Control-Rate Generator Variants | 805 |
| 28 | `ParameterNode` + `@LiveParam` | 826 |
| 29 | RecordBuf + PlayBuf (Audio + Control variants) | 872 | ← archived |
| 29b | PlayBuf Reverse Playback | 879 | ← archived |
| 30 | LyrebirdRoutine + LyrebirdTask + Pattern | 905 |
| 31 | FFT / IFFT Spectral Infrastructure | 930 |
| 32 | Granular Synthesis (BufferGrain, SineGrain, FMGrain, InputGrain) | 973 |
| 33 | Panning Suite (PanN, Pan4, AmbiEncoder1, AmbiDecoder1) | 1016 |
| 33b | Accelerate / vDSP Optimization | 1019 |
| 33b-fixes | RT safety + vDSP correctness fixes | 1038 |
| — | RoutineContext beat API | 1046 |
| — | EnvelopeGen.Control + _Base fixes | 1060 |
| 34 | Multi-Core Support (ParallelGroup) | 1078 |
| 36 | LyrebirdClock | 1092 |
| 37 | MIDI (Language-Side) | 1146 |
| 38 | OSC (Language-Side) | 1146 |
| 39 | Demand-Rate Generators | 1174 |
| 40 | Engine CPU Statistics + LyrebirdStatusView | 1180 |
| 41 | Stereo Scope + Pan (ScopeCapture / LyrebirdScopeView) | 1187 |
| 42 | TriggerListener (RT→Language Trigger Infrastructure) | — |
| 43 | SendTrigger Generators + NRT Support | 1238 |
| — | Envelope.releaseNode + EnvelopeGen.gate (gated ADSR hold) | 1264 |
| — | Envelope.loopNode (single-segment gate-controlled loop; _released flag) | 1271 |
| — | EnvelopeCurve renames (.sin→.sine/.exp→.exponential); digital osc for sine/welch | 1281 |
| — | EnvelopePoll.Audio/Control — stateless valueAtTime lookup; audio-rate time input | 1293 |
| 44 | Runtime Envelope Swap (EnvelopePacket + setEnvelope) | 1300 |
| 45 | LyrebirdEnvelopeView (SwiftUI envelope shape plotter) | 1320 |
| iOS-1 | iOSAudioDriver (RemoteIO); CoreAudioDriver `#if os(macOS)` guard | 1320 |
| iOS-2 | Package.swift `.iOS(.v18)`; AVFoundation linker; DenormalUtils verified | 1320 |
| iOS-3 | LyrebirdWindow `#if os(macOS)`; PlatformColors for ParameterKnob/XY | 1320 |
| iOS-4 | LyrebirdiOSDemo Xcode project; workspace entry; correct session rate init | 1320 |
| — | LyrebirdMusicMath: free functions, midiToHz/hzToMidi, dB/amp/power, linToExp, equalPowerFade | 1369 |
| 47 | Dynamics Generators (AmplitudeFollower, FreqTracker, LookAheadLimiter, Compressor, Expander) | 1404 |
| 48 | ChannelSelect — inline channel extraction ([n] subscript on all generators) | 1420 |
| 49 | Bus Allocator — AudioBus/ControlBus value types + BusAllocator on SynthesisEngine | 1434 |
| 49b | In.Audio / In.Control multi-channel — static channels param, AudioBus passthrough | 1444 |
| 50 | Group Semantics + Node Positioning — release/free lifecycle, NodePosition, addBefore/addAfter | 1472 |
| 51 | DiskIn.Audio + DiskOut.Audio — streaming soundfile I/O (double-buffer + ring-buffer) | 1472 |
| 46 | NRTDriver soundfile input — inputURL + inputStartOffset; ExtAudioFile SR conversion | 1472 |
| 52 | Math generators — Tanh/Pow/Clip/Fold/Wrap/SoftClip/LinLin/LinExp/ExpLin/ExpExp + unary/binary (Abs/Sign/Floor/Ceil/Round/Sqrt/Reciprocal/Log/Exp/Min/Max); Bipolar+UnipolarMappingGenerator | 1547 |
| 53 | FreeVerb — stereo reverb (Jezar Freeverb); 8 comb + 4 allpass per channel; .left/.right aliases; DocC Reverbs topic | 1555 |
| 54 | GVerb — Griesinger algorithmic stereo reverb (SC-faithful rewrite); FDN+Hadamard 4-line network; tap-delay early reflections; 3+3 post-sum allpass diffusers; dryLevel param; .left/.right aliases | 2507 |
| — | Control-rate sub-blocking (controlRateConsiderations): GeneratorBase, ControlGenerator.calculatedSamples sub-block loop, 11 .Control bypass overrides, phase-advancement uses count | 1618 |
| — | controlRateConsiderations fast-follow: _swapSerial gate prevents mid-block EnvelopePacket drain in sub-block mode; defensive channel zero-fill; fanOutCache + subBlockSwap tests; SynthesisEngine driverSuggestion capture; doc callouts | 1619 |
| 55 | Noise Family (Spectral-Colour + Event): xorshift64NextRaw split; PinkNoise/BrownNoise/GrayNoise/ClipNoise/Dust/Dust2 (Audio+Control each); bypass guards on all full-bandwidth Control variants | 1715 |
| 56 | Noise Family (Chaotic + Smooth): Crackle (2-pole chaotic map, bypass guard) + LFCurveNoise (SC LFNoise2 parabolic interp); floatValue fan-out cache fix; PinkNoise b5 sign fix; GrayNoise bitPattern fix | 1747 |
| 57 | Distribution Library + Standalone Distribution Noise Generators: DistributionKind enum; DistributionSampling math (Marsaglia-Tsang gamma, Box-Muller gauss, Knuth Poisson, etc.); UniformNoise/LpRandNoise/HpRandNoise/MeanRandNoise/GaussNoise/ExpRandNoise/ExponentialNoise/GammaNoise/LaplaceNoise/ALaplaceNoise/HcosNoise/LogisticNoise/PoissonNoise/ArcsinNoise/BetaRandNoise/CauchyNoise (Audio+Control each) | 1877 |
| 58 | TemporalStream language side: TemporalParameter (.value/.envelope/.closure); TemporalAlgorithm protocol; TemporalStream (wall-clock + beat-clock timing); TemporalSequence/TemporalRandomPick/TemporalTendency/TemporalBrownian/TemporalClosure algorithms; 163 tests | 1910 |
| — | DSeq→DSequence, DRand→DRandom rename for verbosity | 1910 |
| 59 | TimedDemand synthesis side: RTTemporalParameter (Sendable, no closure); TimedDemandGenerator protocol; TimedDemand.Audio/Control (sample-accurate currentTime+i elapsed); DTemporalTendency (16 distributions); DTemporalBrownian (RT walk, auto-centring) | 1950 |
| 60 | Distribution Preview: LyrebirdScatterView (Canvas scatter plot, degenerate-range guard); DemandGenerator.samples(count:); TimedDemandGenerator.samples(count:timespan:); TemporalStream.collect(_:); TemporalDemand.md Previewing Distributions section | 1959 |
| 61 | PitchShift.Audio — granular live-input pitch shifter; circular capture buffer; auto hop management; pitchRatio [0.25, 4.0]; mono out + MCE | 1978 |
| 62 | SpectralPitchShift — phase-vocoder SpectralProcessor; true-frequency bin tracking; magnitude remapping by ratio; synthesis phase accumulator; out-of-range bins zeroed | 1978 |
| 63 | Granular Modulation Upgrade + TimeStretch — BufferGrain/InputGrain/SineGrain/FMGrain ValidGeneratorInput promotion; rate→pitchRatio rename; TimeStretch.Audio fixed-hop granular time-stretcher | 1995 |
| — | SineBufferGrain→SineGrain, FMBufferGrain→FMGrain, InputBufferGrain→InputGrain rename (drop "Buf" suffix from non-buffer granular generators) | 1995 |
| 64 | Spectral Frame Buffer — SpectralFrameBuffer (framesWritten/interpolatePhases/trimmed) + SpectralRecordBuffer + SpectralPlayBuffer (startPos) + SpectralBufferRead (normalized position) + .lbsf file I/O | 2031 |
| 65 | PlayBuf→PlayBuffer + RecordBuf→RecordBuffer rename; @available deprecated typealiases; docs + agent file updated | 2031 |
| 66 | Buffer Metadata + Duration Helpers | 2040 |
| 67 | BufferRead — normalized-position random-access buffer reader; Audio+Control; multi-channel; lyrebirdBufferRead helper; GeneratorEnum | 2053 |
| 68 | TimeStretch Multi-Channel + Remove Pan — N-channel output matching buffer.channelCount; pan/panSpread removed | 2074 |
| 69 | LyrebirdBuffer Wavetable Generation Utilities — fill(partials:), fillChebyshev, fillWindow, fillWaveshaper, fillBandLimited, fillPartials, fillInharmonicPartials, WavetableSet | 2119 |
| 70 | Ring Modulator Variants — Ring1/Ring2/Ring3/Ring4 Audio+Control binary math generators; SC AM/RM family | 2127 |
| 71 | Band-Limited Oscillators (BLEP) — OscSawtooth / OscSquare / OscTriangle / OscDutyCycle Audio+Control; polyBLEP/BLAMP correction; audio-rate PWM | 2174 |
| 71b | Non-Band-Limited LFO Oscillators — LFSawtooth / LFSquare / LFTriangle / LFDutyCycle Audio+Control; raw piecewise math; audio-rate PWM on LFDutyCycle | 2232 |
| 72 | Euclidean Rhythm + Markov Chain Patterns — euclideanRhythm(pulses:steps:rotation:)->Pattern<Bool>; TemporalMarkov new TemporalAlgorithm | 2267 |
| 73 | Jitter / Triggered Random Generators — TriggeredRandom.Control + Jitter.Control | 2289 |
| 74 | Gendy Stochastic Synthesis — Gendy1/2/3 Audio+Control; linear/cubic/fixed-dur breakpoint state machines; all 16 DistributionKind variants | 2364 |
| 75 | Spectral Feature Extraction — SpectralCentroid/Flatness/Spread/Flux/Entropy/Rolloff (Control-only, bypass sub-block loop) | 2399 |
| 75b | Live Parameter Refactor — `@LiveParam` / `@UIParam` Mirror auto-registration; `ParameterNode` + `UIParamNode` → `ControlGenerator`; `updateParameter` direct atomic; deleted `declareParameter` × 3, `ControlParameter`, `ConstantParameter`, `String: ValidGeneratorInput`, SPSC param queue | 2377 |
| 76 | State Variable Filter (SVF) — Chamberlin recurrence, 4-channel output (LP/HP/BP/Notch) from one coefficient set; `freq` + `q` ValidGeneratorInput; SVF.Control bypasses sub-block loop (audio-input IIR must advance once per block) | 2403 |
| 77 | WavetableMorph Oscillator — Audio + Control; `[LyrebirdBuffer]` + `position: ValidGeneratorInput` [0, N-1] per-sample linear interp between adjacent tables; freq + phase as ValidGeneratorInput; TableInterpolation .none/.linear/.cubic for inner reads | 2426 |
| 77-review-cleanup | Scalar `ValidGeneratorInput` intra-block ramp fixes — `_xIsGenerator` guards + per-sample paths in pan family / dynamics / LF*Noise.Audio / DelayLineFeedback; new `lastGeneratorSampleOrFloat` helper; WavetableMorph dead `_tableCountFloat` removed; rmsValue test helper extracted | 2448 |
| 78 | Karplus-Strong / Waveguide String — `KarplusStrong.Audio` (trigger-based) + `GatedKarplusStrong.Audio` (continuous gate); `exciter` + `trigger`/`gate` + `freq` + `feedback` + `coef` (one-pole, SC formula) + `sampleRate` + `maxDelayTime`; fractional delay with linear interp; `_refillRemaining` gradual fill; Audio-only | 2471 |
| 79 | Flanger / Chorus / Phaser — `Flanger.Audio` (sine-LFO modulated delay + feedback), `Chorus.Audio` (2-tap stereo, LFOs 180° apart, `.left`/`.right`), `Phaser.Audio` (4/6/8 cascaded first-order AP stages, LFO sweeps coefficient); all Audio-only, ValidGeneratorInput for all mod params | 2506 |
| 80 | FrequencyShifter — `FrequencyShifter.Audio` SSB Weaver method; two 4-stage IIR all-pass chains (90° Hilbert approx); quadrature oscillator at `shiftHz`; inharmonic 2-ch output (`.upper`/`.lower`); `shiftHz: ValidGeneratorInput`; Audio-only | 2520 |
| 81 | Polyphonic Voice Allocator — `VoicePool<S: SynthesizerBase>`; noteOn/noteOff/allNotesOff; `.oldest`/`.roundRobin`/`.quietest`/`.lowestAmplitude` steal strategies; `.quietest` reads `@LiveParam` amp via Mirror, falls back to `.oldest` | 2541 |
| 82 | Step Sequencer — `StepSequencer` language-side beat sequencer driven by `LyrebirdClock`; `SequencerStep` with pitch/velocity/gate/probability/duration/parameterLocks; rests; NSLock-protected callbacks; `Atomic<Int>` currentStep; idle-burst-fire prevention | 2563 |
| 83 | AdditiveSynthesizer — `AdditiveSynthesizer.Audio` resynthesizes `SpectralFrameBuffer` as N sines via vDSP (vadd phases + vvsinf + dotpr); position `ValidGeneratorInput`; maxPartials cap; anti-aliasing; lazy phaseIncrement init | 2583 |
| 84 | FormantGrain (FOF) — `FormantGrain.Audio` IRCAM CHANT FOF formant-grain synthesizer; sine² rise + exponential decay; per-pulse octaviation sign-flip; pool-overflow steal-oldest policy; glottalFreq clamped to ≤ sampleRate; unconditional phase wrap via truncatingRemainder; new `Lyrebird.docc/Generators/GranularSynthesis.md` topic covering the family | 2597 |
| 85 | Spectrum / Spectrogram View — `SpectrumCapture` (SpectralProcessor, ping-pong double-buffer) + `LyrebirdSpectrumView` (Canvas log-frequency X / dB Y, optional waterfall spectrogram) | 2606 |
| 85.5 | Smoothing Filters — `Lag`/`LagUpDown`/`Lag2`/`Lag2UpDown`/`Decay`/`Decay2`/`LeakDC` (Audio+Control each); shared `lagCoeff()` helper; Control variants use control rate for coefficient | 2677 |
| 86.75a | Classic SC PV ports — `SpectralPartialFilter` / `SpectralNoiseFilter` (`ClassifierMode.frequency`/`.phase` multi-frame stability classifiers, ring history with warmup), `SpectralMagnitudeMap` (`LyrebirdBuffer` transfer function on normalized mags), `SpectralHarmonicEnhance` (1/i-falloff harmonic series, Double index arithmetic for large fftSize). Atomic<Float>/<Bool> params, no shared base class | 2694 |
| LyrebirdBufferUpdates | `LyrebirdBuffer.setValue(_:at:)` / `setValue(_:frame:channel:)` / `setRangeValues(_:startingAt:)` — live language-side parameter writes safe under concurrent block-rate RT reads. NSLock serialises lang writers; RT snapshots once per block, relies on hw-atomic 8-byte aligned `Double` stores. `invalidate()` takes the same lock | 2705 |
| 86.75b | Classic SC PV ports — `SpectralBinDelay` (per-bin delay + feedback ring; `LyrebirdBuffer` per-bin parameter snapshot per hop), `SpectralCrossMap` (dual-FFT magnitude masking via new `SpectralProcessor2` protocol; bandpass / bandreject continuous mode; freeze hold), `LyrebirdUI.MultiSlider` (N-column vertical slider row writing into a `LyrebirdBuffer`) | 2720 |
| 87 | `ResonatorBank.Audio` — Klank-style parallel two-pole (Ringz) resonator bank driven from a 3-channel `LyrebirdBuffer` of `[freq, decay, amp]` triplets. Coefficients recomputed once per audio block; per-sample inner loop vectorised across the bank via `vDSP_vsmulD`/`vmulD`/`vsubD` + `vDSP_sveD`. Audio-only; mono summed output | 2783 |
| MCE-A | Channel-aware `BinaryOpGenerator` + `outputChannelCount` on Generator protocol — `+ - * /` between any operands now respects channel shape: `1×N`/`N×1` mono-broadcast, `N×N` element-wise, `N×M` with both > 1 and N ≠ M traps at init. ~17 multi-row generators override `outputChannelCount`. `mul:`/`add:` channel-0-only asymmetry preserved and documented loudly | 2803 |
| MCE-B | `GeneratorArray op N-row-generator` precondition trap — element-wise GeneratorArray operators now refuse multi-row other operand (silent-drop fix); routed through `_generatorArrayCheckOtherOperandMono` helper. `GeneratorArray.init` left permissive (existing AmbiDecoder1 patterns rely on row-0-only silent-drop) | 2804 |
| 88 | `VectorOscillator.Audio` — 4-corner XY bilinear-blend wavetable oscillator; freq/x/y/phase all ValidGeneratorInput. Shared `OscillatorTableReadHelpers.swift` (per-mode `oscillatorTableReadNone/Linear/Cubic` + `oscillatorTableRead` dispatcher) replaces fileprivate copies in OscTable + WavetableMorph; FP-boundary-safe `% tableSize` on base index. Silence-path `_mulAdd.applyIfNeeded` propagated to OscTable.Audio + WavetableMorph.Audio + VectorOscillator.Audio. Audio-only; .Control + GeneratorEnum + UI demo deferred to Phase 88b | 2828 |
| 88b | `VectorOscillator.Control` (matches WavetableMorph.Control semantics — Generator inputs read first sample, ramped output via `fillRampedResult`, `_setupSubBlockBuffer()`) + `GeneratorEnum` conformance + `VectorOscillatorUI` demo (macOS + iOS): synthesizer with `@UIParam x/y/frequency/amplitude` and four built-in wavetables (sine, 16-partial saw, triangle, Hanning), `VectorOscillatorView` using existing `LyrebirdUI.ParameterXY` for X/Y, `AppDelegate` switched to `enum Demo { case vector, binDelay, sineTone }` selector defaulted to `.vector` | 2837 |
| 89 | `SpatialDistance.Audio` — physically-plausible source-distance model: `1/distance` amplitude (clamped at `referenceDistance`), one-pole air-absorption lowpass with cutoff ∝ `(referenceDistance/distance)²`, velocity-driven Doppler via fractional read-rate `(1 − velocity/speedOfSound)` clamped to `[0.25, 4.0]`. All params `ValidGeneratorInput`. Audio-only (no GeneratorEnum); circular delay buffer pre-allocated from `maxDelayTime`; one-entry cutoff cache skips `exp()` for scalar distance | 2849 |
| 89.5 | `SpringReverb.Audio` (Schroeder spring tank — 8 cascaded all-pass dispersion stages in feedback loop with one-pole HF damping; mono-out by default, optional 2-tank stereo via `stereo: Bool` flag with detuned right-tank all-pass lengths) + `PlateReverb.Audio` (Dattorro 1997 figure-of-eight EMT 140 model — pre-delay → bandwidth LP → 4 input diffusers → cross-coupled tank with modulated AP + delay + damping + decay + AP + delay; native stereo mono-in/2-row out, `.left`/`.right` aliases, 7 Dattorro Table 1 taps per channel scaled from 29761 Hz reference). Both Audio-only, no `.Control`, no GeneratorEnum. All Dattorro/Schroeder coefficients in file-private named constants. `denormalsToZero` on every IIR feedback state write | 2872 |
| 90 | STK Instrument Models — `BowedString.Audio` (Smith/Cook split-waveguide, two delay lines + bridge LP + Cook friction table), `Flute.Audio` (Cook slide flute, bore+jet delay lines + cubic jet nonlinearity + breath noise), `Clarinet.Audio` (Cook single-reed cylindrical bore, half-wavelength delay + sign-inverted reflection + reed table + breath noise). All Audio-only, no `.Control`, no GeneratorEnum (consistent with Phases 78–80 precedent). `xorshift64Next` shared PRNG for Flute/Clarinet. `denormalsToZero` on every delay write. `PhysicalModels.md` DocC topic. | 2902 |
| 91 | Oversampling primitives — `HalfbandUpsampler2x` / `HalfbandDownsampler2x` (polyphase 2×) + `HalfbandUpsampler4x` / `HalfbandDownsampler4x` (cascaded 4×) as RT-safe public value types in `Sources/Lyrebird/Oversampling/`. Shared 23-tap symmetric Type-1 linear-phase Hamming-windowed sinc halfband FIR (`HalfbandFIR.swift`); centre tap held at exactly `0.5`, six folded paired taps normalised so total filter DC gain = `1.0` exactly; group delay 11 samples at upsampled rate. All state pre-allocated in `init()`; `process(_:)` / `reset()` allocation-free. New `Oversampling.md` DocC topic. Replaces the original "wrapper Generator" framing — sub-rate child Generators would break bus / fan-out cache invariants and the helper-struct shape is what Phase 92 Moog ladder actually wants. | 2921 |
| 92 | `MoogLadder.Audio` — Huovilainen-style 4-pole resonant lowpass with per-stage `tanh` saturation, internal 2× oversampling via Phase 91 `HalfbandUpsampler2x` + `HalfbandDownsampler2x`, and SC-style half-sample feedback compensation (`xfb = x − k·(y4 − 0.5·x)`). Self-oscillates near `resonance = 1.0`, clamped to `moogLadderMaxResonance = 1.4`; cutoff coefficient capped at `0.999`. Mono Audio-only (no GeneratorEnum, no `.Control`). `cutoff`/`resonance` `ValidGeneratorInput`. tanh count optimised: 5 per oversampled sample by caching `tanh(yN)` between stages. `denormalsToZero` on every stage. New "Saturating Ladder Filters" section in `Filters.md` DocC. | 2949 |
| 93 | `ConvolutionReverb.Audio` — uniformly partitioned FFT overlap-save convolution against an `LyrebirdBuffer` IR. `partitionSize` (power of two, default 256) sets FFT size `N = 2P` and inherent latency. IR is partitioned into `ceil(ir.count / P)` blocks at init; each partition's `vDSP_fft_zrip` forward FFT is precomputed once into per-channel split-complex storage. RT path: input accumulator fills P samples, runs forward FFT into a numPartitions-slot frequency-delay line, dispatches `vDSP_zvma` complex multiply-accumulate against every IR partition spectrum (with scalar fix-up for the packed bin-0 DC/Nyquist real values), inverse FFT, scales by `1/(4N)` (forward ×2 × forward ×2 × inverse ×N), copies last P samples (overlap-save) into a per-channel output stage. `outputChannelCount` matches `ir.channelCount`; mono input is convolved separately against each IR channel. `mix`, `mul`, `add` are `ValidGeneratorInput`. All FFT/FDL/IR storage uses `UnsafeMutablePointer<Float>` allocated in `init`, freed in `deinit`. `convolutionReverbMaxPartitionSize` = 8192, `convolutionReverbMaxPartitionCount` = 16384 cap total IR length. | 2962 |
| 94 | `MIDIFile` SMF parser (formats 0 + 1, PPQ division) + `MIDIFilePlayer` clock-driven playback. Pure language-side parser in `Sources/Lyrebird/MIDI/SMF/`: `MIDIFileError` enum, `MIDIFileEvent` (beat-stamped event with `Kind` covering `.midi(MIDIMessage)` channel events + `.tempo`/`.timeSignature`/`.keySignature`/`.trackName`/`.instrumentName`/`.text`/`.copyright`/`.lyric`/`.marker`/`.cuePoint`/`.endOfTrack` meta), `MIDIFileTrack`, `MIDIFile`. Internal `SMFParser` reads MThd/MTrk chunks, decodes VLQ delta times, honours running status, surfaces meta events through `decodeMetaEvent`, silently skips SysEx / unknown meta. Tick→beat conversion at parse time (`beat = tick / ticksPerQuarter`) so result is tempo-independent. `allEvents`/`allChannelEvents`/`tempoMap`/`totalBeats` convenience views; merge across tracks is stable on `(beat, trackIndex)`. `MIDIFilePlayer` owns a `LyrebirdRoutine`, walks `allEvents` calling `ctx.wait(beats:)` between events, dispatches `.midi` to `handler`, applies `.tempo` to `clock.bpm` when `applyTempoMap == true` (else forwards), routes everything else to optional `metaHandler`. `play`/`stop`/`reset`/`state` lifecycle. Rejects format 2 + SMPTE division at parse time. | 2983 |
| 96a | `MIDIClockFollower` language-side BPM follower (`Sources/Lyrebird/MIDI/Sync/MIDIClockFollower.swift`): rolling window of last *N* tick `SampleTime`s (default 24 = quarter-note window) → inter-tick avg → `60 / (avgSec * 24)` BPM, clamped to `[minBPM, maxBPM]`, epsilon-gated push to `clock.bpm` *outside* the follower's lock to avoid lock-ordering vs `LyrebirdClock._lock`. Default `_isRunning = true` so free-running clock sources without transport messages work; `.stop` gates `_handleClock` until `.start`/`.continue` re-enables. New `MIDIMessage.continue` (0xFB) added to enum (keyword-escaped), parser, and `bytes()`. Internal `init(timeProvider:)` allows synthetic-clock test injection. Phase 96b (Ableton Link) not planned. | 3122 |
| 95 | `ScannedSynthesizer.Audio` — Mathews/Verplank 2000 1D mass-spring scanned synthesis. Power-of-two ring of N masses (default 64, max 1024). Per audio block: two-pass Jacobi explicit-Euler update — pass 1 fills `_accelerations[]` from old positions/velocities (avoiding in-place Gauss-Seidel asymmetry), pass 2 integrates `v += a·dt` and `x += v·dt`. Per-mass: discrete 1D Laplacian × stiffness − damping·v − centeringForce·x + excitationForce[i]. Excitation injected at single configurable mass index, sampled once per block via `lastGeneratorSampleOrFloat`. Per-sample audio-rate phasor scans `_positions[]` as a wavetable through `oscillatorTableRead` (none/linear/cubic). New `[Double]` overloads of `oscillatorTableRead*` helpers added in `OscillatorTableReadHelpers.swift`. New `ScannedSynthesizerShape` enum (`.gaussian`/`.sine`/`.impulse`/`.zeros`) for init-time displacement preset. Audio-only, no `.Control`, no `GeneratorEnum`. New DocC topic `Generators/ScannedSynthesis.md`. | 3138 |
| 97 | `MuTronIII` — envelope-controlled resonant filter (Audio + Control) modelling the Musitronics Mu-Tron III (1972) auto-wah. Topology: full-wave rectify × `sensitivity` → asymmetric one-pole envelope follower (inlined, not composed) → exponential cutoff sweep `freqLo·pow(freqHi/freqLo, env)` → inlined Chamberlin SVF (selectable `MuTronIIIMode` `.lowpass`/`.bandpass`/`.highpass` and `MuTronIIISweep` `.up`/`.down` — both `let` constants set at init). Mono output. Guards: `_inputIsGenerator` classification + scalar fast path (avoids `Double.calculatedSamples` heap alloc), sensitivity clamped ≥ 0, `freqLo`/`freqHi` clamped to `[0.001, Nyquist]` with monotone ratio, peak floor `1.0` (Chamberlin stability `q1 + f < 2` at `f → 1.0` from Nyquist sweep), denormals zeroed on `_prevAmp` + `_svfLow` + `_svfBand`. `Control` uses standard `calculatedSamples` bypass for once-per-block IIR state advancement; output `fillRampedResult` from previous to current target. New types: `MuTronIIIMode`, `MuTronIIISweep`. 24 tests including deterministic Chamberlin sample 0/1 verification at `1e-12`. | 3162 |
| 102a | Ambisonic Toolkit (FOA extra encoders) — `FoaEncodeOmni` (omni: W=input, X=Y=Z=0; full amplitude on W vs FoaPanB's plane-wave 1/√2 convention) + `FoaEncodeStereo` (left, right, angle) summing two opposing FoaPanB encodes at ±angle. Static `angle: Double` arg; coefficients (`foaRsqrt2`, `cos(angle)`, `sin(angle)`) pre-computed at init. Direct `GeneratorBase, AudioGenerator` finals with 4-row output. lyrebird_review clean on first pass. 28 new tests. | 3595 |
| 103 | Runtime Source-Swap for `@LiveParam` Slots — `synth.$freq.source = SineOsc.Control(...)` replaces the generator wired into a parameter slot without stopping the synth. RT-safe (no allocation, no locks, no ARC retain/release on the audio thread) via `SourcePacket` carrying `Unmanaged<AnyObject>` over per-parameter `ParameterSourceQueue` (SPSC, capacity 4). Engine-wide `parameterSourceKillQueue` (SPSC, capacity 256) holds old slots until the main-thread drain (hooked into the existing background timer) releases them; overflow degrades gracefully. Crossfade-N-blocks soft swap (mid-block-snapshot mix; scalar↔generator transitions handled; mid-crossfade swap kills in-progress old slot). UIParamNode parity via `calculatedSamples` forwarding. KeyPath approach rejected due to Swift 6 generic-on-open-class constraints; `synth.setSource(synth.$freq, to: lfo)` taking a `ParameterNode` directly is the secondary API. Two review passes — pass 1 caught `as?` on RT path (replaced with class-to-class-protocol `as!`) and `UIParamNode` missing `calculatedSamples` override (would have silently bypassed source-swap pipeline). 69 new tests across 5 files including end-to-end integration through a running engine. | 3703 |
| 104d | AUv3 aux output + sidechain input — Multi-bus extension on top of 104a/b/c. New `LyrebirdAUBusSpec` value type (name + channelCount). Two new `open class var` hooks on `LyrebirdAudioUnit`: `lyrebirdOutputBusses` + `lyrebirdInputBusses` returning `[LyrebirdAUBusSpec]`. Defaults derive from existing single-bus `lyrebirdOutputChannels` / `lyrebirdInputChannels` so single-bus subclasses (LyrebirdFM, every 104a-c demo) keep working unchanged. Init builds N `AUAudioUnitBus` per spec array, sums channels for engine init, builds AU-bus-to-engine-bus offset maps (`auOutputBusOffsets` / `auInputBusOffsets` now stored on `SynthesisEngine` as `public internal(set) var`). `internalRenderBlock` closure captures `outputBusNumber` and passes through to `AUv3Driver.render(outputBusNumber:...)`. Driver gains `configureBusMap(outputBusChannelCounts:inputBusChannelCounts:)` called by `allocateRenderResources` before engine.start; per-output-bus `AUv3RingBuffer`s replace single ring; per-input-bus host ABL + Float backing; `_fillInputStagingFromHost` iterates input busses and pulls each via `AURenderPullInputBlock(...,inputBusNumber:...)`. New `AUv3RingBuffer.write(fromAudioBuses:sourceBusOffset:channelCount:count:)` slices engine.audioBuses per bus. `AUInput.Audio` gains `init(busIndex:channel:)` designated init; existing `init(channel:)` is now a convenience for `busIndex: 0`; compute consults `engine.auInputBusOffsets[busIndex] + channel`. Saturation guard in `_distributeEngineOutputToRings` resets a ring when its `availableToWrite < blockSize` — handles asymmetric host bus pulls (RT crash otherwise). Named `auv3RingBufferHeadroomFactor: Int = 2` constant for ring sizing. Two review passes: pass 1 caught RT crash on asymmetric pulls (saturation guard added) + missing render-loop sidechain coverage (added) + magic number `2` (named) + AUInput.Audio class-level doc gap (busIndex entry added); pass 2 clean. 9 new tests across 1 file (single-bus backcompat + multi-output exposes + multi-output engine layout + multi-output rendering routes independently + asymmetric pulls don't crash + two input busses exposed + sidechain offset map populated + AU input busIndex resolves + render-loop dispatches per-input-bus pullInputBlock). | 3788 |
| 114 | Generator boilerplate reduction (`_result` on `GeneratorBase`, `_checkCount(_:)`, default `floatValue` on `AudioGenerator`, `makeSampleBuffer`/`makeResultBuffer` factories) — eliminates ~1000 lines of mechanical boilerplate. Mono `AudioGenerator` is six lines instead of ~18; multi-row generators call `super.init(channels: N)` and drop manual `_result = …` allocation. `FreqTracker`, `FreeVerb`, `GVerb` got `outputChannelCount` overrides en route (silently mono-ized under operator arithmetic before). `GranularBase.init(seed:channels:)` lets stereo grain subclasses thread channel count through. ~150 generator files + 17 test files swept; `docs/protocols/writing-generators.md`, `Sources/Lyrebird/Lyrebird.docc/Generators/WritingGenerators.md`, and `CLAUDE.md` rewritten around the new patterns. Three review passes: passes 1 + 2 each caught doc-only regressions (class-level + protocol-level `GeneratorBase`/`Generator` summaries that still described post-super reassignment instead of `super.init(channels: N)`, plus the DocC article's five pre-Phase-114 code blocks); pass 3 clean. 3544 tests — same count as Phase 113. | 3544 |
| 148 | Flaky timing tests — three `TestBlockDriver` fixtures (`LyrebirdProcess`/`LyrebirdEventList`/`LyrebirdEventListRecording`) drove the engine at ~1.45 ms audio per 1 ms wall sleep ≈ barely realtime, so 1.5 s wall-clock test timeouts expired before envelope releases / process completions could fire `onFinished` (10–18 failures/run). Burst 32 `processBlock` calls per `Thread.sleep` (≈ 46× realtime). `_running` flag tightened to `Atomic<Bool>` (`Synchronization`) since 32 reads/iter widened the prior plain-`var` race; `_thread` stored property added for parity; sleep duration named (`wallSleepSeconds`). 10 consecutive `swift test --filter` runs clean. Misdiagnosed `FLAKY_TIMING_TESTS.md` census deleted — `releaseElapsed ≈ 62.3 × 10⁹ s` is a `Date.distantFuture`-class sentinel delta, not a mach-timebase bug. | 3610 |
| 149 | `lyrebird repl` fix — `swift package repl` was removed from the Swift toolchain; the CLI's `repl` subcommand + the `lyrebird>` interactive-shell `repl` command had been silently broken. `REPLLauncher` rewritten as a two-step invocation: `swift build` stages `.build/debug/Modules/Lyrebird.swiftmodule` + `libLyrebird.dylib` + `LyrebirdC.build/module.modulemap`, then `swift repl -I .build/debug/Modules -I .build/debug/LyrebirdC.build -L .build/debug -lLyrebird` (same flags SPM was computing internally). New `CLIError.buildFailed(exitCode:)` surfaced in both `InteractiveShell` and `LyrebirdCLIMain.runREPL`; `build(in:)` checks `process.terminationReason == .exit` first so signal kills surface as `exitCode: 1` rather than the raw signal number. WIP recovered from an orphaned agent worktree (`claude/infallible-boyd-97598a`) during a branch-cleanup sweep; 3-way applied cleanly to current `main`. Two-pass review — pass 1 caught missing test coverage on the `buildFailed` path + missing `-I`/`-L` flag-token assertions + signal-kill exit-code leak; pass 2 clean. | 3611 |
| 151 | AppKit-in-core layering fix + `lyrebird_review_cycle` cleanup. Two batches landed together. (1) **AppKit extraction**: new `open class MouseInputBridge` in core (default no-op returns 0.5/0.5/0.0) + `enum MouseInput` registry (`Atomic<UnsafeMutableRawPointer?>` typed pointer with `nonisolated(unsafe)`; **scalar accessors** `currentX`/`currentY`/`currentButton: Double` to avoid returning a class reference on RT path with ARC retain/release; `.relaxed` ordering with documented "install before `engine.start()`" happens-before fence; identity-check fast path on `install(_:)`; `NSLock` serialises install/uninstall; `uninstall()` is `@_spi(LyrebirdExtensions)`). `Mouse.swift` made cross-platform, all three `Mouse.*.Control` get `_calculatedSamplesBlockRate` bypass override. `MouseTracker` deleted from core, recreated in `LyrebirdUI` as `MouseInputBridge` subclass; `installShared()` asserts main thread, idempotent via `Atomic<Bool>` CAS gating both registry install + main-queue NSEvent monitor install. CLAUDE.md module-layering rule extended to ban `AppKit`/`UIKit` in core alongside `SwiftUI`. (2) **Review-cycle cleanup**: RT ARC fixes — SynthesisEngine input-bus copy uses index-loop with `inputSamples[ch].withUnsafeBufferPointer` (no inner-`[Float]` `let` retain) + `Swift.max(0, …)` clamp + `min(src.count, dst.count)` element-wise update (step-1 zero-fill makes tail-clear unnecessary); ScopeCapture `borrowing [[Float]]` parameter + subscript-borrow access; In.swift / AUInput.swift subscript-borrow rewrites with `precondition(offset + count <= buf.count)` bounds restoration; In.floatValue uses `withUnsafeBufferPointer` + `preconditionFailure(...)`. `LyrebirdAUPresetCodable.makeGenerator` lock-during-callback fix (dequeue-then-invoke). 4 granular `outputChannelCount: Int { granularChannelCount }` overrides on `BufferGrain`/`SineGrain`/`FMGrain`/`InputGrain` (silent stereo→mono regression under `* 0.5`), pinned by 4 binary-op tests. New `fillScalarRampedResult(into:previousOutputValue:target:count:)` helper in `MulAdd.swift` with 28-site `Math.Control` sweep; registered in CLAUDE.md "Shared RT-Safe Helpers" + writing-generators.md §13. New `DynamicsBase: GeneratorBase` shared base (`public class`, `static let dbAmplitudeScale`/`logFloor`/`softKneeParabolaFactor`, dual-location `/// - Parameters:` docs at base + `Compressor._Base` + `Expander._Base`); Compressor + Expander `_Base` collapsed to subclasses. `GeneratorEnum`-omitted comments on `SpectralChain`/`AdditiveSynthesizer`/`FormantGrain`. Sendable invariant comments on `ScorePlayer`/`MIDIClockFollower`/`SpectralFrameBuffer`. `MouseTracker` `deinit` removed (singleton process-lifetime). 8 review-fix passes total before clean. | 3697 |
| 152 | Pre-run engine reconfig + master gain / mute. `SynthesisEngine.sampleRate` / `numOutputChannels` / `numInputChannels` promoted from `let` to `public private(set) var` with three new setters (`setSampleRate(_:)` / `setNumOutputChannels(_:)` / `setNumInputChannels(_:)`) gated by `engineIsRunning` + `invalidValue` errors from new `SynthesisEngineConfigError`; identity writes short-circuit so bus-allocator free list doesn't churn. `setSampleRate` recomputes `_blockDurationNs`. Master output gain (`masterGain: Double` via `Atomic<UInt64>` bit-packed pattern, NaN/Inf-rejecting setter) + `isMuted: Bool` (`Atomic<Bool>`) live on the engine; end-of-`processBlock` per-channel `vDSP_vrampmul` linear ramp from `_previousAppliedGain` to live target avoids slider/mute clicks. Per-channel `var start = from` reseed each iteration because `vDSP_vrampmul` mutates `*start` in place — first review pass caught a regression where channels 1–3 flat-multiplied at target instead of ramping. `_previousAppliedGain` reseeded from live state in `start()` so stop→start cycle that ended muted doesn't replay stale ramp. `BusAllocator.hardwareAudioEnd` becomes mutable; new internal `_reconfigureHardwareReservation(numOutputChannels:numInputChannels:)` invalidates audio buses + remarks reservation under existing `NSLock`; control buses untouched. `_release` refactored to `honoursHardwareReservation: Bool` + read live `hardwareAudioEnd` inside lock — closes TOCTOU race. `LyrebirdEngineStatusView` gets Configuration section (sample-rate `Picker` 44.1k / 48k / 88.2k / 96k / 176.4k / 192k dynamically augmented with engine's current rate when non-stock; output/input channel `Stepper`s 1…32 / 0…32) gated `.disabled(isRunning)`, Output section (`Toggle("Mute")` + `Slider` in `-90…+12` dB paired with `TextField` formatted `%+.1f`, shared `masterGainDb` state). View `init` seeds every `@State` from live engine values; private `linearToDb` finite-floors at slider lower bound; `pushConfigToEngine` guards setter `.onChange` against running-while-mirroring drift. Two new test suites — `SynthesisEngineConfigTests` (3 setters × happy / running-throws / invalid / overflow + post-resize bus allocation lands after reservation) + `MasterGainMuteTests` (get/set round-trip, NaN/Inf rejection, end-of-block ramp math `expectedLast = to + (from - to) / n`, 4-channel ramp regression catching the `*start`-leak, mute zeros output, master gain doesn't touch input buses, stop→start regression for `_previousAppliedGain` reseed). Two review passes — pass 1 caught the `vDSP_vrampmul` channel-leakage bug + unnecessary atomic surface area + missing reseed-on-start + reservation invalidation gap; pass 2 clean. | 3727 |
| 153 | `LyrebirdEventList` fire-time tracking + body-closure backref. Two new public methods on `LyrebirdEventList` — `fireTimes(forEvent:) -> [Double]` (every offset at which the index fired; empty if not yet / out-of-range, no trap) + `firstFireTime(forEvent:) -> Double?` — filter `_timeline` rather than maintain a parallel index (timelines are short). New `private let _timelineLock = NSLock()` protects `_timeline` across five mutation sites (`_appendTimelineEntry` / `clearTimeline` / `setTimeline` / `loadTimeline` / the `_timeline.removeAll()` in `reset`) and both cross-thread readers; bare `var timeline` getter + `saveTimeline` / `playTimeline` remain unsynchronized (main-thread only, same thread as mutators) with a new `- Important:` doc note. `@unchecked Sendable` rationale at top of class rewritten to spell out the new locking protocol vs. main-only state. `LyrebirdProcess` gains `internal weak var _owningEventList: LyrebirdEventList?` set in the ownership-claim loop alongside `_eventListStartProvider` / `_eventListStartSampleTimeProvider`; weak so the process doesn't retain the list (list already retains the process via `_allProcesses`). `LyrebirdProcessContext` gains matching `internal weak var _owningEventList` + public `var eventList: LyrebirdEventList?` computed accessor; populated by `LyrebirdProcess._play` next to existing `context._eventListStart = _eventListStartProvider?()`. Body / `onRelease` closures can now write `ctx.eventList?.firstFireTime(forEvent: 0)` to cross-reference earlier events. Six new tests appended to existing `LyrebirdEventList` suite — empty-before-play, monotonic first-fire-time (origin == 0.0, indices 1+2 strictly monotone-positive), out-of-range / negative indices return empty/nil without trapping, multi-fire capture (two `play(eventIndex: 1)` → two distinct entries), context.eventList identity for owned + standalone, body closure reads `ctx.eventList?.firstFireTime(forEvent: 0) == 0.0` after a 10 ms sleep (synchronous `_appendTimelineEntry` inside `play(eventIndex:)` runs before the background task wakes). Two-pass review — pass 1 caught stale `@unchecked Sendable` rationale comment claiming `_timeline` was main-thread only (contradicting the new cross-thread accessors) + two `t1!` / `t2!` force-unwraps in `#expect` (CLAUDE.md prohibits force-unwraps in test code too); fixes used `try #require(...)` bindings; pass 2 clean. | 3727 |
| 163 | `midiToRatio` / `ratioToMidi` SC-style musical-math additions — surfaces existing `semitonesToRatio` / `ratioToSemitones` under SC-flavored names that mirror the `midiToHz` / `hzToMidi` pair, plus dot-syntax on `Double` (`12.0.midiToRatio` → `2.0`, `2.0.ratioToMidi` → `12.0`) and `Int` (`12.midiToRatio` → `2.0`, `(-12).midiToRatio` → `0.5`). Free functions (Double + Int overloads + array overload), `extension Double` / `extension Int` computed-var dot syntax (module-qualified `Lyrebird.midiToRatio(self)` inside the extensions to disambiguate from the property name), `Collection<Double>` / `Collection<Int>` methods paired with the existing `semitonesToRatio()` / `midiToHz()` collection methods. Driven by the MyPiece pitch-shift use case where the composer reasons in semitones but the generator expects a ratio (`PitchShift.Audio(pitchRatio: 7.midiToRatio)`). 14 new tests (octave check, round-trip, equivalence with `semitonesToRatio`, dot syntax Double + Int, array overloads, non-positive edge → `-.infinity` / NaN inherited from `log2`, three collection-method forms). Docs updated end-to-end (`docs/stdlib/generators.md`, `Sources/Lyrebird/Lyrebird.docc/Generators/MusicalMath.md`) with the SC convention paragraph + PitchShift call-site example. Two review passes — pass 1 flagged absent Collection-method symmetry + missing non-positive edge test (both non-blocking but addressed); pass 2 clean. | 3876 |
| 162 | `Envelope.releaseNode` aligned with SuperCollider's level-index convention — fixes a sharp edge where `Envelope([0,1,0], [2,2], releaseNode: 1)` was silently holding at the post-decay zero instead of the audible peak. Pre-Phase-162 `releaseNode` was a SEGMENT INDEX (hold value `levels[releaseNode + 1]`); now a LEVEL INDEX (hold value `levels[releaseNode]`) — matches SuperCollider's `Env` convention and the user's mental model. Valid range `[1, levels.count - 1]`. `EnvelopePacket` converts the public level index → internal segment index `releaseNode - 1` at packet construction so RT-side `EnvelopeGen` arithmetic stays untouched. `LyrebirdProcess.release(reltime:)` reads `_envelope.levels[releaseNodeIdx]` directly. `loopNode` (still a segment index) cross-validation is now `loopNode < releaseNode - 1`. 45 in-tree `releaseNode: N` literals bumped to `N + 1` to preserve their existing hold-level behavior; three doc examples whose values had been incorrect under both old and new semantics were also fixed end-to-end. View helper `_regionForSegment` already treated `releaseNode` as a release-region-start boundary equivalent to a level index, so no view code change. Tests: 4-test `LyrebirdProcessReleaseNodeHoldTest` regression suite (level-index identity for the exact MyPiece envelope, peak-hold under gate, out-of-range clamps to nil, final-level edge case); `StdlibGeneratorTests` assertions `env.releaseNode == N` updated to match bumped public values. Two review passes — pass 1 caught 11 stale comments + a force-unwrap; pass 2 caught 4 remaining stale comments. | 3862 |
| 161 | Auto-free synths on envelope done — surfaces SC-style "envelope done → node freed" semantics. New `Sources/Lyrebird/Envelopes/DoneActionWatchable.swift` protocol (`var needsFree: Bool { get }`, AnyObject-constrained) conformed by `EnvelopeGen.Audio` + `EnvelopeGen.Control`. `SynthesizerBase.autoFreeOnDone(_:)` opt-in inside `build()` designates a lifecycle probe; engine `add`/`schedule`/`remove` hooks register/unregister via a new `_AutoFreeEntry` registry. Single shared `DispatchSourceTimer` on `lyrebird.autofree` utility queue, 10 ms cadence (matches LyrebirdProcess watcher). Tick: snapshot registry, read atomic `needsFree`, remove fired entries from registry BEFORE dispatching `engine.remove(synth)` on main — closes a double-fire race that would otherwise corrupt `NodeTreeMirror` via duplicate `didRemove`. Dead-entry sweep handles both `synth == nil` and `probe == nil` so orphaned slots can't pin the timer. `engine.stop()` cancels the timer, clears entries, and barriers via `_autoFreeWorker.sync {}`; late-arriving `DispatchQueue.main.async` blocks guard `args.engine.isRunning` so a tick that escapes the barrier exits cleanly instead of enqueuing a stranded `.remove` event into `pendingQueue`. Cross-thread carrier `_AutoFreeRemovalArgs: @unchecked Sendable` mirrors the existing `ContextAddArgs` / `GroupFreeArgs` idiom. Five new tests (`Tests/LyrebirdTests/Envelopes/AutoFreeOnDoneTests.swift`): Control + Audio envelope auto-free, manual-remove-before-fire unregister, multiple staggered synths, and a no-opt-in synth that stays in the tree. Three review passes — pass 1 caught the double-remove race + orphaned-probe gap + ARC leak via late-firing main.async after stop(); pass 2 caught a narrow remaining window where main.async could land post-stop; pass 3 clean. | 3855 |
| 160 | Node tree visualization — main-thread `NodeTreeMirror` (`@Observable public final class`) that tracks every language-side `engine.add` / `schedule` / `remove` / `Group.free` and publishes an immutable `NodeTreeSnapshot` for SwiftUI. New `Sources/Lyrebird/NodeTree/NodeTreeSnapshot.swift` (value-type `Node` with `Kind = .synth(className:) / .group / .parallelGroup`, `ObjectIdentifier id`, head→tail children) and `NodeTreeMirror.swift` (internal mutable tree keyed by `ObjectIdentifier`; updated **after** a successful `pendingQueue.enqueue` so the mirror's view stays consistent with the RT thread's view; skipped on overflow). `SynthesisEngine` gains a `public let nodeTreeMirror` seeded after `rootGroup`/`mainGroup` install; hooks added to `schedule(_:at:)`, `schedule(_:after:)`, `add(_:position:)`, `remove(_:at:)`. `Group.free(engine:)` records the update post-enqueue; `Group.release(engine:)`'s background timer hops to `DispatchQueue.main.async` via a new `GroupFreeArgs: @unchecked Sendable` carrier (same `LyrebirdRoutineContext.Args` idiom) before invoking `free` so the mirror is never mutated from `.global(qos: .utility)`. `ParallelGroup.head` promoted `private → internal` so the mirror can walk the main-thread-populated children at engine.add time. New `LyrebirdNodeTreeView` in `LyrebirdUI`: recursive disclosure rows, head→tail order, depth-indented; per-row glyph (chevron / dot), display name, child-count badge for groups, 4-hex identity suffix derived from `ObjectIdentifier.hashValue` (stable across processes; no parsing of stdlib internal `String(describing:)` format). Header has Expand All / Collapse All; macOS `presentInWindow(...)`. `LyrebirdEngineStatusView` gains a collapsible Node Tree section above the Messages section + macOS Open Window button (close-and-reopen toggle). Eleven new `NodeTreeMirrorTests` + one regression test for child-remove preserving the parent group: initial snapshot shape, head/tail/before/after insertion, remove, nested groups, ParallelGroup head→tail walk on add, Group.free dropping subtree, displayName matches runtime class, `.before` fallback on unknown anchor. Three review passes — pass 1 caught a thread-safety violation (`Group.release` timer mutating mirror on utility queue) + multi-param init style + magic-number `6` + dead-code `timestamp` + redundant `@Bindable`; pass 2 caught inaccurate "before"-vs-"after" doc wording and a brittle `String(describing: ObjectIdentifier)` parse; pass 3 clean. | 3839 |
| 159 | `LyrebirdMessage` + `LyrebirdMessageView` — user-visible diagnostic channel kept strictly off the RT thread. New `Sources/Lyrebird/Diagnostics/` subfolder with `LyrebirdMessageTier` (info / warning / error), `LyrebirdMessage` (Identifiable Sendable struct), and `LyrebirdMessageCenter` (`@Observable @MainActor` singleton with bounded FIFO ring, default capacity 200). `LyrebirdMessageView` in `LyrebirdUI` provides a scrollable list with per-tier filter chips, count badges, Clear button, auto-scroll to newest, and macOS `presentInWindow(...)`. `LyrebirdMessageBanner` is a compact 3-line embed surfaced inside `LyrebirdEngineStatusView` as a collapsible Messages section between CPU metrics and configuration; the engine status view also offers an "Open Window" button on macOS. Shared tier-colour / short-label helpers live in `LyrebirdMessageHelpers.swift` per the `*Helpers.swift` rule. `print()` is intentionally untouched — library authors opt into `post()` for user-visible messages while keeping the developer-console stream. Eight new `@MainActor` tests cover post / tier routing / capacity pruning / capacity-reduction prune / clear / identity / capacity-1 / `allCases` ordering. Two review passes — pass 1 caught two-public-types-in-one-file and a cross-file helper not in a `*Helpers.swift`; both fixed plus a missing subfolder rationale added to CLAUDE.md. | 3827 |
| 154 | Explicit `: Type` annotations on every inferred `let` / `var` binding across `Sources/` (351 files, 6177 sites) and `Tests/` (223 files, 14249 sites) — Xcode type-checker speedup + readability win. Motivation: Xcode's expression checker is markedly slower on long, generic-heavy synth-graph expressions when intermediate locals are inferred; annotating the binding short-circuits that work. New `Tools/AnnotateBindings/annotate_bindings.py` drives `/usr/bin/sourcekit-lsp` over LSP JSON-RPC: per file, sends `textDocument/didOpen` then requests `textDocument/inlayHint` for the full range and applies the LSP `textEdits` that come back. Applied set filtered by a strict guard that rejects every Swift position where `: T` would not parse: (a) line-suffix must match `(let\|var\|for)\s+<identifier>$` (no intervening `{`, `[`, `(`, `,`); (b) tuple-pattern destructures (`let (a, b) = …`); (c) closure-header / capture-list (`{ ptr in`, `{ [weak self] in`); (d) `case let .foo(x)` / `catch let err …` pattern positions. Iterated four times during initial bring-up: closure-param hints `{ ptr: T in` broke 16 files → `_has_binding_keyword_before` added; `[weak self: T]` capture-list hints broke 1 file → stricter `<identifier>$` suffix added; `catch let err: T as P` broke `LiveSession.swift` → `_PATTERN_CONTEXT_RE` added. One manual fix: `LyrebirdScratchView.swift` had `let engineRefresh = Timer.publish(...).autoconnect()` annotated as `Publishers.Autoconnect<…>` (Combine type not imported in that file) → reverted to inferred form. One stale untracked `Sources/Lyrebird/Generators/UI/MouseTracker.swift` discovered (Phase 151 deleted this exact path; canonical lives in `Sources/LyrebirdUI/`) → removed manually. Tool ships unit-free using only Python stdlib; idempotent (running twice produces no second round of edits because every binding now ends in `<identifier>$:`). `swift build` clean; `swift test --no-parallel` → 3725 tests in 422 suites pass. Two-agent review (lyrebird_review_agent + caveman line sweep) clean — only non-blocking tool nits flagged (hardcoded `/usr/bin/sourcekit-lsp` path, hardcoded `REPO_ROOT` default, regex doesn't strip `//` comments, file URI not percent-encoded). | 3725 |
| 170 | `GeneratorInputProvider` as first-class `ValidGeneratorInput`. New `_resolvedInput() -> any ValidGeneratorInput` protocol requirement (default returns `self`; provider overrides to call `make()`). Every Generator init resolves `any ValidGeneratorInput` slots once at the top before storing / classifying — provider becomes transparently substitutable for any input source at the call site with no `.make()` boundary call. Helper-boundary resolution at 5 sites (`MulAddSpec` / `OscillatorBase` / `LFNoiseBase` / `NoiseBase` / `DynamicsBase`) covers many Generators automatically; sweep touches 139 Generator inits across all 22 generator-folder families. Provider's other `ValidGeneratorInput` accessors are `preconditionFailure` traps with a shared `_unresolvedProviderTrapMessage` string — unreachable in correct code, fire at first audio block if a provider somehow survives unresolved. Init-time only, non-RT, zero render-path overhead. End-to-end validated by MyPiece `TimeStretchMoment.build()` passing the provider directly to `AmbiEncoder1.azimuth`. One review-fix pass closed 7 blocking findings (3 missed-sweep files, 5 raw-param `is any Generator` classification sites that shadowed correctly-resolved inherited flags, 9 distribution-noise `_Base` inits, 1 helper-boundary policy violation in `AmbiEncoder1`, 1 stale docc example, 1 plan-doc snippet contradicting the skip-list); re-review clean. | 3961 |
| 181 | sampleOrZero sweep — third + final sub-phase of the 179-181 code-dedup follow-on. New `Sources/Lyrebird/GeneratorCore/HotLoopHelpers.swift` with `@inline(__always) @_spi(LyrebirdExtensions) public func sampleOrZero(_ p: UnsafePointer<Double>, _ i: Int, _ n: Int) -> Double` returning `i < n ? p[i] : 0`. Replaces per-sample `(i < n) ? srcP[i] : 0` boilerplate across 16 files (Filter family + Delay primitives). 4 files (DelayLine / DelayLineFeedback / CombFilter / AllpassFilter) had pre-existing `sampleAt(_ i:)` inline closures — deleted; call sites use `sampleOrZero` directly. CLAUDE.md + writing-generators.md §13 registered. Output bit-equivalent across 358 affected tests. Closes the 179-181 follow-on to the 174-178 perf sweep. | 358+ |
| 180 | Smoother step helpers — second sub-phase of the 179-181 code-dedup follow-on. Two related abstractions: (A) `onePoleLowPassStep(state:x:b1:comp:)` (`y = b1·state + comp·x`) + `leakyIntegratorStep(state:x:b1:)` (`y = x + b1·state`) in `FilterHelpers.swift` — applied across Lag / Lag2 / LagUpDown / Lag2UpDown / Decay / Decay2 inner loops. (B) new `Sources/Lyrebird/Generators/Dynamics/DynamicsHelpers.swift` with `AttackReleaseDirection` enum (`.rising` / `.falling`) + `attackReleaseSmoother(state:target:attackCoeff:attackComp:releaseCoeff:releaseComp:direction:)` — applied across AmplitudeFollower (`.rising`) + Compressor / Expander (`.falling`). All `@inline(__always)` — generated code identical to inlined form. Review-fix pass registered new helpers in CLAUDE.md + writing-generators.md §13 (mandatory per convention) + `import Foundation` → `import Darwin` for Dynamics family consistency. Output bit-equivalent across 124 affected tests. | 124+ |
| 179 | Filter helper consolidation — first sub-phase of the 179-181 code-dedup follow-on to the 174-178 perf sweep. Two new `@inline(__always)` module-internal helpers in `Generators/Filters/FilterHelpers.swift`: (A) `runTwoPoleResonatorScalarBlock` + `runTwoPoleResonatorInterpolatedBlock` — `RingingFilter.processScalar` / `processInterpolated` and `ResonatingFilter.processScalar` / `processInterpolated` bodies were byte-identical post-Phase-178 except for the coefficient function; both consumers now shrink to a coefficient closure + one-line helper calls (~80 lines deleted across the two files). (B) `sampleOrFallback(_:scalar:at:)` — per-sample coefficient lookup with zero-fallback past block end. Replaces 8 verbose sites in SecondOrderSection (5) + FirstOrderSection (3). Review-fix pass added 4 missing class-level `/// - Parameters:` doc blocks on touched Generator types (pre-existing gaps). Output bit-equivalent across 358 filter-suite tests. | 358 |
| 178 | IIR filter library sweep — final sub-phase of the 174-178 generator perf sweep. State hoist + raw-pointer hoist + once-per-block denormal flush pattern applied to 12 IIR filter files. Largest win: the two shared `processBlock` overloads on `BiquadState` + `FirstOrderState` in `RBJBiquad.swift` — amortised across every RBJ filter (LP/HP/BP/BPSkirt/AP/Notch/PeakingEQ/LowShelf/HighShelf) and every Butterworth filter (cascade biquad + first-order stages). Direct sweep also touched Lag/Lag2/LagUpDown/Lag2UpDown/LeakDC/Decay/Decay2/SecondOrderSection/FirstOrderSection/RingingFilter/ResonatingFilter. Skipped (deferred): MoogLadder / SVF / MuTronIII (nonlinear oversampled, tanh dominates), ResonatorBank (needs vDSP rather than state-hoist), Hilbert (small site). Two review-fix passes — first eliminated RT-path per-sample Optional dispatch (`srcP?[i] ?? 0`) across all 12 newly-touched files + 4 Phase-176 delay primitives for consistency; second pass cosmetic. Output bit-equivalent across 358 affected tests. | 358 |
| 177 | `DiskOut.Audio` perf pass — fused ring-write + `_result` passthrough into one per-sample loop (was two passes). Mono fast path with raw-pointer hoist on `_ringBuffer[0]` (Float) / `_result[0]` (Double) / input row via nested `withUnsafe(Mutable)BufferPointer`. Four sub-branches `(canWrite, hasInput)`: fused write+passthrough / silence-fill both / passthrough only / silence result only. `wHead` hoisted to local + single `_framesWritten.store` at end. Multi-channel path kept on bounds-checked subscripts. BG-thread + producer-consumer atomics handshake unchanged. One review-fix pass eliminated an RT-path `[]` allocation in the zero-input-row degenerate branch. Output bit-equivalent across 11 DiskIn/DiskOut + EventList recording integration tests. | 11+ |
| 176 | Delay-line primitives perf pass — DelayLine / DelayLineFeedback / CombFilter / AllpassFilter all already used PoT ring + bitmask wrap; new wins from state hoist (`writePos`, `allpassPrevOut`/`InputOut`/`OutputOut`), raw-pointer hoist via nested `withUnsafe(Mutable)BufferPointer` on buffer(s) + input + `_result[0]`, interpolation `switch` lifted out of per-sample loop into 4 explicit per-mode branches (`.none` / `.linear` / `.cubic` / `.allpass`), `cubicInterp` converted from instance method to `@inline(__always) fileprivate static`. One new `ringWrapStressManyWrapsOfShortRing` test covers DelayLine across ~172 ring wraps. Review-fix pass addressed magic-number `64` × 3 in new test + stale `cubicInterp` doc reference. Output bit-equivalent across 124 affected tests. | 124+ |
| 175 | Reverb family modulo elimination — branchless ring-buffer wrap replaces every per-sample `% size` operation across SpringReverb (2 sites), PlateReverb (9 sites), GVerb (12 sites). Non-PoT sizes cannot fold to a bitmask so original code emitted real `idiv` on the RT path. `denormalsToZero` preserved per CLAUDE.md convention (NRTDriver no thread-level FTZ). FreeVerb deferred — already branchless wraps, structural flat-buffer refactor needed for further wins. Three new `denormalLongTailStaysFinite` tests exercise many ring wraps with real DSP (initial draft was vacuous via fan-out cache; review-fix pass hoisted shared engine + per-block `advanceBlock`). Output bit-equivalent across 43 reverb-suite tests. | 43+ |
| 174 | Dynamics family perf pass — `AmplitudeFollower.Audio`, `Compressor.Audio`, `Expander.Audio`. State hoisted to locals across block (`_prevAmp` / `_prevGain`), once-per-block denormal flush, precompute `attackComp = 1.0 - attackCoeff` + `releaseComp = 1.0 - releaseCoeff` once per block, explicit if/else over attack/release branches replaces shared coefficient ternary, raw-pointer hoist on input + `_result[0]`, drop redundant `Double(...)` casts. Control variants untouched (one smoother step per audio block, not per sample). 3 new denormal-cadence tests (`denormalCadenceAmplitudeFollower` / `denormalCadenceCompressor` / `denormalCadenceExpander`). Review-fix pass strengthened the AmplitudeFollower test (initial draft was vacuous — pure zero input never left state). Output bit-equivalent across 41 dynamics-suite tests. | 41+ |
| 173 | Input Conditioning Optimization (three sub-phases on independent branches): **173a** `LookAheadLimiter` perf pass — drop the parallel `_peakRing` (deque payload now carries `(peak, expireAtPos)` inline), branchless wrap on all ring/deque indices (kills every per-sample `%` on non-PoT capacities), precompute `_attackComp = 1.0 - _releaseCoeff`, denormal flush moved from per-sample to once-per-block, zero-look-ahead fast path (no ring, no deque), all state hoisted to locals with single writeback. **173b** `RecordBuffer.Audio._computeSamples` perf rewrite — `LyrebirdBuffer._rawStorageMutable` hoisted once per block, all param arrays + `_result[0]` lifted to raw pointers via nested `withUnsafe(Mutable)BufferPointer`, fill + buffer-write passes fused into one per-sample loop, block-constant fast-path detection on first + last sample of `run` / `recLevel` / `preLevel` (`runStable` / `preBlockZero` / `recBlockOne` flags), mono branch dispatches between four tightened loops with the hottest case collapsing to a single mul-free store per sample. Channel-count validation moved from RT-path `precondition` to `Audio.init`. **173c** new `MixIn.Audio(buses: [AudioBus], mul:, add:)` in `Generators/BusIO/` (sums N non-contiguous audio buses channel-wise into one output — replaces `signal + In.Audio(bus:)` chains) + new `SumChannels.Audio(input:, mul:, add:)` in `Generators/Routing/` (collapses any multi-channel input to mono via row summation; mono passthrough; `vDSP_vaddD` chain for multi-channel). Both Audio-only (no Control variant, `GeneratorEnum` conformance intentionally omitted). 27 new tests across `LookAheadLimiter` (2), `RecordBuffer` (5), `MixIn.Audio` (7), `SumChannels.Audio` (7). Touched-suite filter runs 241+/241+ pass deterministically; full `swift test --no-parallel` hits the intermittent pre-existing `RTThreadIdentity.markingIsThreadLocalNotProcessGlobal` TLS-leak / `LyrebirdBuffer` retain-race flakes only. Driven by MyPiece's `MixAndRecordInputs` / `ConditionAndRecordInputs` synthesizers running hot at session start (mix N input buses → optional `LookAheadLimiter` → `RecordBuffer`). Each sub-phase shipped on its own branch with full `/lyrebird_review` cycle (173a + 173b each had two review-fix passes; 173c one review-fix pass). | 3985+ |
| 172 | `LyrebirdEventList` master-amp routing redesign + `ReplaceOut.Audio` / `ReplaceOut.Control` primitives + pre/post-master sub-groups. Triggered by a real-world MyPiece bug: `LyrebirdProcess._play` accepted a `procOutOverride` parameter and `LyrebirdEventList` used it to silently override every contained process's declared `procOut` to point at an internally-allocated `_masterBus`, silently breaking any process designed to feed a downstream effect chain (e.g. ambisonic-routed B-format → global decoder). Coupled fix: (1) `LyrebirdEventList.init` takes caller-supplied `bus: AudioBus` (replaces `masterChannels: Int`), default `AudioBus(index: 0, channelCount: 2)`; (2) `procOutOverride` parameter removed from `LyrebirdProcess._play` — dead code that was the original-bug mechanism; (3) new `ReplaceOut.Audio` / `ReplaceOut.Control` first-class overwrite bus-write primitives parallel to `Out` (`vDSP_vdpsp` direct to bus slice; engine plumb `setAudioBus` / `setControlBus`; `ScratchBuses.replace` overwrites this child's scratch slot inside `ParallelGroup` — does NOT scrub other siblings or pre-parallel content; `SynthGraph.setSamplesOnAudioBus` routes; `SynthesizerBase.replaceOutput(bus:source:)` helper); (4) `EventListMasterSynth` rewritten as `In.Audio(bus) * smoothAmp -> replaceOutput(bus)` (multi-channel via `BinaryOpGenerator` mono-broadcast); supersedes an interim "delta-add" trick (`bus += bus * (amp - 1)`); (5) new `preMasterGroup` / `postMasterGroup` sub-groups inside `_masterGroup` for caller-owned FX synths around the master amp, with `addPreMaster(_:)` / `addPostMaster(_:)` convenience helpers — synth lifetime bounded by EventList session (freed via `_masterGroup.free()` on teardown; fresh empty groups re-allocated for next session). Unblocks ambisonic decoders / bus-level limiters / master tap recorders. Sweep migrates `Tests/LyrebirdTests/Process/LyrebirdEventList{,Recording,Timeline,BuildFromFile}Tests.swift`, `ProcessSystem.md`, and MyPiece's `QuartetEventManager.createEventList()`. 19 new tests across `ReplaceOutAudioGeneratorTests.swift` (9) + `ReplaceOutControlGeneratorTests.swift` (4) + `LyrebirdEventListPrePostGroupTests.swift` (6). One `/lyrebird_review` cycle — blocking finding (two `@Suite` per file) fixed by splitting Audio + Control suites; non-blocking nits addressed (`_lyrebirdAssertNotOnRTThread()` guard on `outputChannelCount`; duplicate-precondition removal; sink-only `floatValue=0` doc; Control vs Audio channel-count divergence doc; explicit row-count guard; `ScratchBuses.replace` dirty-mark inside the write block; stable-sort pending-queue ordering comment; pre/post group lifecycle comments; design doc reordered to lead with `ReplaceOut`, delta-add moved to "Historical Note"). New `docs/engine/eventlist-routing-design.md` captures the bug, fix, ReplaceOut refactor + trade-off table, pre/post group design, lifecycle / ordering, migration. MyPiece `xcodebuild` BUILD SUCCEEDED with `bus: dependencyContainer.ambisonicRoutingBus`; ambisonic-decode chain now hears all four quad-channel feeds. | 3980 |
| 113 | Pan4 family refactor (`PanAz`, `PanAzDistance`, `PanXY`, `PanXYDistance`) — reshapes the 4-speaker panning family around an `open class Pan4` base class holding the shared infrastructure (4-row output buffer pre-allocated to `lyrebirdDefaultResultBufferSize`, `_mulAdd`, `outputChannelCount = 4`, named channel aliases inherited via extension). Four concrete subclasses provide the actual generator behaviour. Old leaf `Pan4` (azimuth + elevation `@LiveParam` in `[-1, 1]`) retired — its azimuth-only behaviour now lives in `PanAz` with proper radian semantics. New shared `Pan4Helpers.swift` (module-internal, `@inline(__always)`): `azimuthToSquareBoundary(_ az: Double) -> (x, y)` projects azimuth radians onto the unit-square boundary via `1 / max(|sin|, |cos|)` so the trajectory hits speaker corners at `±π/4` and `±3π/4` (rather than the inscribed unit circle leaving corners unreachable); `writeEqualPowerSquarePanSample(into:sampleIndex:source:x:y:)` clamps `(x, y)` to `[-1, 1]²` and writes equal-power gains to the four `_result` rows. **`PanAz`** — `@LiveParam azimuth: Double` in radians (0 = front centre, wraps modulo 2π via `sin`/`cos`); position fixed to unit-square boundary. **`PanAzDistance`** — `azimuth` + `distance` (0 = listener, 1 = boundary, >1 = beyond) + `velocity`; same 1/d amp + air-absorption LP + Doppler pipeline as `PanXYDistance`, single mono LP + single delay line before panning; negative distance treated as `|distance|` (direction from azimuth). **`PanXY`** — `@LiveParam x`/`y` cartesian; refactored to inherit from `Pan4` and call the shared helper. **`PanXYDistance`** — cartesian + Chebyshev distance shaping; refactored to inherit from `Pan4` and use shared helper for the pan-write. `SpatialDistance` file-private constants promoted to module-internal `SpatialDistanceConstants.swift` for reuse across distance-model generators. Test migration: old `Pan4Tests` (in `PanningTests.swift`) rewritten as `PanAzTests` with corner positions at `±π/4` / `±3π/4` and cardinal-edge tests at `0` / `±π/2` / `π`; `Pan4ParameterRampingTests.swift` → `PanAzParameterRampingTests.swift` (git mv + rewrite); `ChannelSelectTests` Pan4-alias test updated to use `PanAz` at `az = -π/4`; new `PanAzDistanceTests.swift` (rate, channel count, boundary corner = PanAz, distance=0 equal-energy collapse, 1/d halving, negative-distance symmetry, Doppler down-shift, mul, fan-out cache); existing PanXY tests stay green via inheritance. Two review cycles total: first (initial PanXY/PanXYDistance with old Pan4 still elevation-based) caught dead `_referenceDistance` + `_sampleRate` + two-`@Suite`-per-file + `try?` swallow; second (this family refactor) clean on the first sweep — vtable dispatch through `AudioGenerator` protocol witness verified, no RT `is`/`as?`, helper inlining clean, channel-alias inheritance through extension on Pan4 correct. Docs swept: `docs/stdlib/generators.md` Panning Extensions section rewritten around the four-row family table; `docs/stdlib/multichannel.md` intro + named-aliases table; `Sources/Lyrebird/Lyrebird.docc/Generators/MultiChannel.md` intro list. | 3544 |
| 112 | Extension authors guide + README extensions section — new `docs/extension-authors-guide.md` walks end-to-end through building an out-of-tree Swift package adding Generator/Synthesizer implementations. Companion to `docs/protocols/extension-sdk.md` (SPI surface list). Covers wiring, versioned releases, and pitfalls (SPI imports in tests, `Bundle.module` per-package, package-name case-sensitivity in target deps, SSH vs HTTPS for private repos, SemVer + compatibility matrix). LyrebirdATK is the canonical worked example — authors clone its `Package.swift` / `Sources` / `Tests` / `README` / `LICENSE` as templates. README.md gets an "Extensions" section between "The lyrebird CLI" and "Project structure" listing known extension packages + pointers to the SDK doc and authors guide; documentation table picks up two new rows. Doc-only commit; no source code changed. | 3499 |
| 111 | Extract Ambisonic Toolkit (FOA) to LyrebirdATK external package — entire `Foa*` UGen set (37 generators in `Sources/Lyrebird/Generators/Ambisonic/`), bundled MIT KEMAR HRIR data (`Resources/HRTF/KEMAR/kemar-full.lbhr`, 1.47 MB), and `HRIRFile.bundledKemar{Full,FullURL}` static accessors removed from core. The exact same code (untouched algorithmically) now ships as the **LyrebirdATK** external Swift package — first worked example of the Extension SDK (Phase 110). Consumers add `LyrebirdATK` as a separate package dependency + `import LyrebirdATK` alongside `import Lyrebird`. Bundled-KEMAR `Bundle.module` lookup moved to `LyrebirdATK/Sources/LyrebirdATK/HRIRFile+BundledKEMAR.swift` where `Bundle.module` resolves to the LyrebirdATK package's resource bundle. Generic `HRIRFile.load(contentsOf:)` loader stays in core, unchanged. Six KEMAR-loading tests moved 1:1 to `LyrebirdATK/Tests/LyrebirdATKTests/HRIRFileBundledKEMARTests.swift`; 28 `Foa*` test suites moved out; synthetic / negative / round-trip loader tests stay in core. `docs/stdlib/ambisonic-toolkit.md` → `LyrebirdATK/docs/ATK-Guide.md`; `docs/stdlib/generators.md` ATK section rewritten as a pointer; `scripts/build-kemar-hrir.py` → `LyrebirdATK/scripts/`. `Package.swift` Lyrebird target — `resources: [.process("Resources")]` removed. Deliberate API-breaking change; recommended tag **Lyrebird 2.0.0** after merging (consumers on prior FOA-bundled Lyrebird stay pinned to `0.9.x`). Verification: core `swift test` 3499 / 405 suites; LyrebirdATK `swift test` (against this branch via local path dep) 322 / 36 suites; sum 3821 = pre-extraction total (no tests deleted, every removed test moved 1:1). | 3499 |
| 110 | Extension SDK foundation — promotes the shared RT-safe helper symbols required by external Generator packages to `@_spi(LyrebirdExtensions) public`. `MulAdd.swift`: `MulAddSpec` (struct + init + stored props), `applyIfNeeded`, `apply`, `identity` static, `extractScalar`, `fillRampedResult`, `lastGeneratorSampleOrFloat`. `WhiteNoise.swift`: `xorshift64Next` + `xorshift64NextRaw`. `@_spi(LyrebirdExtensions)` keeps the surface invisible to ordinary `import Lyrebird` consumers while letting extension authors opt in with `@_spi(LyrebirdExtensions) import Lyrebird`; SPI symbols documented as MINOR-version-mutable. New `docs/protocols/extension-sdk.md` (tier-1 stable public + tier-2 SPI table, versioning policy, namespacing guidance); `docs/protocols/writing-generators.md` §13 cross-link. `Tests/LyrebirdTests/MulAddTests.swift` switched to `@testable @_spi(LyrebirdExtensions) import Lyrebird` (the `@testable` import alone does not grant SPI access). **Phase 110 follow-up**: two additional SPI hooks for out-of-tree test code building its own `advanceBlock`-style helper — `SynthesisEngine.segmentSerial` (read-only acquiring load) + `SynthesisEngine.advanceSegmentSerial()`, documented in a new "Test-helper hooks" subsection of `extension-sdk.md`. Bulk import sweep across 231 test files (mechanical, no test logic changed). | 3821 |
| 109 | `SpectralPolarClosure` + `SpectralComplexClosure` — two closure-driven `SpectralProcessor` wrappers (same role `Closure` plays for time-domain DSP). Polar variant is zero-copy via existing buffer pointer accessors; DC/Nyquist round-tripped through pre-allocated single-element scratch (`_dcValue`/`_nyquistValue` are private). Complex variant uses `_readToRectangular`/`_writeFromRectangular` (vDSP packed split-complex: `real[0]=DC`, `imag[0]=Nyquist`) with two pre-allocated `UnsafeMutablePointer<Float>` scratch arrays freed in `deinit`. `Float` element type matches buffer storage. `hopSize` + `sampleRate` baked into closure class at init. `_frameIndex` mutable `Int` counter, RT single-threaded. New DocC topic `Generators/SpectralClosures.md`; new section in `docs/stdlib/spectral.md`. 12 tests for polar + 15 for complex including `complexFreezeLatchesSpectrum` (pre-allocated `memcpy` latch — canonical RT-safe freeze pattern). Two review passes — pass 1 caught dead `scratchReal`/`scratchImag` vars in freeze doc-example + typo `Latces`→`Latches`; pass 2 caught one non-blocking DocC terminology note (`inout`-like → captured reference box). | 3821 |
| 108 | `PlayBuffer` rate + trigger → `ValidGeneratorInput` — promoted `PlayBuffer.playRate` (renamed to `rate`) + `PlayBuffer.trigger` from `@LiveParam Double` to `any ValidGeneratorInput` init params on both Audio and Control variants. Generator path uses `lastGeneratorSampleOrFloat` (Control) / `Optional<[Double]>?? scalarFallback` (Audio) — no per-sample heap allocation; scalar fast path calls `floatValue(graph:)` once. `Control.calculatedSamples` bypass retained for per-block phase state. +5 tests (generator-driven rate, generator-driven trigger via `Impulse`, scalar trigger reset, Control trigger reset, Control reverse). 4 demos + buffer-io-generators.md swept. Two review passes — pass 1 caught helper-inlining + dead `_zeroFallback`; pass 2 clean. | 3794 |
| 107 | `LyrebirdBuffer.nativeRateScale` — sample-rate compensation helper moved off `PlayBuffer._Base` onto `LyrebirdBuffer` itself; any buffer-consuming generator now reuses it. Redundant `Double()` cast dropped (`sampleRate` already `Double?`). New 4-test `LyrebirdBufferRateScaleTests` @Suite covers nil/equal/up/downsampled; two prior cases in `PlayBufferTests` deleted. Six demos + `docs/stdlib/buffer-io-generators.md` swept. Single review pass clean — no findings. | 3790 |
| 106 | FFT chain consolidation (legacy removal + synthOnly) — delete `FFTAnalysis.swift` + `IFFTSynthesis.swift`; all public spectral surface routes through `SpectralChain.Audio`. New `SpectralBufferGenerator` protocol (`spectralBuffer` + `hopSize`); `SpectralBufferRead` + `SpectralPlayBuffer` conform. New init `SpectralChain.Audio(spectralSource:fftSize:hopSize:…)` for fourth mode — synthOnly: aliases source `spectralBuffer`, drives source once per block, skips windowing + forward FFT, runs processors + fan-out + IFFT bank on aliased buffer. `_fftAnalysisRealp`/`_fftAnalysisImagp` switched to `Optional<UnsafeMutablePointer<Float>>` (`nil` in synthOnly; guarded deinit + use sites). Runtime precondition `count <= hopSize` in synthOnly `_computeSamples` prevents frame-loss when engine blockSize > hopSize. Migrated 7 `.Control` feature extractors (Centroid/Flatness/Spread/Flux/Entropy/Rolloff/OnsetDetector): `analysis:` init type changes from `FFTAnalysis` to `SpectralChain.Audio`. `SpectralChain.Audio.processors` widened `private` → `internal` for OnsetDetector.Control precondition. Doc sweep: `docs/stdlib/spectral.md` rewritten around `SpectralChain.Audio`; `docs/stdlib/generators.md` spectral section rewritten; all `.docc` topics (`SpectralChain.md`, `SpectralFeatures.md`, `SignalAnalysis.md`, `BuiltInGenerators.md`, `PitchShifting.md`, `GranularSynthesis.md`) updated; `LyrebirdBuffer` window docs + `SpectralBuffer` + `SpectrumCapture` + `LyrebirdSpectrumView` updated. Demos: dropped duplicate root-level `PercSpectralPitchShift.swift`; rewrote `Synthesizers/Spectral/PercSpectralPitchShift.swift` to use `SpectralChain.Audio`. New `PercSpectralStereoDiffuse` demo (mono → 2-channel decorrelated stereo via `SpectralStereoDiffuse` fan-out), wired as Demo 5 in `BufferDemos.swift` (TimeStretch shifts to Demo 6). Stale `Synthesizers/Buffer/` + `Synthesizers/Granular/` subfolder duplicates folded — newer flat root copies moved into subfolders via `git mv` to match Xcode pbxproj groups; pbxproj updated for new fan-out demo. Tests rewritten across `FFTTests`, `SpectralAutoPullTests`, `SpectralProcessor2Tests`, `SpectralChainTests`, `OnsetDetectorTests`. Phase 105 golden-buffer parity test removed (no legacy to compare). New `SpectralChain.Audio — synthOnly mode` test suite: `synthOnlyResynthesisProducesNonZeroAudio` + `synthOnlyDispatchesProcessorsOnAliasedBuffer` (verifies counter callCount > 0, lastSeenDC == source DC, chain.spectralBuffer === source.spectralBuffer identity). Two review passes — pass 1 caught missing synthOnly test coverage + class-level `/// - Parameters:` doc gap + fragile capacity-0 allocate/deallocate; pass 2 clean. | 3789 |
| 105 | Spectral mono→N consolidation — `SpectralChain.Audio` Generator (`Sources/Lyrebird/Generators/Spectral/SpectralChain.swift`) collapses the legacy `FFTAnalysis` + `IFFTSynthesis` two-Generator pipeline into one. Three modes: mono resynthesis (default), mono→N fan-out (`fanOut` arg), analyze-only (`analyzeOnly: true` — no IFFT runs, audio output is silent, used by feature extractors). Internals: shared `vDSP_create_fftsetup` across N IFFTs; per-channel synthesis work buffers (`work realp/imagp`, `timeDomainBuf`, `overlapBuf`, `outputRing`) allocated in init; destinations[0] aliases `spectralBuffer` in the no-fanOut path (zero per-hop copy); analysis + synthesis hopCounters tick independently to match legacy `outputRingReadPos = ringSize - hopSize` one-hop latency. Golden-buffer test confirms sample-for-sample equivalence with `FFTAnalysis + IFFTSynthesis` for the mono path. New `SpectralFanOutProcessor` protocol (`process(source:into:channel:)` shape for mono→N decorrelation). First conformer `SpectralStereoDiffuse`: anti-correlated xorshift64 streams seeded from `seed` and `seed ^ spectralStereoDiffuseAntiSeedMask`; magnitudes memcpy-passthrough; phases blend toward independent uniform-random targets via shortest-angular-distance; `Atomic<Float>` amount [0, 1]; amount=0 is exact bypass. Legacy `FFTAnalysis` + `IFFTSynthesis` kept fully functional with class-level docstring "Note (Phase 105)" callouts pointing to `SpectralChain.Audio`; hard `@available(*, deprecated)` annotation deferred so internal feature extractors don't generate warnings — legacy-callsite migration is a future tightly-scoped phase. Two review passes — pass 1 caught a fan-out guard bug (`_destinations.count > 1` silently skipped fan-out for N=1 conformers, leaving uninitialised buffers fed to IFFT) + missing class-level `/// - Parameters:` block on `SpectralChain.Audio`; pass 2 clean. 17 new tests across 2 files. | 3779 |
| 104c | AUv3 MIDI / UI / Presets / Effect-AU — `LyrebirdAudioUnit.midiHandler: ((MIDIMessage, AUEventSampleTime) -> Void)?` dispatched from `internalRenderBlock` via `_MIDIHandlerStorage` `Atomic<UInt64>` pointer swap (acquire/release; ARC-free on RT). `LyrebirdAUVoicePoolBinding` main-thread adapter wraps a `VoicePool` for note-on/off with subclass-configurable per-voice setup + optional channel filter (RT bridging documented but not bundled — users wire via CoreMIDI or SPSC drain). Effect-AU mode via `open class var lyrebirdInputChannels: Int { 0 }` — when > 0 the AU declares an input bus, `AUv3Driver` pulls one engine block of host input per `engine.processBlock` via `AURenderPullInputBlock` into pre-allocated host-input `AudioBufferList` + contiguous Float backing, copies into engine input buses (`[numOutputChannels, numOutputChannels + numInputChannels)`). New `AUInput.Audio(channel:)` Generator reads from those buses lazily at compute time (defensive zero-fill on out-of-range). New `LyrebirdUI.LyrebirdSynthView` Mirror-driven SwiftUI parameter grid — `@UIParam` slots only (LiveParam skipped — no `@Observable` projected value), `LazyVGrid` of `ParameterKnob`, per-knob range/unit/display-name from optional `[String: LyrebirdAUParameterInfo]` metadata. Factory-preset system: `LyrebirdAUFactoryPreset` value type (`name` + `scalarValues` + `sourceSlots`) returned from `factoryPresetsForLyrebird()` override, bridged into `AUAudioUnit.factoryPresets` + `currentPreset` automatically. Source-slot save/restore: `LyrebirdAUPresetCodable` protocol (`presetTypeID` + `presetEncodedParameters` + `presetMake(from:)`) + `LyrebirdAUPresetSourceRegistry` (`NSLock`-protected) — generators wired into `ParameterNode.source` (Phase 103) round-trip through `fullState` when registered. `fullState` payload restructured: scalars + sources + sourceTypes nested under sub-keys (`lyrebirdAUFullStateScalarKey` / `SourcesKey` / `SourceTypesKey`); legacy flat 104a payload still readable. Three review passes — pass 1 caught `_MIDIHandlerStorage.handler` data race (replaced with atomic pointer swap) + `withUnsafePointer` escape in `_fillInputStagingFromHost` + VoicePoolBinding's "RT-callable" doc lie (rewritten main-thread-only with bridging patterns) + RT string interpolation in AUInput precondition + missing dual `/// - Parameters:` doc blocks; pass 2 caught a `!` force unwrap in `_MIDIHandlerStorage.deinit` + 3 unnamed layout constants in LyrebirdSynthView; pass 3 clean. 25 new tests across 7 files. | 3762 |
| 104b | AUv3 Reference Xcode Project — `Demos/LyrebirdAUv3Demo/` ships a working `aumu` AudioUnit v3 plugin (Realized Sound: LyrebirdFM, type/subtype/manufacturer `aumu`/`LBFM`/`RLZS`). Container app target embeds the `.appex` extension into `LyrebirdAUv3Demo.app/Contents/PlugIns/`. Hand-written `project.pbxproj` with both targets, Embed App Extensions copy phase (`dstSubfolderSpec = 13`), `PBXTargetDependency` wiring app → extension, shared `xcscheme` with `parallelizeBuildables="NO"` matching the Xcode 26 SPM convention. The extension target links only the `LyrebirdUI` SPM product — linking `Lyrebird` directly trips Xcode 26's "static library by both X and Y" conflict for the `type: .dynamic` package product. `LyrebirdFM.swift` example synth is a 2-op FM (`@LiveParam carrierFreq/modRatio/modIndex/amp`, mono fanned to stereo). `LyrebirdFMAudioUnit.swift` is 12 lines — `makeSynthesizer()` + `parameterMetadata()`. `LyrebirdFMAudioUnitViewController.swift` is the `AUAudioUnitFactory` (`createAudioUnit(with:)` builds the AU) + empty `AUViewController` stub (104c populates). `Info.plist` declares the `AudioComponents` array with `sandboxSafe = true`, `tags = [Synth]`, factory-via-principal-class. Both targets get `com.apple.security.app-sandbox`; container also gets `user-selected.read-only`. `xcodebuild` Debug + Release verified with `SWIFT_USE_INTEGRATED_DRIVER=NO` + ad-hoc signing; `.appex` correctly embedded. `auval -v aumu LBFM RLZS` + Logic / GarageBand / AUM smoke tests are manual Josh steps (autonomous `pluginkit` registration of an unsigned extension is sandbox-blocked, correctly). New top-level docs: `Demos/LyrebirdAUv3Demo/README.md` (template walkthrough), `docs/auv3-extension-guide.md` (step-by-step "ship your own plugin" guide). Single review pass — pass 1 caught one orphan `Lyrebird` SPM product dep + `BuildIndependentTargetsInParallel = 1` mismatch with scheme's `parallelizeBuildables=NO` + agent-internal memory path leak in the guide + Release launch action; pass 2 clean. No Lyrebird Swift sources changed — tests unchanged at 3737. | 3737 |
| 104a | AUv3 Wrapper Infrastructure — headless Swift API bridging `SynthesisEngine` + `SynthesizerBase` into the `AUAudioUnit` contract. `AUv3Driver` (passive `AudioDriver`; engine ref held via `Unmanaged`, no ARC on RT) drives an `AUv3RingBuffer` (per-channel power-of-two ring) to decouple fixed `blockSize` from host-variable `frameCount`. `open class LyrebirdAudioUnit: AUAudioUnit` exposes subclass hooks `makeSynthesizer()` + `parameterMetadata()` + `lyrebirdBlockSize` + `lyrebirdOutputChannels` + `lyrebirdMaxFramesToRender`; builds parameter tree in `init` via Mirror walk (matches `_autoRegisterLiveParams` order); creates a fresh engine in `allocateRenderResources` at host-negotiated sample rate; tears down in `deallocateRenderResources` (synth survives the cycle). `LyrebirdAUParameterMapping` Mirror-driven discovery emits stable `AUParameterAddress` per `@LiveParam` / `@UIParam` slot; `LyrebirdAUParameterInfo` carries per-parameter min/max/unit/displayName/flags overrides (since `@LiveParam` itself has no bounds). `fullState` round-trips scalar `@LiveParam` values under namespaced `lyrebirdAUFullStateKey` — Phase 103 source-slot generators explicitly out of scope (104c). `Package.swift` widens AVFoundation link from iOS-only to all platforms. Headless — no Xcode `.appex` artefact (104b's job). Two review passes — pass 1 caught two stored `AUAudioUnitBusArray!` IUOs (replaced with `?` + guard-fatalError in getters), two public types in one file (`LyrebirdAUParameterEntry` split out), and five `baseAddress!` force unwraps in tests (replaced with `guard let` + `Issue.record`); pass 2 clean. 32 new tests across 4 files. | 3737 |
| 102b | Ambisonic Toolkit (FOA binaural decoder) — `FoaDecodeBinaural`: 4-row B-format input → 2-row stereo headphone output via MIMO partitioned-FFT overlap-save convolution against 8 baked rendering filters (4 B-format channels × 2 ears). `FoaBinauralFilters.build(from:)` constructs filters at init by projection-decode summation over all HRIR positions (matching `FoaDecodeProjection` coefficients exactly). Bundled MIT KEMAR full set (710 positions, 512-sample IRs, 44.1 kHz) via `HRIRFile.bundledKemarFull`; user HRIR sets accepted via `HRIRFile.load(contentsOf:)`. Configurable `partitionSize` (power of two, default 256); inherent latency = one partition. `.left`/`.right` channel aliases. All buffers + FFT setups pre-allocated in `init`, freed in `deinit`; no RT allocation. 25 new tests. | 3634 |
| 101 | Ambisonic Toolkit (FOA core) — 27 `Foa*` generators in `Sources/Lyrebird/Generators/Ambisonic/`: 20 Group A angle transforms (Rotate/Tilt/Tumble, Focus/Push/Press/Zoom/Direct{X,Y,Z}, DirectO, Asymmetry) via `_FoaAngleBase`; 3 Group B (Dominate{X,Y,Z}) via `_FoaGainBase` (dB cached for skip-when-constant pow); 3 Group C IIR filters (NFC, Proximity, PsychoShelf) with `denormalsToZero` on every feedback var; `FoaPanB` encoder + 3 closed-form decoders (DecodeProjection N-speaker projection, DecodeStereo, DecodeQuad). `FoaMatrix4` 16-tuple `Double` value type + `@inline(__always) foaApply`. Math translated literally from SC3 `AtkUGens.cpp` FILL_*_MATRIX macros. Coexists with `AmbiEncoder1`/`AmbiDecoder1`. Two review passes: pass 1 flagged 5 redundant `calculatedSamples` overrides on `AudioGenerator` conformers (§5 violation — protocol extension already handles segment-serial fan-out caching; bypass concern is `ControlGenerator`-only). All deleted; pass 2 clean. 263 new tests. | 3567 |
| 100 | `SpectralFormantShift` — magnitude-envelope-preserving formant shift `SpectralProcessor`. Estimates the smooth envelope of the current frame via `.cepstral` (default, accurate; internal `CepstralEnvelopeEstimator` owns a second real `FFTSetup`, `vvlogf`/`vDSP_fft_zrip` inverse/lifter/forward/`vvexpf`, `2·N` round-trip rescale, `magnitudeFloor = 1e-12`) or `.magnitudeSmoothing(radiusBins:)` (two-pointer box blur), divides it out to whiten, resamples along the bin axis by `shiftRatio` with linear interpolation + one-bin fade past Nyquist, and reapplies. Phase untouched; DC/Nyquist signs preserved. `shiftRatio` `Atomic<Float>` clamped `[0.25, 4.0]`; `1.0` is bypass. Pairs with `SpectralPitchShift` to decouple pitch from formant motion. New public enum `FormantShiftMethod`. 10 new tests. | 3304 |
| 99 | Spectral Filtering + Phase Manipulation — seven new public `SpectralProcessor` types operating on polar `SpectralBuffer`: `SpectralBrickwall` (`.lp`/`.hp`/`.bp`/`.br` modes; `vDSP_vclr` outside passband), `SpectralPhaseShift` (`.deg90`/`.deg180`/`.deg270`/`.radians` Hilbert-style rotation; live `radians` retunable), `SpectralGate` (linear + `thresholdDB:` convenience init via shared `dbToAmp`; `floor` ∈ [0,1] hard-gate-to-bypass blend), `SpectralTilt` (pre-computed dB/oct gain table around pivot Hz; DC bin forced to unity), `SpectralBlur` (magnitude box-blur via two-pointer running sum; `_blurOut` allocated init-time; edge bins shrink window), `SpectralDiffuse` (continuous phase randomization 0→1 via `lyrebirdSeedXorshift64(from:mixConstant:)` + named `spectralDiffuseMixConstant`; shortest-angular-distance blend), `SpectralConvolve` (frequency-domain complex multiply with second buffer for cross-synthesis or static IR; either-buffer-invalid → live cleared). Two shared helpers extracted to `Sources/Lyrebird/Spectral/`: `wrapPhasesInPlace` (consumed by refactored `SpectralFreeze` + new processors) and `binFromHz`. All `process` methods open `guard spectral.fftSize == _fftSize else { return }` (no RT string interpolation). Pre-allocated scratch; `Atomic<Float>`/`Atomic<Int>` for live params. New "Spectral Filtering & Phase" section in `docs/stdlib/spectral.md`. 50 new tests. Required five review passes (RT precondition string interp; `dbToAmp` helper adoption; DC-bin proxy fix; shared seed helper adoption; multi-line init format + class-level `/// - Parameters:` blocks; unused `Foundation` imports). | 3294 |
| 182 | Pattern facade refactor + Demand* rename — `Pattern<T>` split into thin facade + module-internal `_PatternEngine<Element>` protocol; sequence behaviour moved into `SequencePatternEngine<T>`; exposed via `Pattern.sequence(_:repeats:)` static factory. Old `Pattern.init(values:repeats:)` removed. Four demand-rate sources renamed: `DSequence` → `DemandSequence`, `DRandom` → `DemandRandom`, `DTemporalBrownian` → `DemandTemporalBrownian`, `DTemporalTendency` → `DemandTemporalTendency`. `DemandGenerator` protocol name and `Demand.Audio`/`Demand.Control` puller names unchanged. No new types, no new RT behaviour — foundational phase for the 183-190 Pattern + Demand catalogue expansion. One review-fix pass (single-line init in `SequencePatternEngine` reformatted to multi-line). | 4010 |
| 183 | Atomic numeric Pattern sources — seven new `Pattern<Double>` factory methods via `public extension Pattern where T == Double`: `series` (arithmetic), `geometric`, `uniformRandom` (Box-Muller is `gaussian`'s job — `uniformRandom` is `[low, high]` uniform), `brownian` (clamped random walk; `start` defaults to midpoint), `gaussian` (Box-Muller), `cauchy` (inverse-CDF), `beta` (two-Gamma method on `[0, 1]`). Seven new engines in `Sources/Lyrebird/Patterns/Engines/` conform to `_PatternEngine<Double>` (Phase 182). Random engines reuse the file-internal helpers in `Sources/Lyrebird/Distributions/DistributionSampling.swift` (`_sampleUniform` / `_sampleGauss` / `_sampleCauchy` / `_sampleBetaRand`) — same code consumed by `DemandTemporalTendency`. Seeding via `lyrebirdSeedXorshift64(from:)`. `reset()` rewinds only the response counter / position — PRNG state NOT restored (mirrors `DemandRandom` precedent so rhythmic retriggering keeps audible variety). One review-fix pass (4 missing `reset()` tests across the random engines + stale `import Foundation` + missing `isExhausted` assertion + caveman shadowing nit in `Brownian.next()`). 33 new tests across 7 files. | 4042 |
| 184 | Discrete-pool Pattern sources + closure escape hatch — four new generic `Pattern<T>` factory methods on `public extension Pattern`: `shuffle` (Fisher-Yates permute once at init, then cycle; same permutation replays on `reset()` — SC `Pshuf` semantics), `nonRepeatingRandom` (random pick avoiding same *index* as previous; index-vs-value caveat documented for duplicate-value pools), `weightedRandom` (selection proportional to weight via cumulative distribution; init preconditions on equal count, finite non-negative weights, positive sum), `closure` (wraps `() -> T?`, latches once nil is returned). Four new engines in `Sources/Lyrebird/Patterns/Engines/` conform to `_PatternEngine<T>` (Phase 182). `reset()` rewinds counter / position / last-pick / latch state but NOT PRNG seed (mirrors `DemandRandom`). One review-fix pass (missing `!_values.isEmpty` guard in `WeightedRandomPatternEngine.next()`, plus caveman nits — `+Infinity` weights via `$0.isFinite` precondition, documented `u < cumulative[i]` strict-less-than fallthrough). 21 new tests across 4 files. | 4063 |
| 185 | Length/range Pattern modifiers — four new generic `Pattern<T>` factory methods wrapping any upstream pattern: `repeating` (SC `Pn`; replays `count` times with `reset()` between cycles; `-1` infinite; latches if upstream empty after fresh reset), `limit` (SC `Pfin`; emits at most `count` items returned, not calls made; latches if upstream exhausts first; `count >= 0` precondition), `drop` (SC `Pdrop`; lazy drop on first `next()` then pass through; `count >= 0` precondition), `stutter` (SC `Pstutter`; for each source value, emit it n times where n is the next value from a `Pattern<Int>`; `count <= 0` consumes source but emits nothing; latches when either upstream returns nil while pulling a new pair). Four new engines in `Sources/Lyrebird/Patterns/Engines/` conform to `_PatternEngine<T>` (Phase 182). All `reset()` propagate to wrapped upstream pattern(s). One review-fix pass (two blockers — `RepeatPatternEngine.init` missing `precondition(count >= -1)` allowed any negative to silently run forever; `StutterPatternEngine.next()` returned `_currentValue: T?` directly making invariant violations silently propagate as exhaustion — fixed with defensive guard; also added missing `negativeCountSkipsValue` test). 19 new tests across 4 files. | 4081 |
| 186 | Multi-pattern composition — five new factory methods on `public extension Pattern`: `switching` (SC `Pswitch1`; one value per index draw, out-of-range index latches), `concatenate` (sequential play; advances when active sub-pattern returns nil), `roundRobin` (SC `Ppatlace`; ragged patterns drop out individually with dead-slot tracking, latches when all dead), `tuple` (returns `Pattern<[T]>` — different element type from upstream; zips children into size-stable arrays, latches on any child nil), `interleave` (SC `Place`; outer-cycle semantic — each cycle emits one value per sub-list with `outerStep % sublist.count` wrap; empty sub-lists silently dropped; total emit = `lists.count × repeats`; precondition `repeats >= -1`). Five new engines in `Sources/Lyrebird/Patterns/Engines/`; `TuplePatternEngine` declares `Element = [T]` to make the differing return element type explicit. All `reset()` propagate to wrapped upstream pattern(s). Two review-fix passes (pass 1: `RoundRobin` defensive guard off-by-one + `Interleave` multiplication overflow path AND SC `Place` semantic divergence — rewrote engine to match SC exactly, eliminating both issues; pass 2: stale factory doc comment for `Pattern.interleave` still describing old `× maxLen` semantic — rewrote to `× repeats`). 24 new tests across 5 files. | 4105 |
| 187 | Map/filter/transform Pattern catalogue — nine new factory methods across two extension blocks. Generic (`public extension Pattern`): `map` (SC `Pcollect`; result element type can differ from upstream), `filter` (SC `Pselect`; documented spin caveat for infinite-source-never-matching-predicate), `reject` (SC `Preject`; routes `FilterPatternEngine` with negated predicate). Numeric (`public extension Pattern where T == Double`): `accumulate` (SC `Paccum` running sum), `difference` (SC `Pdiff`; first value verbatim, subsequent = deltas), `wrap` (SC `Pwrap`; floor-modulo into half-open `[low, high)` with FP-boundary post-clamp; precondition `high > low`), `clip` (SC `Pclip`; clamps to `[low, high]`; precondition `high >= low`), `round` (SC `Pround`; `.toNearestOrAwayFromZero` mode for SC parity; precondition `step > 0`), `smooth` (SC `Psmooth`; one-pole exponential smoother; coefficient clamped to `[0, 1]`; first sample passes through). Five new engines (Map / Filter / Accumulate / Difference / Smooth); stateless transforms (wrap / clip / round) reuse `MapPatternEngine` via closure. `PatternFactories.swift` gained `import Darwin` for `floor()` (matches existing Math/ convention). Closes the Pattern-side of the 183-187 sweep. One Lyrebird review cycle clean; two caveman fix passes (SC `Pround` parity via `.toNearestOrAwayFromZero` — banker's rounding default diverges at half-ties like `2.5 → 2` vs SC `3`; `Pattern.wrap` FP-boundary post-clamp; misleading `low == high` doc removed; stale rounding-mode comment in test aligned). 28 new tests across 9 files. | 4132 |
| 188 | Atomic numeric `Demand*` (Pattern-engine wrap consolidation) — four `public final class` `DemandGenerator` conformers built as ~30-line thin wrappers around the corresponding Phase 183 module-internal Pattern engines: `DemandSeries` ↔ `SeriesPatternEngine`, `DemandGeometric` ↔ `GeometricPatternEngine`, `DemandUniformRandom` ↔ `UniformRandomPatternEngine`, `DemandBrownian` ↔ `BrownianPatternEngine`. Each holds a `private let _engine: ConcreteEngineType` (Swift access permits private storage of internal types inside public classes) and forwards `nextValue()` / `reset()` / `isExhausted` in one line. Pattern engines were already RT-safe by construction (pure arithmetic, `xorshift64NextRaw`, no allocation / locks / String) so wrapping is bit-equivalent and saves ~120 lines of algorithm duplication. `DemandBrownian` is plain-parameter complement to `DemandTemporalBrownian`; `DemandUniformRandom` complements pool-based `DemandRandom` by drawing continuous values. `reset()` rewinds counter / position but NOT PRNG seed on random variants. Both Lyrebird + caveman reviews clean on first pass; no fixes. 13 new tests across 4 files. | 4145 |
| 189 | Discrete-pool `Demand*` (Pattern-engine wrap consolidation) — three `public final class` `DemandGenerator` conformers wrapping the corresponding Phase 184 module-internal Pattern engines parameterised over `T=Double`: `DemandShuffle` ↔ `ShufflePatternEngine<Double>` (SC `Dshuf`), `DemandNonRepeatingRandom` ↔ `NonRepeatingRandomPatternEngine<Double>` (SC `Dxrand`), `DemandWeightedRandom` ↔ `WeightedRandomPatternEngine<Double>` (SC `Dwrand`). Same thin-wrap pattern as Phase 188 (`private let _engine`, one-line forwards). RT-safety verified: Fisher-Yates at init only, `next()` bodies pure arithmetic + `xorshift64NextRaw` + `_uniform01`, NonRepeating retry-loop bounded for pools ≥ 2, WeightedRandom uses pre-built cumulative array. One review-fix pass (missing `resetClearsExhaustion` test in `DemandShuffleTests`; every Phase 188 peer carries one — added). 12 new tests across 3 files. | 4157 |
| 190 | Composition `Demand*` — closes the 182-190 Pattern + Demand catalogue expansion. Three new `public final class` `DemandGenerator` conformers composing other `DemandGenerator` instances directly (departure from the Phase 188-189 Pattern-engine-wrap strategy — Pattern engines take `Pattern<T>` upstream while the demand side composes other DemandGenerators, so direct impl is the cleaner fit): `DemandStutter` (scalar `Int` count, each upstream value emitted N times, `count >= 1` precondition; deliberately scalar count rather than `DemandGenerator`-driven for zero-allocation RT-path), `DemandSwitch` (SC `Dswitch1`; index source is itself a `DemandGenerator`, values floor-cast via `Int(idxRaw.rounded(.down))` so fractional negatives in `(-1.0, 0.0)` latch rather than silently picking `demands[0]`; latches on index/sub-source/out-of-range), `DemandConcatenate` (sequential play; advances on sub-source nil; while-loop correctly skips immediately-exhausted sub-sources). Each ~30 lines, RT-safe by construction. One review-fix pass (`Int(idxRaw)` truncate-toward-zero vs documented "floor-cast" — switched to `Int(idxRaw.rounded(.down))`, added `negativeFractionalIndexFloorsToLatch` test). 13 new tests across 3 files. **Pattern + Demand catalogue totals**: Pattern side = 30 factories on `Pattern<T>` (1 facade `sequence` + 29 new); Demand side = 14 public `DemandGenerator` types (10 new + 2 pre-existing renames + 2 pre-existing temporal). | 4170 |
| 196 | Engine Ownership + Lifecycle Safety — set-once atomic binding (`SynthesizerBase._engineBinding: Atomic<UInt>` storing engine pointer bit pattern, two-pass CAS-loop with stale-pointer recovery via `EngineLifecycleCoordinator` registry lookup), opt-in two-tier binding on `LyrebirdBuffer` (exclusive CAS + saturated-subtract read-only refcount); new `engine.identifier: UUID`; new internal `EngineLifecycleCoordinator` singleton holding weak refs keyed by UUID under `NSLock` (lifecycle-lock site around `start`/`stop` deferred to Phase 197 host scope); new public `EngineAddError` enum (`boundToOtherEngine(current:prior: UUID?)`, `doubleAdd`, `pendingQueueFull`, `rebuildFailed` reserved); new internal typed `RetainQueue<T>` centralising the 8 RT-side `Unmanaged.passRetained` enqueue sites in `applyEvent`. Breaking pre-ship: `engine.add(_:)` / `add(_:position:)` / `schedule(_:at:)` / `schedule(_:after:)` Bool → throws, mechanical sweep of ~357 call sites across `Sources/`, `Tests/`, `Demos/`; `LyrebirdEventList.addPreMaster` / `addPostMaster` also throws. Partial-state rollback in `LyrebirdEventList._firstEventSetup` and `VoicePool.init` (committed-array + reverse-`engine.remove` on throw; instance-state writes deferred until full success). New `Tests/LyrebirdTests/MultiEngineRegressionTests.swift` (8 tests) covers two-engines-two-threads-1000-segments, cross-engine + double-add throws, remove + re-add, stale-pointer recovery (with documented address-reuse known limit and skip path), buffer read-only share, buffer exclusive blocks cross-engine, buffer unbind saturation. Docs: `synthesis-engine.md` gains Engine Identity + Ownership Binding sections; `multi-core.md` gains Object Ownership Rules subsection with canonical cross-engine wavetable share pattern; `CLAUDE.md` Interface Conventions gains `engine.add` throws entry. Review skills updated to `swift test --no-parallel` (canonical command per memory). Four `/lyrebird_review` cycles (3 with substantive fixes, 4th clean). 15 commits on `phase-196`. | ~4180 |
| 197 | `EngineHost` Multi-Engine Facade — creation-owning `public final class EngineHost` (NSLock-protected role→engine + UUID→role maps); `public enum EngineHostRole` (`.nrtRender`, `.rtOutput(deviceID:)`, `.auxiliary`, `.custom`) — `.rtOutput` device-exclusivity enforced by role-Hashable identity, no separate `_claimedDevices` set; `public enum EngineHostError`; `public struct SynthesisEngineConfig` value carrier (not Sendable — driver field). APIs: `makeEngine(role:config:) throws`, `engine(for:)`/`role(for:)`/`engines`/`roles`/`engineCount` (lookup), `startAll() throws` / `stopAll()` (snapshot-and-iterate-unlocked with rollback on partial-start failure — failing engine captured inside loop's catch, no fragile re-iteration-by-elimination), `adopt(existing:role:) throws` (verifies engine in EngineLifecycleCoordinator). NRT batch render pool: `renderConcurrent(jobs:maxConcurrent:) -> AsyncThrowingStream<NRTResult, Error>` using `withThrowingTaskGroup` + `addTaskUnlessCancelled` seed-and-refill; pool engines inline (not host-registered); `defer { engine.stop() }` post-render; monotonic `DispatchTime` elapsed measurement. New `public struct NRTJob: Sendable` + `public struct NRTResult: Sendable`. **Lock-nesting safety**: host releases `_lock` before touching `EngineLifecycleCoordinator` (which has its own NSLock) — pre-validate under host lock, release, construct/query coordinator outside, re-acquire for commit with second validation. Closes the latent host→coordinator deadlock window. New 220-line `docs/engine/multi-engine-host.md`; `multi-core.md` "See also" updated; `CLAUDE.md` doc-map gains row. New `EngineHostTests.swift` (15 tests) + `MultiEngineRegressionTests.twoEnginesViaHostUniformityContract` proving host path produces identical observable behaviour to direct-ctor. **Five `/lyrebird_review` cycles** (passes 1-4 substantive fixes, pass 5 clean): lock-nesting, snapshot-and-iterate-unlocked, NRTJob numInputChannels silent-discard, magic 44100, false @MainActor doc, missing defer on pre-check (`.duplicateRole` would leak lock causing instance-wide deadlock), stale class-level + role + adopt + multi-engine-host.md docs on `.duplicateDevice` semantics, magic 1_000_000_000.0 literal, `addTaskUnlessCancelled` refill bug, cancellation doc accuracy, NRTJob.numInputChannels doc contradiction, doc-comment merging bug (class Quick Help mis-attributed to file-scope const). 9 commits on `phase-197`. | ~4204 |
| 198 | Host Footgun Cleanup — discharges the eleven non-blocking findings (F1–F11) captured in POST_197_FIXES.md after the five-cycle phase-197 review. **F1 code fix**: `EngineHost.renderConcurrent` outer catch distinguishes caller-initiated cancel from a user `build` closure deliberately throwing `CancellationError` via `Task.isCancelled` guard — caller break ends stream cleanly; build-thrown surfaces as stream throw. Two regression tests cover both paths. **F2–F7 docs**: new "Caveats and footguns" section in `docs/engine/multi-engine-host.md` covering NRT pool memory cost (per-engine working-set table, mobile cap recommendation), in-flight files written after cancel (caller-side `Set<URL>` cleanup pattern), cross-job synth-instance sharing (WRONG vs RIGHT examples), cooperative pool starvation (user-side cap; host-side `DispatchQueue` redesign deferred to Phase 199+), `adopt` TOCTOU benign via ARC takeover. **F6 role doc**: `EngineHostRole.swift` `.rtOutput(deviceID:)` rewrote for macOS/iOS asymmetry — iOS deviceID is host-bookkeeping only because RemoteIO doesn't address devices. **F8 source-break**: dropped `.duplicateDevice(UInt32)` case from `EngineHostError` — had no producer (`.rtOutput` Hashable role discriminates by deviceID directly) and forced consumer switches to handle dead code. **F11 code comment**: `// TODO(phase-future, F11)` at `SynthesisEngine.init` call in `makeEngine` documenting non-throwing-init dependency. **Cleanup**: deleted `POST_197_FIXES.md`. F9 + F10 skipped after evaluation. **Two `/lyrebird_review` cycles** — pass 1 found one blocking (CancellationError-from-`build`-vs-caller-cancel ambiguity), pass 2 clean (review-agent no blocking; caveman LGTM on arch + 3 nits applied: rethrow caught CancellationError instance, `>= 1` result count robustness, `onTermination` fires-on-finished comment). 5 commits on `phase-198`. | ~4205 |
| 204 | Score / MusicXML demo + CLI templates — `Demos/LyrebirdScoreDemo/` NRT-render demo + `ProjectTemplate.score` + `LyrebirdScore.xctemplate`, all driven by the existing Score DSL + MusicXML round-trip (no new core API). | 4214 |
| 222 | `LyrebirdPaths` filesystem conveniences — `projectRoot(from:marker:)` (source-anchored via default-arg `#filePath`, extension-marker match) + sandbox-standard dir accessors; score template writes output via it. | 4516 |
| 223 | `Generate` / `PatternNotes` algorithmic score generators — index-driven + `Pattern`-driven `[ScoreElement]` helpers (no new result-builder type); demo/template/docc examples. | 4526 |
| 224 | `TimeSignature` + `MeterMap` model — `beatGrouping` primitive (compound/simple/additive), segmented meter map + anacrusis; `Score.meterMap` + `Part.meterMap?` polymeter override. Model-only foundation for the beat-timeline group. | 4544 |
| 225 | `ScoreTimeline.fill` + shared `fillRests` — place elements at 0-based quarter beats, auto-fill rests, throw on overlap. Generic helper dedups all three gap-fill sites (Timeline/parser Fraction, MIDI Double); `Fraction: AdditiveArithmetic`. | 4558 |
| 226 | `BeatPosition` musical addressing — `.quarters`/`.beat`/`.bar(_:beat:)`/`.bar(_:division:)` resolved to absolute quarters via `MeterMap`; `beat` = felt/conducted pulse (consistent across 4/4, compound 6/8, additive 3+3+2). Anacrusis + mid-piece meter accumulation; meter-layer naming aligned (`pulse*`→`beat*`, `beatUnitQuarters`→`divisionQuarters`). | 4579 |
| 227 | `ScoreTimeline` overlap policies (`.trap`/`.truncatePrevious`) + multi-voice (`fillVoices` explicit, `fillAutoVoiced` greedy distribution). Double + BeatPosition overloads; `ScoreTimelineError.invalidVoice`. | 4586 |
| 228 | Mid-piece meter-change notation (encoder) — `Score+MusicXMLEncode` consumes `meterMap`: `<time>` on change, per-measure capacity in both loops, `measureCount(atoms:meterMap:)`. Constant-meter byte-identical. Encoder-only (round-trip/anacrusis → 228b). | 4595 |
| 228b | Parser meter round-trip — reads all `<time>` → `MeterMap` segments (sort, bar-1 guarantee, dedupe); `annotateBeams` per-measure capacity. Constant-meter byte-identical. Grouping re-inferred (MusicXML carries no grouping). | 4600 |
| 228c | Anacrusis (pickup) notation + round-trip — `<measure number="0" implicit="yes">` (capacity = `anacrusis`), full bars 1-based, both loops + `measureCount` + beam accounting; parser recovers `anacrusis`. No-anacrusis byte-identical. | 4611 |
| 229 | Polymeter notation — per-part `MeterMap` renders each part against its own meter (independent bar groupings/counts). Tests + `Meter`/`Polymeter`/`Beat timelines` docc + ScoreDemo material samples. Closes the beat-timeline group (223–229). | 4615 |
| 230 | Configurable `SynthesisEngine.maxEventsPerBlock` (was hard-coded 256) — the per-block firing + carry-over look-ahead budget; threaded through `SynthesisEngineConfig`/`EngineHost`. RT-safe drop telemetry (`perBlockEventDropCount`) + one-line console warning drained off-RT (`freeWorker`/`stop()`/NRT post-render). `docs/engine/scheduling.md`. | 5456 |
| 231 | `LyrebirdRoutineContext.onMain(_:)` — construct `@MainActor` synths inside a `@Sendable` routine/task body (result carried out of the main hop via a box; the shared bridge is `Void`-returning). Threading/isolation documented in `ARCHITECTURE.md` §9.2 + linked from GettingStarted / RoutineTask docs; records why `SynthesizerBase.init` cannot be `nonisolated` (MainActorConsumer fixture). | 5460 |
| 232 | Doc sweep + DocC warning ratchet — `scripts/check-docc.sh` gates new DocC warnings against a 62-entry baseline (links pin full signatures; nothing else checks them). Fixed actively-wrong docs (SPSCQueue "rounds up" → traps; nonexistent `schedule(.remove:)`; `Package.swift` docc target), 11 `engine.add` examples missing `try`, and SynthesisEngine init/threading/NRT drift. | 5460 |
| 233 | DocC link repair — 62 → 5 warnings. Score API grew params (`spanners:`, `meterMap:`, `normalType:`, `tie:`, `measureBarlines:`…) and DocC links pin full signatures, so every older link broke. Updated links; converted permanently-ambiguous overloads (`Chord`, `fill`, `dbToAmp`) and `internal` symbols to plain code. 5 article/symbol collisions left (DocC bug, IA decision). | 5460 |
| 234 | DocC catalog to zero warnings — converted 5 filename-colliding articles (`SendTrigger`, `SpectralChain`, `StepSequencer`, `ValueComputable`, `GeneratorInputProvider`) into documentation extensions, so each guide merges into its symbol's page instead of shadowing the API reference. Baseline now empty; the gate is effectively strict. | 5460 |
| 235 | Killed the three hand-copied API mirrors (`SynthesizerProtocol`, `GeneratorProtocol`, `EngineSetup`) — all three had already drifted — replacing them with gate-verified symbol-link tables; removed 75 references to the deleted `LyrebirdFloat`/`LyrebirdInt` types from live docs. | 5460 |
| 236 | Doc-example compile harness — `check-doc-snippets.sh` typechecks doc fences against the real API via `swiftc -typecheck` + `#sourceLocation` (failures point at the .md line). Checked set classified by the compiler, not by hand: 323 of 1457. | 5460 |
| 237 | Doc-example fallout — fixed `GettingStarted`'s flagship example (`doneAction`/`.freeEnclosing` never existed), made entry examples self-contained (coverage 382/1458; the original `try` rot now fails), harness `throws` wrapper + narrowest-first preambles, and pinned `DistributionKind`'s golden values (3 of 4 had drifted). | 5465 |
| 238 | Doc-rot gap pass — extended the DocC gate to `LyrebirdUI` (was entirely unguarded; 0 warnings), implemented the `member` preamble (396 → 426 fences), confirmed zero remaining dead API forms, and established that the residual 1032 fences are continuation fragments no preamble can fix. | 5477 |
| 239 | Doc checks in the review process — `check-doc-impact.sh` reports which docs a diff's public-API changes may have invalidated (validated against the commit that caused the original `engine.add` rot). Reports, never fails; suppresses refs the compile guard already covers; wired into `/lyrebird_review` step 2b. | 5477 |
---
## Upcoming Phases
## Deferred / Future
- **HOA (Higher-Order Ambisonics)**: Deferred until demand is clear. FOA covered by Phases 101 + 102. HOA decoder requires Accelerate `vDSP_mmulD` matrix multiply path; encoder requires real spherical harmonic basis up to chosen order.
- ~~AUv3 plugin export~~ → Phase 104 (split into 104a wrapper infrastructure, 104b Xcode example project + `auval`, 104c MIDI / UI / preset features).
- ~~Runtime source-swapping~~ → Phase 103 (planned; replaces obsolete `declareParameter`-era description with `@LiveParam` slot swap via `ParameterNode._sourceSlot` + `Unmanaged<AnyObject>` SPSC queue).
- **Single-sample feedback / History** (§7.2): `History.Audio` one-sample delay across blocks for zero-latency feedback. Engine-level change to permit designated feedback arcs in the DAG. Blocked on clear design.
- **Hot-reload / live coding** (§9.4): Unblocked by Phase 103 (runtime source-swap). Scope after 103 ships: file-watcher → recompile → swap.
- **CV/Gate Eurorack** (§9.3): Language-side only — `LinLin` scaling constants for ES-8/ES-9 ±5V range. Trivial; do inline when convenient.
- ~~`.demand` rate (pull-based on-demand generators)~~ → Phase 39 ✓
- ~~SIMD optimization pass~~ → Phase 33b ✓
- ~~iOS Support~~ → Phases iOS-1–iOS-4 ✓
File diff suppressed because it is too large Load Diff
+5
View File
@@ -14,6 +14,11 @@ you need to react to RT events from the UI, the existing
`SynthesisEngineListener` lifecycle hook is the only fan-out the engine
exposes today.
> This guide covers user-visible runtime surfaces. For **developer-side**
> inspection — breakpointing a specific voice on the RT thread, reading a
> generator's live output and inner state — see the DocC article `<doc:Debugging>`
> (`Sources/Lyrebird/Lyrebird.docc/Debugging.md`).
---
## Part 1 — `LyrebirdMessage`
+188
View File
@@ -0,0 +1,188 @@
# 1 · Hello, World
The programmer's tradition is a program that prints `Hello, World`. Lyrebird's tradition is a program that makes a **tone**. We'll do both — the print first (to prove your toolchain works), then the sound.
By the end of this page you will have written, built, and run a Swift program that plays a 440 Hz sine wave, and you'll understand every line.
---
## Part 0 — Prove Swift works
Open **Terminal** (Applications → Utilities → Terminal). Check you have a Swift toolchain:
```sh
swift --version
```
You should see something like `Apple Swift version 6.0`. If you get "command not found", install Xcode from the Mac App Store, launch it once, and let it install command-line tools. (Guide 4 covers Xcode in depth.)
Now the classic:
```sh
echo 'print("Hello, World")' > hello.swift
swift hello.swift
```
Swift can run a single file like a script. If you see `Hello, World`, your toolchain is alive. That's the smallest possible Swift program:
```swift
print("Hello, World")
```
- `print(...)` is a function that writes text to the console.
- `"Hello, World"` is a **String** — text in double quotes.
- No `main`, no boilerplate, no semicolons required. Swift keeps simple things simple.
---
## Part 1 — The shape of a Lyrebird program
A Lyrebird program is a normal Swift program that uses the Lyrebird library. Here is the entire "hello tone", which you'll build up in Part 2:
```swift
import Foundation
import LyrebirdSynth
// The engine owns Core Audio and runs the audio graph.
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
// A synthesizer describes the sound.
final class SineTone: SynthesizerBase {
override func build() {
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.2)
let panned: Pan2 = Pan2(input: sine, pan: 0.0)
output(bus: 0, source: panned)
}
}
do {
try engine.start() // open the audio device
try engine.add(SineTone()) // start sounding
print("Playing 440 Hz for 3 seconds…")
Thread.sleep(forTimeInterval: 3.0)
engine.stop() // close the device
print("Done.")
} catch {
print("Something went wrong: \(error)")
}
```
Run that and you hear a sine tone for three seconds. Now let's read it.
---
## Part 2 — Reading it line by line
### The imports
```swift
import Foundation
import LyrebirdSynth
```
`import` pulls in a module — a bundle of code someone else wrote. `Foundation` is Apple's standard utility library (it's where `Thread.sleep` lives). `LyrebirdSynth` is Lyrebird itself.
> **The naming quirk:** the Swift Package product is named `Lyrebird`, but the *module* you import is `LyrebirdSynth`. When you set up a project (guide 4) you'll add a dependency on `Lyrebird` — then write `import LyrebirdSynth`. Right for both, even though they don't match.
### Creating the engine
```swift
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
```
- `let engine: SynthesisEngine = ...` declares a **constant** named `engine`, and the `: SynthesisEngine` is a **type annotation** — it states the type explicitly. `let` means "this name won't be reassigned." (Swift also has `var` for values that change — guide 2.)
- **Every example in this series annotates the type**, even though Swift can infer it. It documents the code for the reader and, in a large project, makes Swift and Xcode compile faster — the compiler doesn't have to work out each type. Guide 2 explains this properly; for now, read `name: Type = value` as "a constant of this type." (Swift also has `var` for values that change — guide 2.)
- `SynthesisEngine(...)` **constructs** an engine. The words before each colon (`blockSize:`, `sampleRate:`, …) are **argument labels** — Swift names its arguments, which makes call sites read like sentences. You can't reorder or omit them.
- `blockSize: 512` — the engine processes audio 512 samples at a time. (Lyrebird caps this at 512.)
- `sampleRate: 48000` — 48,000 samples per second.
- `numOutputChannels: 2` — stereo out. `numInputChannels: 0` — no microphone input.
- `driver: CoreAudioDriver()` — talk to the Mac's audio hardware. (iOS uses a different driver; guide 4.)
### Describing the sound
```swift
final class SineTone: SynthesizerBase {
override func build() {
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.2)
let panned: Pan2 = Pan2(input: sine, pan: 0.0)
output(bus: 0, source: panned)
}
}
```
- `final class SineTone: SynthesizerBase` defines a new type called `SineTone` that **inherits from** `SynthesizerBase`. The colon means "is a." Everything a synthesizer needs is in `SynthesizerBase`; you fill in the blanks. `final` means "no one will subclass this further" (good default; guide 2).
- `override func build()` — `SynthesizerBase` has an empty `build()` method; you **override** it to supply your graph. Lyrebird calls `build()` for you when the synth is added.
- `OscSin.Audio(freq: 440.0, mul: 0.2)` — an audio-rate sine oscillator at 440 Hz, with output multiplied by 0.2 so it isn't harsh. A raw sine at full scale is loud; `mul: 0.2` scales amplitude to 20%.
- `Pan2(input: sine, pan: 0.0)` — takes a mono signal and places it in the stereo field. `pan: 0.0` is dead center; `-1` is hard left, `+1` hard right.
- `output(bus: 0, source: panned)` — send the panned signal to output bus 0. `Pan2` produces two channels, so this fills both left and right. `output(...)` is a helper `SynthesizerBase` gives you.
Notice the **data flow**: `sine` feeds `panned` feeds `output`. Each generator is a node; wiring them by passing one as another's `input:` builds a graph. That's the core idea of Lyrebird.
### Running it
```swift
do {
try engine.start()
try engine.add(SineTone())
print("Playing 440 Hz for 3 seconds…")
Thread.sleep(forTimeInterval: 3.0)
engine.stop()
print("Done.")
} catch {
print("Something went wrong: \(error)")
}
```
- `do { … } catch { … }` is Swift's **error handling**. Some operations can fail; those are marked `try`. If a `try` fails, control jumps to `catch`, where `error` describes what happened. (Guide 2 covers this properly.)
- `try engine.start()` opens the audio device. It can fail (device busy, no output) — hence `try`.
- `try engine.add(SineTone())` constructs a fresh `SineTone` and hands it to the engine. It starts sounding immediately. `add` can also fail (hence `try`), for example if you add the same instance twice.
- `Thread.sleep(forTimeInterval: 3.0)` pauses the program for 3 seconds. Without this, the program would reach the end and exit instantly — you'd hear nothing. Audio runs on its own thread; the main program just needs to stay alive.
- `engine.stop()` closes the device cleanly. (Not `try` — stopping doesn't fail.)
- `\(error)` inside a string is **string interpolation**: it drops the value of `error` into the text.
---
## Part 3 — Make it yours
Change one thing at a time and re-run. This is the fastest way to build intuition:
- **Pitch:** `freq: 440.0` → `freq: 220.0` (an octave down) or `freq: 660.0` (a fifth up).
- **Loudness:** `mul: 0.2` → `mul: 0.4`. Careful with headphones.
- **Position:** `pan: 0.0` → `pan: -1.0` (hard left).
- **Duration:** `forTimeInterval: 3.0` → `10.0`.
- **A different wave:** `OscSin.Audio` → `OscSawtooth.Audio` (bright, buzzy) or `OscSquare.Audio` (hollow). Same `freq:`/`mul:` arguments.
Try two oscillators at once for a chord — a taste of what guide 3 makes systematic:
```swift
override func build() {
let a: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.15) // A4
let e: OscSin.Audio = OscSin.Audio(freq: 660.0, mul: 0.15) // E5
let mix: BinaryOpGenerator = a + e // generators add with +
output(bus: 0, source: Pan2(input: mix, pan: 0.0))
}
```
`a + e` sums two signals — Lyrebird overloads `+` so audio math reads like arithmetic. More of that in guide 3.
---
## What you learned
- A Swift program can be as small as one `print`, or a full Lyrebird patch — same language, same rules.
- `import`, `let` with a **type annotation** (`let x: Type = …`), argument labels, `class`/`override`, and `do`/`try`/`catch` — you've now seen Swift's most common building blocks in context.
- Lyrebird's shape: **engine → synthesizer → generator graph → output bus**.
Next: [Swift Basics & Best Practices](02-swift-basics.md) — the same building blocks, slowed down and explained properly, so you can write your own from scratch.

Some files were not shown because too many files have changed in this diff Show More