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
+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