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
+15
View File
@@ -0,0 +1,15 @@
{
"originHash" : "6af3e8d671d9174391c6e00ce7b43f22373b57aa528394f7ca9641ede96f515d",
"pins" : [
{
"identity" : "swift-syntax",
"kind" : "remoteSourceControl",
"location" : "https://github.com/swiftlang/swift-syntax",
"state" : {
"revision" : "79e4b74a295b6eb74a8b585e3a39d29e70c1dbd1",
"version" : "603.0.2"
}
}
],
"version" : 3
}
+40
View File
@@ -0,0 +1,40 @@
// swift-tools-version: 6.0
// Package.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Build-time code generator for the interpreted graph-DSL's builtin registry.
//
// Deliberately a SEPARATE package under `Tools/` rather than a target in the
// main package: it depends on swift-syntax, which is large and would otherwise
// be resolved and built on every `swift build` of Lyrebird itself. The shipped
// `LyrebirdGraphDSL` target has no such dependency — it only consumes the Swift
// file this tool emits.
//
// Run via `bash scripts/generate-dsl-registry.sh` (which shells
// `swift run --package-path Tools/DSLRegistryGen`).
import PackageDescription
let package = Package(
name: "DSLRegistryGen",
platforms: [.macOS(.v13)],
dependencies: [
.package(
url: "https://github.com/swiftlang/swift-syntax",
"600.0.0"..<"700.0.0"
),
],
targets: [
.executableTarget(
name: "DSLRegistryGen",
dependencies: [
.product(name: "SwiftSyntax", package: "swift-syntax"),
.product(name: "SwiftParser", package: "swift-syntax"),
],
path: "Sources/DSLRegistryGen"
),
]
)
@@ -0,0 +1,571 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Scans the Lyrebird generator sources and emits the interpreted graph-DSL's
// builtin registry (a `[DSLBuiltin]` table) as Swift source.
//
// Usage:
// DSLRegistryGen --generators <dir> [--constants <dir>] --output <file>
// DSLRegistryGen --generators <dir> [--constants <dir>] --report
// DSLRegistryGen --generators <dir> [--constants <dir>] --output <file> --check
//
// `--report` prints a classification summary; `--check` regenerates in memory
// and exits non-zero if it differs from the committed `--output` file (drift
// guard). Exactly one of `--output` / `--report` is required.
import Foundation
import SwiftParser
import SwiftSyntax
// MARK: - Model
/// A generator init parameter as written in source.
struct ScannedParameter {
let label: String
let typeText: String
let defaultText: String?
/// `true` when the Swift init declares the parameter positionally (`_ value:`).
let isPositional: Bool
/// Type text with optionality + whitespace normalised away.
var normalizedType: String {
var t: String = typeText.trimmingCharacters(in: .whitespaces)
if t.hasSuffix("?") { t.removeLast() }
return t.trimmingCharacters(in: .whitespaces)
}
/// How the DSL supplies this parameter: a signal/number/buffer, or nothing
/// (an enum, URL, bus, closure, array — not expressible in the DSL).
var kind: String {
switch normalizedType {
case "any ValidGeneratorInput": return "signal"
case "Double": return "double"
case "Int": return "int"
case "Float": return "float"
case "LyrebirdBuffer":
// A buffer with a non-nil Swift default can't be expressed (the DSL
// can only omit → nil, or supply a named buffer), so reject rather
// than silently override the default with nil.
if let d: String = defaultText, d.trimmingCharacters(in: .whitespaces) != "nil" {
return "unsupported"
}
return "buffer"
default: return "unsupported"
}
}
var isDSLExpressible: Bool { kind != "unsupported" }
/// `true` for an optional buffer (`LyrebirdBuffer?`), which the DSL may omit.
var isOptionalBuffer: Bool {
kind == "buffer" && typeText.trimmingCharacters(in: .whitespaces).hasSuffix("?")
}
var hasDefault: Bool { defaultText != nil }
}
/// A generator the scanner found, with the init it would be constructed from.
struct ScannedGenerator {
/// DSL name (`OscSin`, `Pan2`).
let name: String
/// `"audio"` or `"control"`.
let rate: String
/// Swift expression that constructs it (`OscSin.Audio`, `Pan2`).
let constructor: String
let parameters: [ScannedParameter]
let sourceFile: String
/// `true` when the class declared more than one usable init — only the first
/// was taken, so a human should confirm the right overload ships.
let hadMultipleInits: Bool
/// Constructible from the DSL only if every parameter is either
/// DSL-expressible or has a default we can omit.
var isConstructible: Bool {
parameters.allSatisfy { $0.isDSLExpressible || $0.hasDefault }
}
/// Parameters the DSL actually exposes.
var exposedParameters: [ScannedParameter] {
parameters.filter { $0.isDSLExpressible }
}
var rejectionReason: String? {
guard !isConstructible else { return nil }
let blocking: [String] = parameters
.filter { !$0.isDSLExpressible && !$0.hasDefault }
.map { "\($0.label): \($0.typeText)" }
return "required non-expressible parameter(s): " + blocking.joined(separator: ", ")
}
}
/// Internal plumbing `Generator` types that conform to `AudioGenerator` but are
/// not musical builtins a DSL author would reach for — excluded from the table.
let excludedGeneratorNames: Set<String> = [
"ConstantGeneratorInput",
]
// MARK: - Constant scanning (top-level, SwiftSyntax)
/// Collects module-level numeric constants (name → literal text): file-scope
/// `let`s and type-member `static let`s. Function-local bindings are ignored, so
/// a local `let minFreq = 1.0` cannot shadow a module constant.
final class ConstantScanner: SyntaxVisitor {
private(set) var constants: [(name: String, value: String)] = []
/// Nesting inside a function / init / closure body — locals here are ignored.
private var funcDepth: Int = 0
/// Nesting inside a type (class/struct/enum/extension) — a member here counts
/// only when `static`.
private var typeDepth: Int = 0
override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind { funcDepth += 1; return .visitChildren }
override func visitPost(_ node: FunctionDeclSyntax) { funcDepth -= 1 }
override func visit(_ node: InitializerDeclSyntax) -> SyntaxVisitorContinueKind { funcDepth += 1; return .visitChildren }
override func visitPost(_ node: InitializerDeclSyntax) { funcDepth -= 1 }
override func visit(_ node: ClosureExprSyntax) -> SyntaxVisitorContinueKind { funcDepth += 1; return .visitChildren }
override func visitPost(_ node: ClosureExprSyntax) { funcDepth -= 1 }
override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind { typeDepth += 1; return .visitChildren }
override func visitPost(_ node: ClassDeclSyntax) { typeDepth -= 1 }
override func visit(_ node: StructDeclSyntax) -> SyntaxVisitorContinueKind { typeDepth += 1; return .visitChildren }
override func visitPost(_ node: StructDeclSyntax) { typeDepth -= 1 }
override func visit(_ node: EnumDeclSyntax) -> SyntaxVisitorContinueKind { typeDepth += 1; return .visitChildren }
override func visitPost(_ node: EnumDeclSyntax) { typeDepth -= 1 }
override func visit(_ node: ExtensionDeclSyntax) -> SyntaxVisitorContinueKind { typeDepth += 1; return .visitChildren }
override func visitPost(_ node: ExtensionDeclSyntax) { typeDepth -= 1 }
override func visit(_ node: VariableDeclSyntax) -> SyntaxVisitorContinueKind {
// Never a function-local. In a type, only `static` members qualify.
guard funcDepth == 0 else { return .skipChildren }
let isStatic: Bool = node.modifiers.contains { $0.name.text == "static" }
guard typeDepth == 0 || isStatic else { return .skipChildren }
for binding: PatternBindingSyntax in node.bindings {
// `trimmedDescription` drops leading/trailing trivia, so a trailing
// `// comment` after the literal doesn't defeat the literal check.
guard let name: String = node.identifierName(binding),
let typeText: String = binding.typeAnnotation?.type.trimmedDescription,
typeText == "Double" || typeText == "Int" || typeText == "Float",
let value: String = binding.initializer?.value.trimmedDescription,
isNumericLiteral(value) else { continue }
constants.append((name, value))
}
return .skipChildren
}
private func isNumericLiteral(_ s: String) -> Bool {
s.range(of: #"^-?[0-9][0-9_]*(\.[0-9_]+)?([eE][-+]?[0-9]+)?$"#,
options: .regularExpression) != nil
}
}
extension VariableDeclSyntax {
func identifierName(_ binding: PatternBindingSyntax) -> String? {
binding.pattern.as(IdentifierPatternSyntax.self)?.identifier.text
}
}
/// Scan every file for file-scope numeric constants. Same name with different
/// values across files is a genuine ambiguity — recorded in `collisions` and
/// dropped from the table rather than silently overwritten.
func scanNumericConstants(files: [URL]) -> (table: [String: String], collisions: [String]) {
var table: [String: String] = [:]
var collisions: Set<String> = Set<String>()
for file: URL in files {
guard let text: String = try? String(contentsOf: file, encoding: .utf8) else { continue }
let tree: SourceFileSyntax = Parser.parse(source: text)
let scanner: ConstantScanner = ConstantScanner(viewMode: .sourceAccurate)
scanner.walk(tree)
for c: (name: String, value: String) in scanner.constants {
if let existing: String = table[c.name], existing != c.value {
collisions.insert(c.name)
} else {
table[c.name] = c.value
}
}
}
for name: String in collisions { table.removeValue(forKey: name) }
return (table, collisions.sorted())
}
// MARK: - Generator scanning
/// Collects generator declarations from one parsed file. Handles both shapes:
/// 1. `public enum Osc… { public final class Audio: … }` → `Osc….Audio`
/// 2. `public final class Pan2: GeneratorBase, AudioGenerator` → `Pan2`
final class GeneratorScanner: SyntaxVisitor {
private(set) var found: [ScannedGenerator] = []
private(set) var noDeclaredInit: [String] = []
/// Classes conforming to both generator protocols on one declaration — none
/// today, but flagged so a future one surfaces rather than being silently
/// classified audio-only.
private(set) var bothRateClasses: [String] = []
private let fileName: String
private var enumStack: [String] = []
init(fileName: String) {
self.fileName = fileName
super.init(viewMode: .sourceAccurate)
}
override func visit(_ node: EnumDeclSyntax) -> SyntaxVisitorContinueKind {
enumStack.append(node.name.text.trimmingCharacters(in: .whitespaces))
return .visitChildren
}
override func visitPost(_ node: EnumDeclSyntax) {
if !enumStack.isEmpty { enumStack.removeLast() }
}
override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind {
let className: String = node.name.text.trimmingCharacters(in: .whitespaces)
let isAudio: Bool = conforms(node, to: "AudioGenerator")
let isControl: Bool = conforms(node, to: "ControlGenerator")
if isAudio, isControl { bothRateClasses.append(className) }
let rate: String
if isAudio {
rate = "audio"
} else if isControl {
rate = "control"
} else {
return .visitChildren
}
let dslName: String
let constructor: String
if (className == "Audio" || className == "Control"), !enumStack.isEmpty {
// DSL name is the enclosing enum path joined (Mouse.X → "MouseX"),
// which for the common single-level case is just the owner (OscSin).
// Constructor is the full nesting path so a doubly-nested type
// (Mouse.X.Control) constructs correctly.
dslName = enumStack.joined()
constructor = (enumStack + [className]).joined(separator: ".")
} else if enumStack.isEmpty, !className.hasPrefix("_") {
dslName = className
constructor = className
} else {
return .visitChildren
}
guard !excludedGeneratorNames.contains(dslName) else { return .visitChildren }
let usableInits: [InitializerDeclSyntax] = designatedInits(in: node)
guard let initDecl: InitializerDeclSyntax = usableInits.first else {
noDeclaredInit.append("\(dslName) (\(fileName))")
return .visitChildren
}
let params: [ScannedParameter] = initDecl.signature.parameterClause.parameters.map { p in
let label: String = (p.firstName.text == "_"
? (p.secondName?.text ?? p.firstName.text)
: p.firstName.text)
.trimmingCharacters(in: .whitespaces)
return ScannedParameter(
label: label,
typeText: p.type.description.trimmingCharacters(in: .whitespacesAndNewlines),
defaultText: p.defaultValue?.value.description
.trimmingCharacters(in: .whitespacesAndNewlines),
isPositional: p.firstName.text == "_"
)
}
found.append(ScannedGenerator(
name: dslName,
rate: rate,
constructor: constructor,
parameters: params,
sourceFile: fileName,
hadMultipleInits: usableInits.count > 1
))
return .visitChildren
}
private func conforms(_ node: ClassDeclSyntax, to proto: String) -> Bool {
guard let inheritance: InheritanceClauseSyntax = node.inheritanceClause else { return false }
return inheritance.inheritedTypes.contains { inherited in
inherited.type.description.trimmingCharacters(in: .whitespaces) == proto
}
}
/// The class's usable designated inits — `public`/`internal`, not
/// `convenience`, not `private`, not failable. (The DSL constructs via the
/// designated init; a convenience or failable overload would mislead.)
private func designatedInits(in node: ClassDeclSyntax) -> [InitializerDeclSyntax] {
node.memberBlock.members.compactMap { member in
guard let initDecl: InitializerDeclSyntax = member.decl.as(InitializerDeclSyntax.self)
else { return nil }
if initDecl.optionalMark != nil { return nil } // failable
let modifiers: [String] = initDecl.modifiers.map { $0.name.text }
if modifiers.contains("convenience") || modifiers.contains("private") { return nil }
return initDecl
}
}
}
// MARK: - Driver: arguments + scanning
func parseArgument(_ name: String) -> String? {
let args: [String] = CommandLine.arguments
guard let i: Int = args.firstIndex(of: name), i + 1 < args.count else { return nil }
let value: String = args[i + 1]
// A following flag is not this flag's value.
return value.hasPrefix("--") ? nil : value
}
func fail(_ message: String) -> Never {
FileHandle.standardError.write(Data("DSLRegistryGen: \(message)\n".utf8))
exit(2)
}
func swiftFiles(under root: URL) -> [URL] {
guard let e: FileManager.DirectoryEnumerator = FileManager.default.enumerator(
at: root, includingPropertiesForKeys: nil
) else { return [] }
var out: [URL] = []
for case let url as URL in e where url.pathExtension == "swift" {
out.append(url)
}
return out.sorted { $0.path < $1.path }
}
guard let generatorsPath: String = parseArgument("--generators") else {
fail("usage: --generators <dir> [--constants <dir>] (--output <file> [--check] | --report)")
}
let wantReport: Bool = CommandLine.arguments.contains("--report")
let outputPath: String? = parseArgument("--output")
let wantCheck: Bool = CommandLine.arguments.contains("--check")
guard wantReport || outputPath != nil else {
fail("no mode given — pass --output <file> or --report")
}
let generatorFiles: [URL] = swiftFiles(under: URL(fileURLWithPath: generatorsPath))
let constantsPath: String = parseArgument("--constants") ?? generatorsPath
let constantFiles: [URL] = constantsPath == generatorsPath
? generatorFiles
: swiftFiles(under: URL(fileURLWithPath: constantsPath))
let (constants, constantCollisions): ([String: String], [String]) = scanNumericConstants(files: constantFiles)
var all: [ScannedGenerator] = []
var missingInit: [String] = []
var bothRateClasses: [String] = []
for file: URL in generatorFiles {
guard let text: String = try? String(contentsOf: file, encoding: .utf8) else { continue }
let tree: SourceFileSyntax = Parser.parse(source: text)
let scanner: GeneratorScanner = GeneratorScanner(fileName: file.lastPathComponent)
scanner.walk(tree)
all.append(contentsOf: scanner.found)
missingInit.append(contentsOf: scanner.noDeclaredInit)
bothRateClasses.append(contentsOf: scanner.bothRateClasses)
}
let constructible: [ScannedGenerator] = all.filter { $0.isConstructible }
let rejected: [ScannedGenerator] = all.filter { !$0.isConstructible }
// MARK: - Emitter
/// Default expressions the emitter could not reduce to a literal (so the
/// parameter became required in the DSL instead of defaulted). Single-threaded
/// tool; the isolation opt-out is safe.
nonisolated(unsafe) var unresolvedDefaults: Set<String> = Set<String>()
/// A default's text reduced to something the generated module can compile:
/// a literal as-is, a known file-scope numeric constant inlined, otherwise `nil`.
func resolvedDefault(_ text: String) -> String? {
let t: String = text.trimmingCharacters(in: .whitespaces)
if t.range(of: #"^-?[0-9][0-9_]*(\.[0-9_]+)?([eE][-+]?[0-9]+)?$"#,
options: .regularExpression) != nil {
return t
}
if let literal: String = constants[t] { return literal }
unresolvedDefaults.insert(t)
return nil
}
func effectiveHasDefault(_ p: ScannedParameter) -> Bool {
// An optional buffer is omittable even though its `nil` default isn't a
// numeric literal we inline.
if p.isOptionalBuffer { return true }
return p.defaultText.flatMap { resolvedDefault($0) } != nil
}
/// Reject a generator whose emitted call would drop a positional argument out
/// from under a later positional one (a defaulted non-expressible positional
/// param followed by an exposed positional). None exist in-tree today; this
/// guards against a future addition silently mis-binding.
func hasUnsafePositionalDrop(_ g: ScannedGenerator) -> Bool {
var droppedPositional: Bool = false
for p: ScannedParameter in g.parameters {
let exposed: Bool = p.isDSLExpressible
if !exposed {
if p.isPositional { droppedPositional = true }
} else if p.isPositional, droppedPositional {
return true
}
}
return false
}
func argumentExpression(_ p: ScannedParameter, builtin: String) -> String {
let key: String = "args[\"\(p.label)\"]"
let where_: String = "\"\(builtin)\", \"\(p.label)\""
// Buffers are resources. An optional buffer (`LyrebirdBuffer?`) may be
// omitted (Swift init default applies); a required one must be supplied.
if p.kind == "buffer" {
let fn: String = p.isOptionalBuffer ? "optionalBuffer" : "buffer"
return "try DSLArgument.\(fn)(\(key), \(where_))"
}
// Signal / number: pass the DSLValue through the coercion, supplying the
// Swift init's default (as a `.signal`) for an optional parameter.
let helper: String = (p.kind == "signal") ? "input" : p.kind
let def: String? = p.defaultText.flatMap { resolvedDefault($0) }
let source: String = def.map { "\(key) ?? .signal(\($0))" } ?? key
return "try DSLArgument.\(helper)(\(source), \(where_))"
}
func emitRegistry(_ generators: [ScannedGenerator]) -> String {
var out: String = """
// GeneratedDSLRegistry.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// GENERATED FILE — do not edit by hand.
// Produced by Tools/DSLRegistryGen from the generator sources.
// Regenerate with: bash scripts/generate-dsl-registry.sh
import LyrebirdSynth
extension DSLBuiltinRegistry {
/// Every generator the DSL can construct, emitted from the generator
/// sources. A generator appears here when all of its init parameters are
/// either DSL-expressible (a signal/number) or have a Swift default that
/// can be omitted.
static let generated: [DSLBuiltin] = [\n
"""
for g: ScannedGenerator in generators {
let exposed: [ScannedParameter] = g.exposedParameters
let paramList: String = exposed
.map { " DSLParameter(label: \"\($0.label)\", hasDefault: \(effectiveHasDefault($0))),\n" }
.joined()
let callArgs: String = exposed
.map { p in
let expr: String = argumentExpression(p, builtin: g.name)
let prefix: String = p.isPositional ? "" : "\(p.label): "
return " \(prefix)\(expr)"
}
.joined(separator: ",\n")
// Empty-argument constructors emit `Foo()`; otherwise a multi-line call.
let makeBody: String = exposed.isEmpty
? " \(g.constructor)()"
: " \(g.constructor)(\n\(callArgs)\n )"
out += """
DSLBuiltin(
name: "\(g.name)",
rate: .\(g.rate),
parameters: [
\(paramList) ],
make: { args in
\(makeBody)
}
),\n
"""
}
out += """
]
}
"""
return out
}
// De-duplicate by (DSL name, rate) (report collisions), stable order.
var seen: Set<String> = Set<String>()
var nameCollisions: [String] = []
let unique: [ScannedGenerator] = constructible
.sorted { ($0.name, $0.rate) < ($1.name, $1.rate) }
.filter { g in
if seen.insert("\(g.name)|\(g.rate)").inserted { return true }
nameCollisions.append("\(g.name) (\(g.rate))")
return false
}
let unsafeDrops: [ScannedGenerator] = unique.filter { hasUnsafePositionalDrop($0) }
let emittable: [ScannedGenerator] = unique.filter { !hasUnsafePositionalDrop($0) }
let source: String = emitRegistry(emittable) // also populates unresolvedDefaults
// MARK: - Modes
if let outputPath: String = outputPath {
if wantCheck {
let existing: String = (try? String(contentsOf: URL(fileURLWithPath: outputPath), encoding: .utf8)) ?? ""
if existing != source {
fail("registry is stale — run scripts/generate-dsl-registry.sh and commit \(outputPath)")
}
print("OK: DSL registry is up to date (\(emittable.count) builtins).")
} else {
do {
try source.write(toFile: outputPath, atomically: true, encoding: .utf8)
print("emitted \(emittable.count) builtins → \(outputPath)")
} catch {
fail("write failed: \(error)")
}
}
}
// Surface everything the human should know, regardless of mode.
func warn(_ label: String, _ items: [String]) {
guard !items.isEmpty else { return }
FileHandle.standardError.write(Data("warning: \(label): \(items.joined(separator: ", "))\n".utf8))
}
warn("dropped for unsafe positional argument order", unsafeDrops.map { $0.name })
warn("DSL-name collisions (kept first)", nameCollisions)
warn("ambiguous multi-init classes (first init used)",
emittable.filter { $0.hadMultipleInits }.map { $0.name })
warn("constant-name collisions (default dropped, param made required)", constantCollisions)
warn("classes conforming to both generator protocols (classified audio)", bothRateClasses)
/// The resource category blocking a rejected generator, for the surface map
/// that informs how the language will name non-numeric resources.
func blockingResourceKind(_ g: ScannedGenerator) -> String {
let types: [String] = g.parameters
.filter { !$0.isDSLExpressible && !$0.hasDefault }
.map { $0.typeText }
func any(_ needle: String) -> Bool { types.contains { $0.contains(needle) } }
if any("LyrebirdBuffer") { return "buffer" }
if any("ValidBus") || any("AudioBus") || any("ControlBus") { return "bus" }
if any("URL") { return "url" }
if types.contains(where: { $0.contains("->") || $0.contains("@escaping") }) { return "closure" }
return "other (\(types.joined(separator: ", ")))"
}
if wantReport {
let audio: Int = emittable.filter { $0.rate == "audio" }.count
let control: Int = emittable.filter { $0.rate == "control" }.count
print("scanned generator files: \(generatorFiles.count)")
print("generator classes (A+C): \(all.count)")
print("DSL-constructible: \(constructible.count)")
print("emitted (unique): \(emittable.count) (audio \(audio), control \(control))")
print("rejected (non-expressible required param): \(rejected.count)")
print("no declared init: \(missingInit.count)")
print("multi-init (first used): \(emittable.filter { $0.hadMultipleInits }.count)")
print("file-scope constants: \(constants.count)")
print("unresolved default exprs: \(unresolvedDefaults.count)")
print("")
print("— rejected by resource kind (the surface the language must reach) —")
var byKind: [String: [String]] = [:]
for g: ScannedGenerator in rejected {
byKind[blockingResourceKind(g), default: []].append("\(g.name)(\(g.rate))")
}
for kind: String in byKind.keys.sorted() {
let names: [String] = byKind[kind] ?? []
print(" \(kind): \(names.count) [\(names.prefix(6).joined(separator: ", "))\(names.count > 6 ? ", …" : "")]")
}
if !unresolvedDefaults.isEmpty {
print("")
print("— unresolved defaults (param made required) —")
for d: String in unresolvedDefaults.sorted().prefix(20) { print(" \(d)") }
}
}