v1.4.0 release: live-coding scratch editor, interpreted Graph DSL, ClosureSynthesizer + SampleLoop
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
Phases are ordered by dependency. Each phase should have tests before moving on.
|
||||
|
||||
Completed phases (1–34, 36–95, 96a, 97, 99, 101, 102a, 102b, 103, 104a, 104b, 104c, 104d, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 160, 161, 162, 163, 170, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 196, 197, 198, 88b, MCE-A, MCE-B, 85.5, 86.75a, 86.75b, LyrebirdBufferUpdates, 77-review-cleanup, 71b, 49b, 46, iOS-1–iOS-4, Score Phases A–D, 204, 222, GC-1–GC-9B, GC-11, GC-12, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239) are archived in `docs/01-completed-working-order.md`.
|
||||
Completed phases (1–34, 36–95, 96a, 97, 99, 101, 102a, 102b, 103, 104a, 104b, 104c, 104d, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 160, 161, 162, 163, 170, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 196, 197, 198, 88b, MCE-A, MCE-B, 85.5, 86.75a, 86.75b, LyrebirdBufferUpdates, 77-review-cleanup, 71b, 49b, 46, iOS-1–iOS-4, Score Phases A–D, 204, 222, GC-1–GC-9B, GC-11, GC-12, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, LC-1, LC-2, LC-3, LC-4, LC-5, LC-6, LC-7) are archived in `docs/01-completed-working-order.md`.
|
||||
|
||||
## Phase Completion Checklist
|
||||
|
||||
@@ -241,11 +241,33 @@ Full details in `docs/01-completed-working-order.md`.
|
||||
| 237 | Doc-example fallout — fixed `GettingStarted`'s flagship example (`doneAction`/`.freeEnclosing` never existed), made entry examples self-contained (coverage 382/1458; the original `try` rot now fails), harness `throws` wrapper + narrowest-first preambles, and pinned `DistributionKind`'s golden values (3 of 4 had drifted). | 5465 |
|
||||
| 238 | Doc-rot gap pass — extended the DocC gate to `LyrebirdUI` (was entirely unguarded; 0 warnings), implemented the `member` preamble (396 → 426 fences), confirmed zero remaining dead API forms, and established that the residual 1032 fences are continuation fragments no preamble can fix. | 5477 |
|
||||
| 239 | Doc checks in the review process — `check-doc-impact.sh` reports which docs a diff's public-API changes may have invalidated (validated against the commit that caused the original `engine.add` rot). Reports, never fails; suppresses refs the compile guard already covers; wired into `/lyrebird_review` step 2b. | 5477 |
|
||||
| LC-1 | Re-eval readiness signal (`ReevalState`) — `LyrebirdScratchModel` publishes `.empty`/`.clean`/`.dirty`/`.compiling`/`.failed` + `canEvaluate`; view status badge; menu Run gated on `canEvaluate` via `NSMenuItemValidation`. Folded in: `discoverSPMModuleMaps` fixes snippet `import LyrebirdSynth` under bare `swift build`/`swift test` (was Xcode-only). LiveCompile sub-package 47/47. | 5497 (+47 sub-pkg) |
|
||||
| LC-2 | Bare-graph play ergonomics — new public `ClosureSynthesizer` (`SynthesizerBase` from a closure, no `build()` override); `SnippetContext.play { }` forwarder; scratch placeholder leads with the one-liner. | 5502 (+48 sub-pkg) |
|
||||
| LC-3 | Named slots / `Pdef`-style hot-swap — `LiveSession` name→synth slot map (persists across non-additive re-eval); `SnippetContext.play(slot:) { }` replaces one voice in place; `clearSlot`/`clearSlots`; Clear Synths full-reset. | 5502 (+54 sub-pkg) |
|
||||
| LC-4 | On-beat swap (latency masking) — `SwapQuantize` (`.immediate`/`.nextBeat`/`.nextBar`); quantized slot swaps schedule add+remove on the next `LyrebirdClock` boundary (orphan-safe via per-slot add-time); `ReevalState.queued(untilBeat:)`. | 5502 (+63 sub-pkg) |
|
||||
| LC-5 | Module-cache prewarm (time-to-first-sound) — measured: warm compile ~0.12s, cold `.pcm` build ~2–3s; `LiveCompiler.prewarm`/`LiveSession.prewarm()` warm swiftc's default cache off-main at `onAppear`; auto-annotate dropped (measured worthless); dedicated `-module-cache-path` reverted (dlopen cast-crash). | 5502 (+67 sub-pkg) |
|
||||
| LC-6 | Scratch editor syntax highlighting — `ScratchSwiftTokenizer` (pure UTF-16 lexer) + `ScratchSyntaxHighlighter` paints token colors onto `NSTextStorage`; `isRichText`, re-highlight per edit. Completion (SourceKit-LSP) deferred. | 5502 (+80 sub-pkg) |
|
||||
| LC-7 | Session reset valve + snippet-memory accounting — `LiveSession.resetAll()` (panic clear) + `loadedSnippetCount`; dlclose rejected as unsafe (dangling Swift conformance-cache pointers). User-facing memory UI revisit deferred to end of arc. | 5502 (+83 sub-pkg) |
|
||||
|
||||
---
|
||||
|
||||
## Upcoming Phases
|
||||
|
||||
### LiveCompile / Scratch Improvements (LC-1 … LC-8)
|
||||
|
||||
Two tracks. **Track A** (LC-1…LC-7) polishes the existing Swift-compile scratchpad — full Swift power, macOS-only, floors at a few-hundred-ms warm eval (Swift has no supported in-process JIT). **Track B** (LC-8) is a separate bet: an interpreted Generator-graph DSL for instant, no-dylib, no-leak evaluation. iOS reach is a *bonus* of Track B, deprioritized as a driver.
|
||||
|
||||
Cross-cutting note: the async off-main compile path is **already implemented** (`LyrebirdScratchModel.run` awaits `LiveSession.compileAndRunAsync`, gated by `isCompiling`). So the near-term work is readiness signalling + ergonomics, not un-freezing.
|
||||
|
||||
- **LC-1 — Re-eval readiness signal.** ✅ Complete (see `docs/01-completed-working-order.md`). `ReevalState` published by `LyrebirdScratchModel`, view badge, menu Run gating on `canEvaluate`; folded in the `discoverSPMModuleMaps` bare-SPM compile fix.
|
||||
- **LC-2 — Bare-graph play ergonomics (time-to-first-sound).** ✅ Complete (see `docs/01-completed-working-order.md`). Public `ClosureSynthesizer` (core) + `SnippetContext.play { }` forwarder; placeholder leads with the one-liner.
|
||||
- **LC-3 — Named slots + hot-swap (`Pdef` analogue).** ✅ Complete (see `docs/01-completed-working-order.md`). `context.play(slot:) { }` replaces one voice in place; per-name tracking in `LiveSession` (persists across non-additive re-eval); `clearSlot`/`clearSlots`.
|
||||
- **LC-4 — On-beat swap (latency masking).** ✅ Complete (see `docs/01-completed-working-order.md`). `SwapQuantize` + `LiveSession.swapClock`/`swapQuantize`; quantized slot swaps schedule add+remove on the next `LyrebirdClock` boundary (orphan-safe); `ReevalState.queued(untilBeat:)`.
|
||||
- **LC-5 — Module-cache prewarm.** ✅ Complete (see `docs/01-completed-working-order.md`). Measurement showed the cost is purely the cold `.pcm` build; `LiveSession.prewarm()` warms swiftc's default cache in the background at session start (first ⌘↩ ~0.12s vs ~2.2s). Auto-annotate lever dropped — measured to shave nothing at warm.
|
||||
- **LC-6 — Editor UX.** ✅ Syntax highlighting complete (see `docs/01-completed-working-order.md`): `ScratchSwiftTokenizer` + `ScratchSyntaxHighlighter`, re-highlight per edit.
|
||||
- **LC-6b — Code completion (SourceKit-LSP).** ✅ Complete (see `docs/01-completed-working-order.md`). `SourceKitLSPClient` drives the toolchain's `sourcekit-lsp` over stdio; `SnippetCompletionService` resolves snippet symbols via a wrapped-snippet workspace + generated `compile_commands.json`; the editor pops the standard completion window on `.` (Swift mode only). Manual-invoke shortcut is a possible follow-up.
|
||||
- **LC-7 — Dylib leak mitigation.** ✅ Complete (see `docs/01-completed-working-order.md`). Reset valve (`LiveSession.resetAll()` + `loadedSnippetCount`; refcount-gated `dlclose` **rejected as unsafe** — dlopen registers Swift type metadata + conformance records into process-global caches that dlclose leaves dangling → crash even with zero live instances). **User-facing revisit done**: the editor mirrors `loadedSnippetCount` as a "snippets: N" count (orange past a 50-dylib threshold) and shows a warning banner nudging a restart or a switch to the leak-free Graph DSL mode; `snippetMemoryHint` is a unit-tested pure boundary.
|
||||
- **LC-8 — Interpreted Generator-graph DSL (Track B).** ✅ Complete (see `docs/01-completed-working-order.md`). Cross-platform `LyrebirdGraphDSL` target + `DSLBuiltin`/registry code-genned from generator sources (`Tools/DSLRegistryGen`, `scripts/generate-dsl-registry.sh` + `--check`; **304 builtins** = 165 audio + 121 control + 18 buffer). Language: `DSLLexer`→`DSLParser`→AST→`DSLGraphBuilder`→`DSLInterpreter.evaluate` — instant, no swiftc, no dylib, no leak. Rate suffix is the exact Swift name (`OscSin.Control`) for paste-compatibility; buffer resources via a `DSLValue`/`DSLResourceResolver` contract. Editor (8d): status-bar mode toggle in the scratch view runs the buffer through `LiveSession.runGraphDSL` on the same track/slot machinery, DSL errors in the same gutter. (Bus/URL/closure/demand builtins intentionally out of DSL scope — host-level or Swift-path.)
|
||||
|
||||
## Deferred / Future
|
||||
|
||||
|
||||
@@ -11088,3 +11088,177 @@ Swept what the guards could not see. Each item below was measured, not assumed.
|
||||
rot that no API change caused (`theory.md`'s `.freeEnclosing` was already dead — that needed
|
||||
the phase 238 sweep), and for short common member names the candidate list is long enough that
|
||||
the reviewer must qualify by owning type. It narrows where to look; it does not decide.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-1 — Re-eval readiness signal (ReevalState)
|
||||
|
||||
First step of the LiveCompile / Scratch improvement group (LC-1…LC-8; roadmap in `docs/00-working-order.md`). Lives entirely in the macOS-only `LiveCompile/` sub-package — host-side tooling, nothing on the RT audio thread.
|
||||
|
||||
**The signal.** New `public enum ReevalState` (`LiveCompile/Sources/LyrebirdLiveCompileUI/ReevalState.swift`): `.empty` / `.clean` / `.dirty` / `.compiling` / `.failed(diagnosticCount:)`, plus `canEvaluate: Bool` (false only for `.empty` / `.compiling`). Answers "can I re-evaluate, and would it change anything?" — distinct from the free-text `statusMessage`.
|
||||
|
||||
**Model wiring** (`LyrebirdScratchModel`): `@Published private(set) var reevalState`; `lastEvaluatedText` baseline captured on each successful run. `text.didSet` recomputes to `.dirty`/`.empty`/`.clean` on edit (no-op while compiling — the run owns the state until it resolves). `run(additive:)` drives `.dirty` → `.compiling` → `.clean` (or `.dirty` if the buffer was edited mid-compile) / `.failed`. `clearTracked()` and `load(from:)` drop the baseline (nothing the buffer produced is still playing) so the buffer reads `.dirty` again. `didSet` correctly does not fire for the `init` assignment, so `reevalState` is seeded explicitly in `init`.
|
||||
|
||||
**UI** (`LyrebirdScratchView`): a colored dot + label + tooltip in the status bar bound to `reevalState`. `LyrebirdScratchMenuController` conforms to `NSMenuItemValidation` and disables the Run / Run Additive commands when `canEvaluate` is false (compiling or empty) — the readiness signal drives the actual UI gating. Corrected the stale "v1 synchronous, freezes UI" claim in `LiveCoding.md` (the off-main `compileAndRunAsync` path already ships) and the false "Run buttons disable" doc (no buttons existed; runs are menu-driven) in both `LiveCoding.md` and the view docstring; documented the readiness signal.
|
||||
|
||||
**Compile-env fix (folded in).** `LiveSession.makeSwiftcArgs` only discovered Clang module maps at Xcode's `GeneratedModuleMaps` location, so a snippet's `import LyrebirdSynth` failed with `missing required module 'LyrebirdC'` under a plain `swift build` / `swift test` layout (the C target's map lives at `<buildDir>/<Target>.build/module.modulemap`). New `discoverSPMModuleMaps` surfaces that location (umbrella-header path is absolute, so the map alone resolves the module). Fixed the 12 compile-round-trip tests that were red under bare `swift test` and makes live-compiled snippets work outside Xcode.
|
||||
|
||||
**Tests:** LiveCompile sub-package 47/47 (`swift test --no-parallel`). 3 `ReevalState` enum + 9 `LyrebirdScratchModel` transition + 1 `discoverSPMModuleMaps` fixture test. Main package unaffected (5497/5497).
|
||||
|
||||
**Review:** two agents (`lyrebird_review_agent` + caveman sweep), no RT/correctness blockers (host tooling). Findings resolved: named the badge-spacing constant (no magic numbers); wired real menu-item gating to make the doc claim true; tightened the run-outcome tests to assert `.clean` directly once the module-map fix made compiles reliable; added the `discoverSPMModuleMaps` unit test.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-2 — Bare-graph play ergonomics (ClosureSynthesizer)
|
||||
|
||||
Second step of the LiveCompile / Scratch group (roadmap in `docs/00-working-order.md`). Time-to-first-sound: play a generator graph without declaring a `SynthesizerBase` subclass and overriding `build()`.
|
||||
|
||||
**Core type.** New `public final class ClosureSynthesizer: SynthesizerBase` (`Sources/Lyrebird/Synthesizer/ClosureSynthesizer.swift`) — supplies its output graph from an `@escaping () -> any ValidGeneratorInput` closure instead of a `build()` override. The closure runs inside `build()`, once per instance, on the main thread at `engine.add` time (`rebuildGraph()` → `build()`; `evaluate()` never re-runs it). A multi-channel source fans across consecutive buses from `bus` (default `0`), exactly like `output(bus:source:)`. No `@LiveParam` slots — reach for a named subclass once a voice needs live-controllable parameters. Reusable everywhere (demos, tests, one-off voices), not just scratch:
|
||||
|
||||
```swift
|
||||
try engine.add(ClosureSynthesizer { OscSin.Audio(freq: 440, mul: 0.1) })
|
||||
```
|
||||
|
||||
**Snippet surface.** `SnippetContext` gains `play(bus:_:)` — a `@MainActor` forwarder wrapping the closure in a `ClosureSynthesizer` and routing through the existing `play(_:)` so it is tracked for cleanup on the next non-additive re-evaluation. Scratch `defaultPlaceholder` rewritten to lead with the one-liner (`context.play { Pan2(input: OscSin.Audio(freq: 440, mul: 0.15), pan: 0) }`) — no subclass boilerplate.
|
||||
|
||||
**Docs:** `docs/protocols/synthesizer.md` gains a "ClosureSynthesizer — a graph without a subclass" section (bus fan-out, once-per-`build()` execution, graph-copy-per-instance guidance).
|
||||
|
||||
**Tests:** 5 core (`ClosureSynthesizerTests` — bus-zero write, `bus:` selection, closure-runs-once-per-instance-at-add, bare-oscillator produces audio, multi-channel fan-out) + 1 LiveCompile (`closurePlayAddsAndTracksBareGraph`, round-trips the `play { }` form through the real swiftc pipeline). Main package 5502/5502; LiveCompile sub-package 48/48. Guards green: `check-swift6-consumer.sh` (zero-annotation consumer guarantee holds despite the new public subclass), `check-docc.sh` (0 warnings), `check-doc-snippets.sh` (543).
|
||||
|
||||
**Review:** two agents, no blocking findings (host/non-RT + a pure `SynthesizerBase` subclass); caveman sweep LGTM. The only `check-doc-impact.sh` "no doc reference" entry was `ClosureSynthesizer.outputBus`, a `private let` — internal, no doc obligation.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-3 — Named slots (Pdef-style hot-swap)
|
||||
|
||||
Third step of the LiveCompile / Scratch group (roadmap in `docs/00-working-order.md`). Entirely in the macOS-only `LiveCompile/` sub-package — no core `Lyrebird` module changes; nothing on the RT audio thread.
|
||||
|
||||
**The idiom.** `context.play(slot: "bass") { OscSaw.Audio(freq: 55, mul: 0.2) }` installs a voice under a name. Re-running that slot definition **replaces just that voice in place** — the new voice starts before the old is removed (brief overlap, no gap) — while every other slot keeps playing. Unlike anonymous `context.play`, a slotted voice is **not** torn down by the next non-additive (⌘↩) run, which is what lets you edit and re-evaluate one voice at a time (the SC `Pdef` mental model).
|
||||
|
||||
**Model.** `LiveSession` gains a name→synth map `slottedSynths`, guarded by the existing `trackingLock`, kept SEPARATE from the anonymous `trackedSynths` so slots survive a non-additive clear: internal `assignSlot(_:synth:)` (post-add hook — called after `engine.add` succeeds; swaps the dict under the lock, then `engine.remove`s the previous synth outside the lock; the removed synth is a *different* instance, so the "one processBlock between remove and re-add of the same instance" constraint does not apply), plus public `clearSlot(_:)` / `clearSlots()` / `slotCount` / `slotNames`. `SnippetContext` gains `play(slot:_:)` (Synthesizer) and `play(slot:bus:_:)` (bare-graph closure via `ClosureSynthesizer`). `LyrebirdScratchModel.clearTracked()` is now a full reset (anonymous + slots) for the toolbar Clear Synths button; the non-additive run's internal `clearTracked` still clears anonymous only, so slots persist.
|
||||
|
||||
**Known gotcha (documented):** a slot definition you delete from the buffer and stop re-running is not auto-removed — clear it with `context.session.clearSlot("name")` / `clearSlots()`, or hit Clear Synths. Diffing which slots a run touched (to auto-prune) was judged not worth the complexity; deferred.
|
||||
|
||||
**Docs:** `LiveCoding.md` "Named slots (hot-swap)" section + lifetime table; `LYREBIRD_START_HERE.md` snippet-API list updated.
|
||||
|
||||
**Tests:** LiveCompile sub-package 54/54 (+6): 5 `LiveSession` (assign/replace-in-place keeps one voice, `clearSlot` named-only + no-op, `clearSlots` all, `clearTracked` leaves slots intact, end-to-end `play(slot:)` round-trip through real swiftc surviving a non-additive re-run) + 1 model (Clear Synths full-reset also clears slots). Main package untouched (5502).
|
||||
|
||||
**Review:** two agents; one blocking (a doc self-contradiction — the Clear Synths description in `LiveCoding.md` still said it called `LiveSession.clearTracked()` directly, contradicting the new Named slots section) + two non-blocking docs (the `@unchecked Sendable` proof didn't enumerate `slottedSynths`; stale `LYREBIRD_START_HERE.md` API list) — all fixed. Slot swap logic, lock discipline (`engine.remove` outside the lock, non-reentrant `NSLock` never double-acquired), and actor isolation verified clean; caveman sweep LGTM.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-4 — On-beat swap (quantized slot swaps, latency masking)
|
||||
|
||||
Fourth step of the LiveCompile / Scratch group. Entirely in the macOS-only `LiveCompile/` sub-package — no core changes; nothing on the RT thread. Depends on LC-1 (readiness state), LC-3 (named slots), and `LyrebirdClock`.
|
||||
|
||||
**The point.** A `swiftc` build finishes a few hundred ms after ⌘↩ — Swift has no in-process JIT, so that latency is a floor, not a bug to optimize away. LC-4 *hides* it: point the session at a clock and named-slot swaps land on the next musical boundary instead of whenever the compile finished. You edit the bass, hit ⌘↩, and the change drops on the downbeat.
|
||||
|
||||
**Mechanism.** New public `SwapQuantize` enum (`.immediate` / `.nextBeat` / `.nextBar(beatsPerBar:)`) with `targetBeat(clock:)`. `LiveSession` gains `swapClock` / `swapQuantize` config (settable, `trackingLock`-guarded) and `swapSlot(_:synth:)`: in quantized mode it computes the boundary `SampleTime` from a `LyrebirdClock` and calls `engine.schedule(new, at: t)` + schedules the old voice's removal at the same time — a glitch-free on-grid swap; immediate mode falls back to add-now (the LC-3 path). `pendingSwapBeat` is a self-clearing signal (nil once the clock passes the target or the config changes). `ReevalState` gains `.queued(untilBeat:)`, which the model shows after a scheduled swap and settles to `.clean` once the boundary passes (the view's heartbeat timer calls `refreshQueuedState`); purple badge.
|
||||
|
||||
**Orphan-safety (review-fixed).** Each slot occupant carries its scheduled add time (`SlotEntry`); every removal goes through `removeSlotOccupant`, which schedules the removal at `max(desired, addTime)` — never before the occupant's own add. The engine's per-block event sort is stable at equal times and the add is always enqueued first, so an add + removal on the same sample apply add-then-removal and the voice is always cleaned up. Without this, clearing a slot (or re-swapping earlier) before a scheduled add fired left a permanent orphan voice — the RT `remove` synchronously unbinds and no-ops the tree removal, then the later add lands unremovable. Regression test drives `processBlock` past the boundary and asserts `synthesizerCount == 0`.
|
||||
|
||||
**Tests:** LiveCompile 63/63 (+9 over LC-3): 4 `SwapQuantize.targetBeat`, `LiveSession` schedule/pending-beat/immediate-no-pending + the two node-tree tests (replace→one voice, clear-before-boundary→no orphan), 1 model queued-then-settles, `ReevalState.queued` canEvaluate. Main package untouched (5502).
|
||||
|
||||
**Review:** two agents; **one blocking** (the orphan bug) + several correctness/doc issues (discarded remove Bool, phantom `pendingSwapBeat` after config change, "engine.add failed" message on the schedule path, stale `ReevalState` state-machine doc, a "LC-3" phase reference in shipped docs) — all fixed, with a discriminating regression test. Thread-safety (all swap state under `trackingLock`, `engine.remove` outside the lock), actor isolation, and `SwapQuantize` math verified clean; caveman sweep otherwise LGTM.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-5 — Module-cache prewarm (kill time-to-first-sound)
|
||||
|
||||
Fifth step of the LiveCompile / Scratch group. Entirely in the macOS-only `LiveCompile/` sub-package — no core changes; nothing on the RT thread. **Measurement-driven** (the whole point of doing the measurement first).
|
||||
|
||||
**What the numbers said.** A warm snippet compile is ~0.12 s; the cost is the **cold module cache** — building the precompiled module (`.pcm`) for the large `LyrebirdSynth` interface, ~2–3 s, paid once, landing on the user's first ⌘↩. Annotating snippet bindings shaved nothing at warm (0.11 vs 0.10 s), so the "auto-annotate" lever was dropped. Swift has no in-process JIT, so the cold build is a floor to *hide*, not optimize away.
|
||||
|
||||
**Fix — prewarm at session start.** `LiveCompiler.prewarm(extraSwiftcArgs:)` type-checks a trivial import-only snippet (building the `.pcm`) via the existing `runSwiftc`; `LiveSession.prewarm()` runs it on a detached `.utility` task, idempotent via `_prewarming`/`_prewarmed` under `trackingLock`, with the flag-building filesystem walk done *inside* the task (off the caller's thread). `isPrewarmed` reflects success only — a failed prewarm (missing toolchain) stays `false` and is retryable, never throws. `LyrebirdScratchView` triggers it from `onAppear` (deliberately not `LyrebirdScratchModel.init`, so constructing a model never shells swiftc). First ⌘↩ then hits a warm cache (~0.12 s) instead of ~2.2 s.
|
||||
|
||||
**Design landmine (found + reverted).** The first cut pinned a dedicated `-module-cache-path`. That **deterministically SIGSEGV'd** the sync-compile test: a freshly-built dedicated cache produces module metadata that diverges from the already-loaded `libLyrebirdLiveCompileDynamic`, turning the test bundle's benign ObjC class-duplication *warning* into a hard cast crash on `dlopen`. Confirmed it passes on `main`, isolated `-module-cache-path` as the trigger, reverted to swiftc's default shared cache (which measurement showed warms + persists). Prewarm and the real compile now share the default cache. The rationale is documented in `makeModuleResolutionArgs` and `LiveCoding.md`.
|
||||
|
||||
**Tests:** LiveCompile 67/67 (+4 over LC-4), stable across repeated runs (the crash was deterministic — now consistently clean). Two `LiveSession` prewarm tests (completes+flag, idempotent) plus two direct `LiveCompiler.prewarm` tests (success with real module-resolution args; throws when modules unresolvable) that bypass the session's error-swallowing wrapper. Main package untouched (5502).
|
||||
|
||||
**Review:** two agents; no blocking correctness bugs, but several real issues fixed including nits (per request): flag-building fs-walk ran on the main thread (moved off), `isPrewarmed` flipped true even on failure (now success-only + retryable), two stale reverted-design doc references (`moduleCachePath` symbol link, `-module-cache-path` in a param doc), a stdout comment not covering `-typecheck`, and a test-quality gap (the session-level tests passed regardless of real success — added direct `LiveCompiler.prewarm` coverage). Prewarm lifecycle thread-safety and `[weak self]` verified clean.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-6 — Scratch editor syntax highlighting
|
||||
|
||||
Sixth step of the LiveCompile / Scratch group. Entirely in the macOS-only `LiveCompile/` sub-package — no core changes, nothing on the RT thread. Scope: **highlighting only**; code completion (a SourceKit-LSP path) is a much larger async effort, deliberately deferred.
|
||||
|
||||
**What.** The `NSTextView` scratch editor now colors Swift as you type — keywords + `@attributes` (pink), Capitalized-identifier types like `OscSin`/`Pan2` (purple), strings (red), numbers (blue), comments (green), via dynamic `NSColor.system*` that adapt to light/dark.
|
||||
|
||||
**How.** New `ScratchSwiftTokenizer` — a pure, dependency-free, UTF-16-correct lexer (nested `Kind`/`Token`) that classifies the colorable spans: line + nested-block comments, single- and triple-quoted strings with escapes, number literals (no range-operator over-capture, signed exponents), keywords, and Capitalized-identifier types. Approximate by design (a highlighter, not a parser). New `ScratchSyntaxHighlighter` paints those token colors onto an `NSTextStorage` — normalizes font/paragraph/label over the whole buffer first (so a paste or font change can't leave stray styling), then overlays per-token foreground colors; attribute-only, so the string and selection are untouched. `ScratchEditor` switched to `isRichText` (with `importsGraphics = false` so no attachment glyphs) and re-highlights on every edit.
|
||||
|
||||
**Tests:** LiveCompile 80/80 (+13 over LC-5). 11 `ScratchSwiftTokenizer` tests (keywords/types/plain, numbers incl. range-operator + signed exponent, strings incl. escapes, line/nested-block comments, attributes, UTF-16 offsets across an emoji, concurrency keywords, empty, **and the trailing-backslash-at-EOF crash regression**) + 2 `ScratchSyntaxHighlighter` render-wiring tests against a real `NSTextStorage` (correct per-token colors; re-apply normalizes away a stale keyword color). The tokenizer→color→storage path is verified; only NSTextView's pixel render isn't exercised headlessly. Main package untouched (5502).
|
||||
|
||||
**Review:** two agents, and one found a **blocking crash** — the string escape handler advanced `i += 2` unconditionally, overrunning the UTF-16 offset table when a backslash was the buffer's last character (trap: "Index out of range"); since the editor re-tokenizes per keystroke, typing an opening quote + trailing backslash crashed the UI. Clamped both escape sites to `min(i + 2, count)` with a regression test. Plus nits fixed: named the `"""` delimiter-length constant, added the concurrency keywords, signed exponents, switched the internal-type DocC symbol link to a plain code span, pinned `importsGraphics = false`, and softened the perf claim.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-7 — Session reset valve + snippet-memory accounting
|
||||
|
||||
Seventh step of the LiveCompile / Scratch group. Entirely in the macOS-only `LiveCompile/` sub-package — no core changes, nothing on the RT thread. **Scope was deliberately reduced after an engineering finding** (confirmed with the maintainer).
|
||||
|
||||
**The finding — dlclose is unsafe, not just risky.** The roadmap wanted a refcount-gated `dlclose` behind a flag. Investigation: `dlopen` of a Swift snippet dylib registers its type metadata and protocol-conformance records into **process-global runtime caches**; `dlclose` unmaps the dylib without deregistering them, leaving those caches dangling → a crash on a later type operation, **even after every synth the snippet produced has been removed** (the refcount gate does not make it safe). A flag-gated `dlclose` would therefore knowingly ship a crash, so it was rejected rather than built. Reclaiming mapped snippet memory needs a process restart; the interpreted-graph path (LC-8) is the structural fix.
|
||||
|
||||
**Shipped (safe).** `LiveSession.resetAll()` — a panic/clear valve that removes every anonymous tracked synth (`clearTracked()`) and every named slot (`clearSlots()`) from the engine and clears the pending-swap signal, without tearing down the engine; the toolbar **Clear Synths** routes through it. `LiveSession.loadedSnippetCount` — thread-safe count of mapped snippet dylibs, for host observability (e.g. a "restart to reclaim memory" nudge after a long session). New `LiveCoding.md` "Snippet memory (the dylib leak)" section documenting the leak, why `dlclose` is unsafe, and `resetAll` as the valve.
|
||||
|
||||
**Tests:** LiveCompile 83/83 (+3 over LC-6): `resetAll` clears tracked + slots, `resetAll` clears a pending quantized swap, `loadedSnippetCount` grows per compile. Main package untouched (5502).
|
||||
|
||||
**Review:** two agents. Locking verified correct (`clearTracked`/`clearSlots` release `trackingLock` before `resetAll` re-acquires it — no re-entrancy/deadlock; `NSLock` non-reentrant), the pending-scheduled-swap interaction verified orphan-safe, and the doc's `dlclose`-unsafety claim confirmed accurate. One blocking (the `_pendingSwapBeat` clear was untested — added a test) + a doc caveat (concurrency precondition + non-atomic reset) fixed.
|
||||
|
||||
**Planned revisit (deferred).** At the end of the LiveCompile arc, come back for more user-facing memory choice/safety — e.g. surfacing `loadedSnippetCount` in the editor with a restart nudge past a threshold, and any additional guardrails. Tracked in `docs/00-working-order.md` Deferred / Future.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-8 — Interpreted Generator-graph DSL
|
||||
|
||||
Final step of the LiveCompile / Scratch group: a text-to-graph language that plays instantly with no `swiftc`, no dylib, no leak, and no sandbox-disable — the structural answer to LC-7's by-design snippet-dylib leak. The DSL layer (`LyrebirdGraphDSL`) is a cross-platform main-package target; only the editor integration is macOS-only.
|
||||
|
||||
**Code-gen first (8a).** No generator registry exists in Lyrebird (no runtime table, no reflection to call inits by name), so the DSL had to introduce one — generated, not hand-written. `Tools/DSLRegistryGen` is a separate SwiftPM package (swift-syntax stays out of the main build) that scans generator sources and emits `Sources/LyrebirdGraphDSL/Generated/GeneratedDSLRegistry.swift`, driven by `scripts/generate-dsl-registry.sh` (`--report` / `--check` drift guard, compile-verify). `DSLBuiltin` (Sendable, `@Sendable make` closure) + `DSLBuiltinRegistry` (keyed by name + rate) + `DSLArgument` (coerces a bound `any ValidGeneratorInput` to the `Double`/`Int`/`Float`/buffer an init needs).
|
||||
|
||||
**Wider surface before the language.** `.Control`-rate variants emitted alongside audio (registry keyed by `(name, rate)`); resource kinds (buffer/bus/URL/closure) categorised so the parser was designed against the full surface. Final registry: **304 builtins** (165 audio + 121 control + 18 buffer).
|
||||
|
||||
**The language (8b + language surface).** `DSLLexer` → `DSLParser` (recursive descent, `*/` over `+-`, parens, unary minus, positional + labelled args, `name = expr` slot assignment, depth-capped at 128, constant-folds numeric subexpressions so numeric-literal-only params accept `-0.5`/`220*2`) → AST (`DSLExpr`/`DSLProgram`/`DSLSpan`) → `DSLGraphBuilder` (registry lookup, `+ - * /` → `BinaryOpGenerator` ops, duplicate-arg detection) → `DSLInterpreter.evaluate(_:resources:)` → `[DSLOutput]`. Explicit control-rate selection and buffer resources: `DSLValue` (`.signal | .buffer`), `DSLResourceResolver` (host name → `LyrebirdBuffer`), bare-identifier references (`PlayBuffer(buffer: kick)`), operators signal-only.
|
||||
|
||||
**Paste-compatibility.** The rate suffix is the *exact* Swift nested-class name — `OscSin.Control(freq: 4)`, not a lowercase `.control` or an SC-style `.kr` — so a DSL graph expression reads and constructs identically in the editor and in a Lyrebird `build()`; only the wrapping (`output(...)`, `let` slot) differs. (`.ar`/`.kr` was shipped, then corrected to `.audio`/`.control`, then to `.Audio`/`.Control` after maintainer feedback that a user shouldn't have to learn a spelling difference between environments.)
|
||||
|
||||
**Editor mode (8d).** A status-bar segmented toggle (`ScratchEvalMode`) switches the scratch buffer between the swiftc Swift-snippet path and the instant DSL path. `LiveSession.runGraphDSL(_:additive:resources:)` interprets the buffer and plays each `DSLOutput` through the **same** tracking + named-slot machinery as the Swift path (bare line → tracked anonymous synth; `name = …` → persistent hot-swap slot). The whole program is built **before** any engine mutation, so a malformed edit never drops the currently-playing graph; once valid, playback is best-effort per statement (a `.pendingQueueFull` on one statement is collected, not aborted — matching `SnippetContext.play`). `GraphDSLDiagnosticMapper` turns `DSLParseError`/`DSLBuildError` into the same `[Diagnostic]` the swiftc path emits (parse errors resolve a line/column from the span's char offset; build errors report at file scope). `LyrebirdScratchModel.switchMode(to:)` swaps the seed placeholder, clears diagnostics, and drops the run baseline.
|
||||
|
||||
**Linking (the crash paid for twice).** The DSL is compiled as a **local** `LyrebirdGraphDSLEmbedded` target in the LiveCompile sub-package, from the main package's shared sources via a git symlink (`LiveCompile/Sources/LyrebirdGraphDSLEmbedded` → `../../Sources/LyrebirdGraphDSL`, distinct module name), **not** consumed as a main-package product. Any `LyrebirdGraphDSL` product — static *or* dynamic — static-embeds a second copy of `LyrebirdSynth` into its dylib (a same-package target dependency is always embedded into a dynamic product; verified via `nm`), so both it and `libLyrebirdDynamic` register Lyrebird's ObjC classes → double registration → spurious cast failures + `SIGSEGV` under `swift test`. Only a cross-package boundary forces dynamic linking (the same mechanism that made the LiveCompile split necessary). Compiling the DSL as a local target lets its `import LyrebirdSynth` resolve cross-package to the one shared `libLyrebirdDynamic` (verified: 0 embedded `LyrebirdSynth` symbols in the LiveCompile dylib, `otool -L` shows the `libLyrebirdDynamic` dependency). Safe because the DSL is pure value types — it registers nothing with the ObjC runtime.
|
||||
|
||||
**Tests.** DSL suite grew across the sub-phases (lexer/parser/interpreter/registry/argument/resource); the editor phase added 22 (LiveCompile 86 → 108: `LiveSessionGraphDSLTests`, `GraphDSLDiagnosticMapperTests`, `ScratchModelGraphDSLTests`). Main package untouched (5563); registry `--check` clean.
|
||||
|
||||
**Review.** Two agents per sub-phase. Notable fixes: constant resolution silently broken (assigned before its `var` ran → wiped); designated-init selection dropped overloads (RBJBandPass lost `q:`); doubly-nested types got the wrong DSL name (`MouseX` not `X`); a stack-overflow on deep nesting (depth cap); a deterministic `PlayBuffer`-teardown `SIGTRAP` worked around by testing buffer resolution directly (underlying `LyrebirdBuffer` ARC race tracked separately). The editor phase's three blocking findings — `runGraphDSL` aborting the mutation loop on the first engine error (→ per-statement continue-on-error), a DSL build error rendering as the nonsensical `preamble:0:0` (→ `(file)`), and `switchMode` leaving stale diagnostics / a false `.clean` — were all fixed and re-reviewed clean.
|
||||
|
||||
**Deferred / out of scope.** Bus/URL/closure/demand builtins (routing is host-level via `ClosureSynthesizer`'s `Out`; closures are the Swift path). LC-6b SourceKit-LSP completion. LC-7 revisit (user-facing memory choice/safety). The `LyrebirdBuffer` teardown ARC race.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-6b — Editor code completion (SourceKit-LSP)
|
||||
|
||||
The deferred half of LC-6: real Swift code completion in the live-coding editor, driven by the toolchain's `sourcekit-lsp`. macOS-only, all non-RT host tooling.
|
||||
|
||||
**Feasibility first.** The novel risk was whether `sourcekit-lsp` could resolve `LyrebirdSynth` symbols for an otherwise free-standing snippet file. Proven with a throwaway probe before any real code: driving the LSP handshake against a `compile_commands.json` built from the SPM build products, `OscSin.` completed to `Audio` / `Control` / `_Base`.
|
||||
|
||||
**`SourceKitLSPClient`** — a minimal LSP JSON-RPC client over stdio: `initialize` / `initialized`, `textDocument/didOpen` / `didChange`, `textDocument/completion`. A background reader thread parses `Content-Length`-framed messages and completes `CheckedContinuation<Data, Error>`s stored in an `NSLock`-guarded pending map; requests carry `Data` (Sendable) and use sync lock helpers so no `NSLock` call sits in an `async` context. Per-request timeout via a task-group race; injectable timeout/arguments for testing.
|
||||
|
||||
**`SnippetCompletionService`** (actor) — maintains a temp workspace holding the snippet **wrapped** in the same `SnippetHarness` preamble the compiler uses, next to a `compile_commands.json` carrying the host `LiveSession`'s `-I` / module-map / link flags plus an explicit `-sdk` / `-target` (which a normal build infers but the LSP needs). The caret is mapped through the harness line offset (`wrappedLine = userLine + userBodyLineOffset - 1`). SDK lookup + file writes run inside the async `start()` (actor executor), never on the caller's main thread.
|
||||
|
||||
**Editor wiring** — the `ScratchEditor` Coordinator pre-fetches candidates asynchronously on `.` and serves them synchronously to `NSTextView`'s own completion window (arrows / return / esc / insertion for free). A generation counter drops superseded responses; a caret-equality guard drops ones whose insertion point moved. Swift-mode only — graph-DSL is interpreted and needs no compiler. Best-effort: any LSP failure yields no candidates, never an error. `editorLineAndUTF16Char` (the offset→(line, UTF-16 column) mapping, LSP's coordinate space) is extracted and unit-tested.
|
||||
|
||||
**Tests** — 120/120 LiveCompile. Integration tests spawn the real `sourcekit-lsp`: `OscSin.` → `Audio`/`Control`, `context.` → `play`/`engine`; graph-DSL mode returns nothing. Unit tests cover the position mapping and the client's timeout / launch-failure paths.
|
||||
|
||||
**Review.** Two rounds. The critical find: `request(...)`'s timeout path dropped the pending continuation without resuming it, so the task-group child stayed suspended and `request` hung forever — the exact wedged-server case the timeout exists to guard (`cancelAll()` does not wake a suspended continuation). Fixed by resuming-then-dropping under the lock (+ a regression test). Also fixed: a blocking `xcrun` shelled from `init` on the main actor (moved into async `start()`), a swallowed graceful `exit` on shutdown, and a missing request-generation guard.
|
||||
|
||||
**Follow-ups (optional).** A manual-invoke completion shortcut (⌥/⌃-driven; dropped from the MVP to avoid `NSEvent`-monitor isolation friction), and richer completion presentation (detail/kind in the popup — `NSTextView`'s built-in window shows plain strings only).
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-7 revisit — snippet-memory UX (user-facing)
|
||||
|
||||
The deferred user-facing half of LC-7: make the by-design snippet-dylib leak visible and give the user a choice, without the unsafe `dlclose` (still rejected). LiveCompile-only, non-RT.
|
||||
|
||||
Each successful **Swift-mode** ⌘↩ maps one compiled snippet dylib that is never unloaded (`dlopen` registers Swift type metadata + conformance records into process-global caches that `dlclose` leaves dangling); Graph-DSL runs map none. `LyrebirdScratchModel` now mirrors `LiveSession.loadedSnippetCount` (refreshed at every site `trackedSynthCount` is — init, both run-path defers, `clearTracked`). A pure, unit-tested `snippetMemoryHint(count:threshold:)` returns a restart nudge past `snippetRestartThreshold` (50). The editor shows a **"snippets: N"** count in the engine bar (orange past the threshold) and an orange warning banner carrying the hint ("restart to reclaim, or use Graph DSL — no compile, no leak"). `Clear Synths` explicitly does *not* reclaim the dylibs and says so. It is a soft nudge, not a hard cap — the Graph DSL mode is the leak-free path the banner steers toward.
|
||||
|
||||
Review (pr_review_agent): no blocking issues; added one test exercising `clearTracked`'s mirror refresh. LiveCompile 127→128. Main untouched.
|
||||
|
||||
**LiveCompile arc complete: LC-1 … LC-8 + LC-6b + LC-7 revisit all shipped.**
|
||||
|
||||
@@ -14,6 +14,11 @@ you need to react to RT events from the UI, the existing
|
||||
`SynthesisEngineListener` lifecycle hook is the only fan-out the engine
|
||||
exposes today.
|
||||
|
||||
> This guide covers user-visible runtime surfaces. For **developer-side**
|
||||
> inspection — breakpointing a specific voice on the RT thread, reading a
|
||||
> generator's live output and inner state — see the DocC article `<doc:Debugging>`
|
||||
> (`Sources/Lyrebird/Lyrebird.docc/Debugging.md`).
|
||||
|
||||
---
|
||||
|
||||
## Part 1 — `LyrebirdMessage`
|
||||
|
||||
@@ -123,6 +123,103 @@ final class SineTone: SynthesizerBase {
|
||||
- `evaluate(graph:count:)` is `final` — the engine drives it automatically.
|
||||
- Do not override `evaluate` in subclasses; override `build` instead.
|
||||
|
||||
### ClosureSynthesizer — a graph without a subclass
|
||||
|
||||
When all you want is to hear a generator graph — a scratchpad line, a demo, a
|
||||
one-off voice, a test — `ClosureSynthesizer` supplies the graph from a closure
|
||||
instead of a `build()` override:
|
||||
|
||||
```swift
|
||||
try engine.add(ClosureSynthesizer { OscSin.Audio(freq: 440, mul: 0.1) })
|
||||
try engine.add(ClosureSynthesizer(bus: 0) { Pan2(input: saw, pan: 0) })
|
||||
```
|
||||
|
||||
The closure runs inside `build()` — once, on the main thread, at add time. Each
|
||||
instance is its own graph, so construct the generators **inside** the closure
|
||||
rather than handing it instances shared with another synthesizer (the same
|
||||
graph-copy-per-instance rule as any `SynthesizerBase`). A multi-channel source
|
||||
fans out across consecutive buses from `bus`, exactly like `output(bus:source:)`.
|
||||
There are no `@LiveParam` slots — reach for a named subclass once a voice needs
|
||||
live-controllable parameters.
|
||||
|
||||
## Debugging: per-instance debug tap
|
||||
|
||||
> Canonical reference: the DocC article `<doc:Debugging>`
|
||||
> (`Sources/Lyrebird/Lyrebird.docc/Debugging.md`) covers this plus inspecting inner
|
||||
> nodes and stepping a generator's compute loop. The summary below is a quick pointer.
|
||||
|
||||
`evaluate(graph:count:)` is `final`, so you cannot hook it directly. Instead override
|
||||
`debugTap(graph:count:outputs:)` — an `open` no-op the engine calls once per scheduling
|
||||
segment, **after** every output generator has run, but only when `debugTapEnabled` is set on
|
||||
that instance. The tap's *invocation* is compiled out of release builds (the call site is
|
||||
`#if DEBUG`); the method and flag still exist so an override compiles unconditionally, but
|
||||
the hook never fires in release.
|
||||
|
||||
This is the canonical place to set a breakpoint on one specific voice.
|
||||
|
||||
```swift
|
||||
final class FMTone: SynthesizerBase {
|
||||
@LiveParam var carrierFreq: Double = 440.0
|
||||
|
||||
override func build() {
|
||||
let mod: any Generator = OscSin.Audio(freq: 220.0) * 660.0
|
||||
output(bus: 0, source: OscSin.Audio(freq: $carrierFreq + mod) * 0.18)
|
||||
}
|
||||
|
||||
override func debugTap(
|
||||
graph: SynthGraph,
|
||||
count: Int,
|
||||
outputs: [any Generator]
|
||||
) {
|
||||
// 👈 Breakpoint here. The RT thread halts with self, outputs, and graph
|
||||
// in scope. In the debugger:
|
||||
// po self.carrierFreq
|
||||
// po outputs.first?._cachedResult // Out's samples this block
|
||||
// po outputs.first?._result[0].prefix(8) // first 8 samples
|
||||
let block: Int = count
|
||||
_ = block
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Enable it per instance — flip only the voice you want to inspect:
|
||||
|
||||
```swift
|
||||
let voice: FMTone = FMTone()
|
||||
#if DEBUG
|
||||
voice.debugTapEnabled = true // main thread, before add — only this voice taps
|
||||
#endif
|
||||
try engine.add(voice)
|
||||
```
|
||||
|
||||
In a poly pool, gate the flag so a single note breaks:
|
||||
|
||||
```swift
|
||||
for note: Int in chord {
|
||||
let v: FMTone = FMTone()
|
||||
v.debugTapEnabled = (note == 60) // break only middle C
|
||||
try engine.add(v)
|
||||
}
|
||||
```
|
||||
|
||||
**What you get when it halts**
|
||||
|
||||
| In scope | Holds |
|
||||
|---|---|
|
||||
| `self` | Every `let` / `@LiveParam` on the voice. |
|
||||
| `outputs` | This instance's registered output-generator tree. Each generator's `_cachedResult` / `_result` = samples just computed for this block. |
|
||||
| `graph.engine` | Sample rate, block size, bus pool — read a bus mid-render. |
|
||||
| `count` | Samples in this scheduling segment (`≤ 512`; the engine splits a block at scheduled-event boundaries, so the tap can fire several times per audio block). |
|
||||
|
||||
**Rules**
|
||||
|
||||
- Runs on the **RT render thread.** A breakpoint is fine (it halts the thread and you look).
|
||||
Any *code* in the override obeys the RT rules — no allocation, locks, `print`, or `String`.
|
||||
- Fires per scheduling segment — hundreds of hits/sec while audio runs. Use a conditional
|
||||
breakpoint (`count == 512`) or an override-local frame counter to break every Nth.
|
||||
- Want continuous inspection without halting? Snapshot into a pre-allocated ring in the tap
|
||||
and drain it on the main thread instead — see `NodeTreeMirror` for the pattern.
|
||||
|
||||
## Adding to the Engine
|
||||
|
||||
```swift
|
||||
|
||||
@@ -3,6 +3,13 @@
|
||||
A step-by-step guide to implementing correct, RT-safe generators in Lyrebird.
|
||||
Every built-in generator in `Sources/Lyrebird/Generators/` follows the patterns here.
|
||||
|
||||
> Before you write a whole type: for one-off custom sample-accurate DSP — especially a
|
||||
> **single-sample feedback loop** (one-pole, waveguide, comb/allpass) — reach for `SampleLoop`
|
||||
> (`Sources/Lyrebird/Generators/Core/SampleLoop.swift`) first. It gives an RT-safe,
|
||||
> allocation-free per-sample body with typed `inout` feedback state and channel inference, no
|
||||
> new `Generator` declaration. Promote to a full generator (this guide) when you want
|
||||
> parameters, Quick Help, reuse, and raw-pointer speed.
|
||||
|
||||
---
|
||||
|
||||
## 1. Protocol Choice — `AudioGenerator` vs `ControlGenerator`
|
||||
@@ -609,6 +616,12 @@ final class MyGenerator: GeneratorBase, AudioGenerator {
|
||||
|
||||
## 10. Testing Checklist
|
||||
|
||||
> Debugging a generator that compiles but computes the wrong numbers: tag the
|
||||
> instance with `GeneratorBase.debugTag`, set an LLDB conditional breakpoint on its
|
||||
> `_computeSamples`, and/or read its post-block output from a Synthesizer debug tap.
|
||||
> Full workflow in the DocC article `<doc:Debugging>`
|
||||
> (`Sources/Lyrebird/Lyrebird.docc/Debugging.md`).
|
||||
|
||||
Write tests for every new generator using Swift Testing (`@Test`, `#expect`, `@Suite`).
|
||||
|
||||
> The `makeTestEngine`, `makeSynthGraph`, and `advanceBlock` helpers are defined in `Tests/LyrebirdTests/TestHelpers.swift`. Test files must use `@testable import LyrebirdSynth` and belong to the `LyrebirdTests` target to access them.
|
||||
|
||||
@@ -356,6 +356,18 @@ position in `[-1, 1]` and apply their own internal scaling.
|
||||
|
||||
---
|
||||
|
||||
## Custom multi-channel DSP — `SampleLoop`
|
||||
|
||||
`SampleLoop` (`Sources/Lyrebird/Generators/Core/SampleLoop.swift`), the closure escape hatch
|
||||
for custom per-sample DSP, is channel-aware on both ends. Output channel count is inferred as
|
||||
`max` over its inputs' `outputChannelCount` (or set explicitly via `channels:`); each input is
|
||||
broadcast up to that width (mono spreads; a channel count that is neither `1` nor the output
|
||||
width `precondition`-traps at init, matching `BinaryOpGenerator`); and the body receives
|
||||
`numChannels` so one width-agnostic loop covers mono, stereo, or N-channel signals. Per-channel
|
||||
feedback state is sized from `numChannels` via the `makeState` argument.
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- `Sources/Lyrebird/Generators/ChannelSelect.swift` — `ChannelSelect.Audio/.Control`, `[n]` subscript
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
# 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.
|
||||
Reference in New Issue
Block a user