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
@@ -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"))
}
}