v1.4.0 release: live-coding scratch editor, interpreted Graph DSL, ClosureSynthesizer + SampleLoop

This commit is contained in:
2026-07-20 10:02:49 -07:00
parent 560724d116
commit 38d2107f64
104 changed files with 14471 additions and 105 deletions
@@ -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