Files
Lyrebird/docs/tooling/graph-dsl-design.md

179 lines
18 KiB
Markdown

# LC-8 — Interpreted Generator-Graph DSL (Design)
**Status:** design (gate before implementation). This document is the roadmap-required design gate for LC-8.
## Why
The compiled scratch path (LC-1…LC-7) hit its structural ceilings: Swift has no in-process JIT, so a snippet compile floors at ~0.1 s warm (LC-5), and its dylibs cannot be safely unloaded (LC-7 — `dlclose` leaves dangling Swift conformance-cache pointers). Both are inherent to shelling out to `swiftc`.
An **interpreted graph DSL** — parse a small language at runtime and build `Generator` graphs directly, no `swiftc` — sidesteps all of it:
- **Instant** (<~5 ms): no compile, no `dlopen`, no link.
- **No leak, no dylibs, no sandbox-disable:** nothing is mapped; runs in a sandboxed App-Store app.
- **Cross-platform:** pure Swift over core types → runs on **iOS/iPad** (a bonus, deprioritized as a driver).
It does *not* replace the Swift path. Swift stays for full-power work (new `Generator` types, arbitrary control flow). The DSL is the fast, safe, restricted lane for the live-coding loop — "change a number, hear it now" — which is exactly what the vs-SuperCollider assessment flagged as the gap.
## Goals / non-goals
**In scope (v1):**
- Construct `Generator` graphs: named generator calls with positional + named args, nesting, and the `+ - * /` operators.
- Numeric literals, unit helpers (Hz/dB/beats as plain numbers to start).
- Bind a graph to output or to a **named slot** (reuse LC-3/LC-4 `play(slot:)` + on-beat swap).
- A small set of `Pattern`/`Demand` builders and live-param `set`/`ramp` (LC-3-adjacent) — phased.
- Parse/build errors surfaced as `Diagnostic`s (reuse the existing type), mapped to source ranges.
**Out of scope (v1), by design:**
- Arbitrary control flow (loops, conditionals, functions), user-defined types, imports.
- Defining new `Generator` types (that is the Swift path's job).
- Full Swift expression semantics. This is a graph-description language, not Swift.
## The core constraint: there is no generator registry
Lyrebird has **329 generator files** and **no runtime registry** — generators are Swift `GeneratorEnum` types (`enum OscSin { class Audio; class Control }`) with heterogeneous inits (`OscSin.Audio(freq:phase:interpolation:table:mul:add:)` — note `TableInterpolation` and `LyrebirdBuffer?` params that a numeric DSL can't express). Swift has no runtime reflection to enumerate types or call an init by name. So the roadmap's "auto-generate the builtin table from the `GeneratorEnum` registry" **has no registry to reflect** — the DSL must *introduce* one.
Two ways to populate it:
1. **Hand-written curated registry (recommended for v1).** A table of `DSLBuiltin` entries, each: a DSL name, an arg spec (which named/positional params it accepts, defaults), and a `([Arg]) throws -> any ValidGeneratorInput` constructor closure that calls the real Swift init. Start with ~40 high-value generators (core oscillators, noise, the common filters, envelopes, `Pan2`, math ops, a few effects). Explicit, reviewable, RT-safe by construction, and it *documents* the DSL surface. Cost: hand-maintained; new generators don't appear for free.
2. **Build-time code-gen (future).** A script parses generator `init` signatures and emits the registry, filtering to DSL-expressible param types (numeric / `ValidGeneratorInput`). Automated, but needs a Swift-source parser and a policy for non-numeric params. Defer until the hand-written set proves the language; revisit as **LC-8-codegen**.
Recommendation: **ship v1 on the hand-written registry**, designed so a code-gen backend can later populate the same `DSLBuiltin` table without touching the parser/builder.
### Decision (approved)
- **Code-gen first.** Build the registry-generation tooling before shipping the language. The generator emits the same `DSLBuiltin` table a hand-written registry would; the parser/builder consume it either way.
- **Module:** new cross-platform **`LyrebirdGraphDSL`** target in the **main package** (depends on `LyrebirdSynth`), so iOS gets the interpreter for free. The code-gen tool is a **separate executable target** (`LyrebirdDSLRegistryGen`) that depends on `swift-syntax`; the shipped `LyrebirdGraphDSL` target does **not** depend on `swift-syntax`. The generator writes `Sources/LyrebirdGraphDSL/Generated/…` and is run manually / in CI (a `scripts/generate-dsl-registry.sh` ratchet), with its output committed — the same pattern as the other repo guard tools.
### Code-gen challenge: inheritance resolution
Generator DSL params frequently live on a **base class**, not the leaf. `OscSin.Audio.init(freq:phase:interpolation:table:mul:add:)` forwards straight to `super.init(...)` on `OscillatorBase`; the `NoiseBase` / filter-helper families do the same. A pure-syntax parser (SwiftSyntax has no type/inheritance resolution) sees only the leaf `init` and its `super.init` call, not the base's declared params + defaults. Options, cheapest first:
1. **Emit from the leaf `init` as written** — works for self-contained generators; for forwarding leaves, follow the `super.init(...)` *call arguments* (the labels are present at the call site) and pair them against the base `init` found by resolving the superclass name across the parsed file set. Feasible because the base classes (`OscillatorBase`, `NoiseBase`, …) are a small, enumerable set in-tree.
2. **Curated overrides** for the handful of families whose base resolution is ambiguous — a small hand-maintained supplement merged into the generated table.
**Outcome (LC-8a):** in practice this problem does **not** occur. The scanner reads each leaf class's own declared `init`, and running it across the whole tree found **0** generator classes whose Audio class declares no init of its own — every leaf re-declares its full parameter list. So no `super.init` resolution is implemented; a class with no declared init would be *reported* (bucketed as `noDeclaredInit`) for curation rather than guessed at, but none exist today. The resolution strategy above is kept only as the plan if that ever changes.
## The surface, mapped (LC-8 wider-surface pass)
Sequencing the code-gen's *breadth* before the language, so the parser is designed against the real surface rather than retrofitted. Current scan:
| | count |
|---|---|
| generator classes (Audio + Control) | 338 |
| **emitted builtins** | **286** (165 audio, 121 control) |
| rejected (required non-numeric resource) | 52 |
| Control classes with no own init (params on a base) | 11 — *reported, not guessed* |
### Rates
Both `.Audio` and `.Control` variants are emitted. A ``DSLBuiltin`` carries a ``DSLRate``; the registry keys by `(name, rate)`. `DSLBuiltinRegistry.lookup(name, rate:)` defaults to `.audio`; `rates(of:)` reports what a name offers. How the *language* selects rate (shipped: an explicit `.Audio`/`.Control` suffix matching `OscSin.Audio`/`.Control`, defaulting to audio-preferred) is an 8b concern — the registry already carries both.
**Naming.** A DSL name is the enclosing enum path *joined* — `OscSin.Audio` → `OscSin` (single level), and a doubly-nested `Mouse.X.Control` → `MouseX` (not the bare, collision-prone `X`). The constructor uses the full dotted path (`Mouse.X.Control`). All builtin names are therefore flat, unqualified identifiers — good for the parser, which needs no dotted-name grammar. **Scanner limitation:** a generator's `AudioGenerator`/`ControlGenerator` conformance must be spelled on the class declaration itself; one inherited only through a `_Base` would be skipped (absent, never mis-emitted). This matches the in-tree convention; a class conforming to *both* protocols is flagged by `--report`.
### Rejected → the resource value-kind
The 52 rejected builtins cluster by the non-numeric resource they need. This is the map the language must design a value-kind against **before** the parser is written:
- **buffer** (20): `LyrebirdBuffer` — `PlayBuffer`, `BufferRead`, `RecordBuffer`, granular. The dominant, musical case.
- **bus** (7): `In` / `Out` / `MixIn` / `ReplaceOut` — signal routing.
- **url** (2): `DiskIn` / `DiskOut`.
- **closure / demand / envelope / spectral / generator-array** (the rest): `SampleLoop`, `Demand`, `EnvelopeGen`, `AdditiveSynthesizer`, ambisonic decoders, `Select` — each needs a first-class DSL value that isn't a number or a signal.
**Design implication for the parser:** a DSL argument is not just *number | signal*. It must also admit a **resource reference** — a bare identifier the host resolves (`PlayBuffer(buffer: kick)` where the host registered `kick` → `LyrebirdBuffer`). This means:
1. The `DSLBuiltin.make` contract carries `[String: DSLValue]` (signal or resource), and a bare-identifier `DSLExpr.reference` is resolved through a `DSLResourceResolver` the host supplies — **shipped**; the buffer builtins are emitted.
2. The classifier already categorises each rejected builtin by resource kind (`--report`), so the emit pass is a matter of teaching the emitter one `ctx.buffer("label")` / `ctx.bus(...)` form per kind, gated per builtin.
Bus routing and the graph output are partly handled outside the DSL already (the built graph is wrapped in `ClosureSynthesizer`, which owns the `Out`), so `Out`/`In` may stay host-level rather than DSL builtins — a call to make when the language lands.
## Language sketch
```
# comment
bass = OscSaw(freq: 55, mul: 0.2) >> LPF(freq: 400, q: 0.7) # named slot "bass"
Pan2(input: OscSin(440) * 0.1, pan: 0) # anonymous output
lead = Pan2(OscSin(freq: 440) + OscSaw(220) * 0.5, pan: 0)
```
- **Calls:** `Name(arg, name: arg, …)`. Positional args fill the builtin's declared positional slots; named args match by label. Unknown labels / arity errors → diagnostic.
- **Operators:** `+ - * /` (generator math, existing `BinaryOpGenerator`), plus optionally `>>` sugar for "feed into" (`x >> LPF(…)` ⇒ `LPF(input: x, …)`). `*`/`/` precedence over `+`/`-`; parens override.
- **Values:** number literals (int/float), nested calls, operator expressions. (Strings/buffers deferred.)
- **Binding:** `name = expr` → `context.play(slot: "name") { expr }`; a bare `expr` → `context.play { expr }`. One statement per line (newline-terminated); `#` comments.
- **Live params / patterns / clock:** phased in (see below), e.g. `set bass.freq 220`, `ramp bass.freq 440 over: 2`, `seq(1, 3, 5)`.
Grammar (v1 core, EBNF-ish):
```
program = { line } ;
line = [ statement ] [ comment ] newline ;
statement = ( ident "=" expr ) | expr ;
expr = term { ("+"|"-") term } ;
term = factor { ("*"|"/"|">>") factor } ;
factor = number | call | "(" expr ")" ;
call = ident "(" [ args ] ")" ;
args = arg { "," arg } ;
arg = [ ident ":" ] expr ;
```
### Status (LC-8b — language shipped)
Lexer → parser → AST → `DSLGraphBuilder` → `DSLInterpreter.evaluate(source) -> [DSLOutput]` is implemented and renders. Numeric subexpressions and unary minus are **constant-folded** at parse time, so a numeric-literal-only parameter (a `Double` init param) accepts `-0.5` / `220 * 2`. The parser is **depth-capped** (throws `DSLParseError.tooDeeplyNested` rather than overflowing on pathological/generated input). A parameter bound twice is a `DSLBuildError.duplicateArgument`, not a silent overwrite.
**Shipped since:** explicit control-rate selection via an `.Audio`/`.Control` call suffix (`OscSin.Control(freq: 4, …)` — the exact Swift nested-class names, so it pastes into a project unchanged); without a suffix `DSLGraphBuilder.resolve` prefers audio and falls back to a name's sole rate (so control-only generators like `MouseX` are reachable). **Buffer resources** shipped too: a `DSLValue` (`.signal | .buffer`), a `DSLResourceResolver` (host name→`LyrebirdBuffer`), a bare-identifier `DSLExpr.reference`, and the `make`-context change (`DSLBuiltin.make` takes `[String: DSLValue]`; buffer builtins emitted — registry 304). `DSLInterpreter.evaluate(_:resources:)` resolves references; bus/URL/closure/demand builtins remain intentionally out of DSL scope (routing is host-level; closures are the Swift path). The remaining LC-8 work is editor integration (8d).
### Swift paste-compatibility
A design goal: a DSL **graph expression** should be valid Lyrebird Swift, so a user who likes what they made in the live editor can paste it into a project with minimal edits — and, crucially, without learning that the *same generator* is spelled differently in the two places. Concretely:
- Generator names, parameter labels, `+ - * /`, nesting, and number literals are already identical to Swift (the labels come straight from the Swift inits via the code-gen).
- The rate suffix is the **exact Swift nested-class name** — `OscSin.Control(freq: 4)`, not a lowercase `.control` or an SC-style `.kr`. So `OscSin.Control(freq: 4) * 0.1` reads and constructs identically in the DSL and in a `build()`.
What still differs is only the **wrapping**, i.e. the "context block" the user already expects to change:
| DSL | Lyrebird Swift |
|-----|----------------|
| `OscSin.Audio(freq: 440) * 0.1` | `output(bus: 0, source: OscSin.Audio(freq: 440) * 0.1)` |
| `bass = OscSaw.Audio(freq: 55) * 0.2` | `let bass = OscSaw.Audio(freq: 55) * 0.2` (+ `output(...)`) |
The bare `OscSin(freq: 440)` (no rate) is a DSL shorthand for the audio variant and is *not* valid Swift; the explicit `.Audio` form is the paste-compatible one. The editor's onboarding should steer toward the explicit form for anything a user may want to keep.
## Architecture
```
source ──► Lexer ──► Parser ──► AST ──► GraphBuilder ──► any ValidGeneratorInput
│ (registry-driven)
└─► ClosureSynthesizer ──► LiveSession.play / play(slot:)
```
- **Lexer / Parser / AST:** pure Swift, no deps. AST nodes: `numberLiteral`, `call(name, [arg])`, `binaryOp(op, lhs, rhs)`, `assignment(name, expr)`. UTF-16 source ranges on every node (reuse for diagnostics + future editor hooks).
- **GraphBuilder:** walks the AST; for a `call`, looks up the `DSLBuiltin` by name, validates/binds args, invokes its constructor closure → `any ValidGeneratorInput`; for `binaryOp`, applies the existing generator operator; produces the graph. Constructs on the main thread (same as any graph build — no RT concern; graph-copy-per-instance still holds via `ClosureSynthesizer`).
- **Output adapter:** the built graph is a `() -> any ValidGeneratorInput` closure fed to `ClosureSynthesizer` (LC-2), then `play` / `play(slot:)` (LC-3) with on-beat swap (LC-4). **All of the slot/quantize/reset machinery is reused unchanged** — the DSL only replaces the "produce a graph" front-end.
- **Errors:** parse + build failures produce `Diagnostic`s with source ranges → surfaced exactly like swiftc diagnostics in the editor; `ReevalState` (LC-1) is reused (instant, so `.compiling` is effectively skipped; `.failed` carries the diagnostics).
## Module placement
New **cross-platform** SwiftPM target `LyrebirdGraphDSL` in the **main package** (depends on `Lyrebird` core; pure Swift, no AppKit, no `swiftc`). Not in the macOS-only `LiveCompile/` sub-package — placing it in the core package gives **iOS the interpreter for free** and keeps it independent of the swiftc tooling.
The macOS scratch editor gains a **DSL mode** alongside the Swift mode (toggle, or auto-detect by a leading directive); iOS hosts get a DSL-only editor later. `LiveSession` (or a sibling `LiveDSLSession`) exposes `evaluateDSL(_:)` mirroring `compileAndRunAsync` but synchronous + instant.
## Phasing
- **LC-8a — Skeleton:** `LyrebirdGraphDSL` target; lexer + parser + AST; `DSLBuiltin` registry with ~5 generators (OscSin, OscSaw, Pan2, `*`, `+`); `GraphBuilder`; evaluate a bare expression to a graph. Unit tests on parser + builder (pure, no engine). **Proves the pipeline.**
- **LC-8b — Registry + binding:** expand the registry (~40 generators: oscillators, noise, common filters, envelopes, math); slot binding (`name = …`) via `play(slot:)`; operator precedence + parens + `>>`; diagnostics with source ranges. Engine round-trip tests (build → add → `processBlock` → non-zero audio).
- **LC-8c — Live + patterns:** `set` / `ramp` of slot live-params; a handful of `Pattern`/`Demand` builders; clock/tempo directives (reuse LC-4 `swapClock`).
- **LC-8d — Editor integration:** DSL mode in `LyrebirdScratchView` (reuse the LC-6 highlighter — DSL is a subset, colors work); `ReevalState`; instant eval path. Optionally an iOS-only DSL editor (the deprioritized bonus).
- **LC-8-codegen (future):** build-time generation of the registry from generator init signatures, feeding the same `DSLBuiltin` table.
## Risks / open questions
- **Registry maintenance.** Hand-written means new generators don't appear automatically. Mitigation: the curated set covers the live-coding 80%; code-gen backend later. Accept the gap for v1.
- **Param-type expressibility.** Non-numeric init params (enums, buffers, tables) aren't DSL-expressible. Each `DSLBuiltin` chooses which params to expose and defaults the rest; complex generators are simply not in the registry until they earn a curated entry.
- **Language scope creep.** Strong pressure to add variables, loops, functions. Hold the line: v1 is graph-description only; anything more is the Swift path. Revisit only with evidence.
- **`>>` operator semantics.** Sugar for `input:` — only valid for generators whose first/`input` param is a signal. Needs a per-builtin "accepts upstream" flag. Deferrable to LC-8b.
- **Two editor modes.** Mode toggle vs auto-detect vs separate views — decide at LC-8d. Auto-detect risks ambiguity; a leading `#!dsl` directive or an explicit toggle is safer.
## Non-goals restated
This is the **specialized-but-more-possible** live-coding lane, not a general language and not a Swift replacement. It exists to make the tight edit→hear loop instant and safe (and portable to iPad), reusing every downstream piece LC-1…LC-7 already built.