# Live coding with `LyrebirdScratchView` A SwiftUI scratchpad for hot-swapping snippets through `LyrebirdLiveCompile`. ## Overview `LyrebirdScratchView` pairs an `NSTextView`-backed Swift editor with a `LiveSession` that owns the audio engine. Pressing **⌘↩** wraps the snippet body in the standard harness, shells out to `swiftc`, `dlopen`s the resulting dylib, and calls the snippet's `lyrebird_snippet_entry` with a `SnippetContext` bound to the session. Synthesizers played via `context.play(_:)` are tracked, so the next non-additive run replaces them. **⌘⇧↩** layers a new snippet on top of the prior ones. Compile diagnostics from a failing snippet are parsed by `DiagnosticParser` and rendered beneath the editor with line numbers already remapped from the wrapped source back to the user's snippet coordinates. The view is macOS-only — `LyrebirdLiveCompile` shells out to `swiftc`, which is unavailable on iOS. The nested `LiveCompile/` sub-package declares `platforms: [.macOS(.v15)]` and cannot be added to an iOS target. ## Hosting ```swift import LyrebirdSynth import LyrebirdUI // LyrebirdWindow import LyrebirdLiveCompile // LiveSession import LyrebirdLiveCompileUI // LyrebirdScratchView let engine = SynthesisEngine(/* … */) try engine.start() let session = LiveSession(engine: engine) let window = LyrebirdWindow(title: "Lyrebird Scratch", width: 640, height: 480) window.open { LyrebirdScratchView(session: session) } ``` ## Keyboard shortcuts | Shortcut | Action | |----------|--------| | ⌘↩ | Compile + run. Removes the previous run's *anonymous* synths first (named slots persist). | | ⌘⇧↩ | Compile + run additively. Keeps previously played synths in the engine. | The toolbar exposes both as buttons plus a `Clear Synths` button that calls ``LyrebirdScratchModel/clearTracked()`` — a full reset that removes both the anonymous tracked synths and every named slot. The engine status pill at the top-left is also a **Start/Stop** button (``LyrebirdScratchModel/toggleEngine()``): green "engine running" when live, red "▶ start engine" when stopped. A snippet is only audible while the engine is running; the host normally starts it at launch, but this lets the user recover from a failed start (e.g. no output device) without relaunching. ## Snippet API surface A snippet has one local in scope: ```swift context: SnippetContext ``` `SnippetContext`: - `context.engine` — the host `SynthesisEngine`. - `context.play(_:)` — add a `Synthesizer` to the engine and register it for cleanup on the next non-additive run. - `context.play { }` — play a bare generator graph, no `SynthesizerBase` subclass needed (wraps it in a `ClosureSynthesizer`). - `context.play(slot:_:)` / `context.play(slot:) { }` — play into a **named slot** (see below). - `context.reportMessage(_:)` — write back to the host (used by tests; handy for `print`-style probes during development). ## Named slots (hot-swap) `context.play(slot: "name") { … }` installs a voice under a name. Re-running a slot definition **replaces just that voice in place** — the new voice starts before the old one is removed (a brief overlap, no gap), while everything else keeps playing: ```swift context.play(slot: "bass") { OscSaw.Audio(freq: 55, mul: 0.2) } context.play(slot: "lead") { Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0) } ``` Unlike anonymous `context.play`, a slotted voice is **not** torn down by the next non-additive (⌘↩) run — that is what lets you edit and re-evaluate one voice at a time while the rest of the patch keeps going (the `Pdef` idiom). | API | Lifetime | |-----|----------| | `context.play(_:)` / `context.play { }` | Removed on the next non-additive run. | | `context.play(slot:) { }` | Persists; a same-name re-run replaces it in place. | Clear a slot with `context.session.clearSlot("bass")`, all slots with `context.session.clearSlots()`. The toolbar **Clear Synths** button is a full reset — anonymous synths *and* every slot. A slot definition you delete from the buffer and stop re-running is *not* auto-removed (a `Pdef`-style gotcha) — clear it explicitly or hit Clear Synths. ## Threading All UI is `@MainActor`-isolated. The Run / Run Additive actions dispatch a `Task` that awaits ``LyrebirdScratchModel/run(additive:)``, which awaits `LiveSession.compileAndRunAsync` — the `swiftc` subprocess runs on a background `Task.detached`, so the editor stays responsive while a compile is in flight. The snippet entry then resumes on the main actor to touch engine + UI state. `LyrebirdScratchMenuController` disables the Run / Run Additive commands whenever ``ReevalState/canEvaluate`` is `false` (a compile is in flight or the buffer is empty); `run(additive:)` additionally guards re-entrancy on ``LyrebirdScratchModel/isCompiling``. ## Re-evaluation readiness ``LyrebirdScratchModel/reevalState`` publishes a ``ReevalState`` — a structured signal for *when* a re-evaluation is available and whether it would change anything: | State | Meaning | |-------|---------| | `.empty` | Buffer is blank. Nothing to run. | | `.dirty` | Edited since the last run (or never run). An eval is available. | | `.compiling` | A compile + run is in flight. | | `.queued(untilBeat:)` | Compiled; a quantized slot swap is scheduled but not yet audible (see below). | | `.clean` | Buffer matches what is currently playing. | | `.failed(diagnosticCount:)` | The last run failed to compile. | The editor renders this as a colored dot + label in the status bar. ``ReevalState/canEvaluate`` is `true` whenever a run can be triggered right now (non-blank buffer, no compile already running) — hosts can gate their own Run controls on it. ## Quantized swaps (on-beat latency masking) A `swiftc` build finishes a few hundred milliseconds after ⌘↩ — long enough to feel loose against a running groove. Point the session at a `LyrebirdClock` and choose a `SwapQuantize` mode, and named-slot swaps land on the next musical boundary instead of whenever the compile happens to finish: ```swift let clock = LyrebirdClock(engine: engine, bpm: 120) let session = LiveSession(engine: engine) session.swapClock = clock session.swapQuantize = .nextBar(beatsPerBar: 4) // .immediate | .nextBeat | .nextBar ``` Now `context.play(slot: "bass") { … }` **schedules** the new voice's add and the old voice's removal at the same upcoming boundary sample time (`engine.schedule` / `engine.remove(_:at:)`), so the swap is glitch-free and on-grid. Because the change is quantized to a boundary that is comfortably past the compile, the compile latency is hidden: you edit, hit ⌘↩, and the change drops exactly on the downbeat. While the swap is pending, ``LyrebirdScratchModel/reevalState`` reads `.queued(untilBeat:)` (a purple badge); it settles to `.clean` once the clock passes the boundary (or `.dirty` if you edit again first). ``LiveSession/pendingSwapBeat`` exposes the target beat. `.immediate` (or no `swapClock`) makes swaps take effect at once. Anonymous `context.play` is unaffected; quantization applies to named slots only. Re-running a slot while its previous quantized swap is still pending is safe: the previous voice's removal is always scheduled no earlier than its own add, so a just-scheduled voice is never left orphaned. ## First-run latency (module-cache prewarm) A snippet compiles in ~0.1 s once the Swift/Clang module cache is warm — but the *first* compile of a session pays ~2–3 s to build the precompiled module for the large `LyrebirdSynth` interface. Left alone, that cost lands on the user's first ⌘↩ (the "time to first sound"). ``LiveSession/prewarm()`` moves it into the background: it type-checks a trivial import-only snippet on a detached `.utility` task, warming swiftc's default module cache so the first real compile is already fast. `LyrebirdScratchView` calls it from `onAppear` (idempotent — safe to call again). It is *not* wired into `LyrebirdScratchModel.init`, so constructing a model never shells out to swiftc; a headless host should call `session.prewarm()` at launch itself. A prewarm never throws: a failure (e.g. a missing toolchain) leaves ``LiveSession/isPrewarmed`` `false` — so a later call retries, and the first real compile simply pays the cold build itself and surfaces any real error through its own diagnostics. > Note: the prewarm deliberately uses swiftc's default module cache rather than a > pinned `-module-cache-path`. A freshly-built dedicated cache produces module > metadata that diverges from the already-loaded `libLyrebirdLiveCompileDynamic`, > which turns a benign ObjC class-duplication warning into a hard cast crash when > a snippet is `dlopen`'d. ## Code completion Swift code completion is provided by the toolchain's `sourcekit-lsp`, driven over stdio by ``SourceKitLSPClient`` and bridged to the editor by ``SnippetCompletionService``. Typing `.` after an expression pops the standard completion window; the candidates are the real symbols the snippet would see at compile time — `LyrebirdSynth` generators (`OscSin.` → `Audio`, `Control`, …), the injected `context` (`context.` → `play`, `engine`, …), and the Swift standard library. How it resolves those symbols for an otherwise free-standing file: the service maintains a small 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. sourcekit-lsp's compilation-database build system reads that file. The caret is mapped through the harness line offset, so a completion request at the user's row hits the right row in the wrapped document. Completion is Swift-mode only — graph-DSL mode is interpreted and needs no compiler — and best-effort: any LSP failure yields no candidates rather than an error. ## Limitations - macOS only. - Syntax highlighting is a lightweight built-in lexer (`ScratchSwiftTokenizer`) — approximate by design, not a full parser. Completion (above) uses the real compiler via sourcekit-lsp; the two are independent. - Completion currently triggers on `.`; a manual-invoke shortcut is a possible follow-up. - The host `.app` must not be sandboxed and must allow library validation to be disabled, since `swiftc` is invoked via `Process` and the resulting unsigned dylib is `dlopen`'d. ## Snippet memory (the dylib leak) Every ⌘↩ compiles a fresh dylib and `dlopen`s it; those dylibs are **never unloaded**, so a session's mapped memory grows one dylib per successful evaluation. ``LiveSession/loadedSnippetCount`` reports how many are mapped — a host can nudge the user to restart after a very long session. This is a hard limit of the compiled approach, not an oversight. Reclaiming the memory would require `dlclose`, which is **unsafe** for these dylibs: `dlopen` registers a Swift dylib's type metadata and protocol-conformance records into process-global runtime caches, and `dlclose` unmaps the dylib without deregistering them — leaving those caches pointing into freed memory, so a later type operation can crash. That holds even after every synth a snippet produced has been removed. A refcount-gated `dlclose` was therefore considered and rejected rather than shipped as a crash-prone flag. ``LiveSession/resetAll()`` (the toolbar **Clear Synths**) is the pressure-relief valve: it stops all snippet audio — removing every anonymous and slotted synth — and gives a clean slate without tearing down the engine, but it does not reclaim the mapped dylibs. Only restarting the process does. The **Graph DSL mode** below sidesteps dylibs entirely and is the structural fix. The editor makes this visible rather than silent: the engine bar shows a **"snippets: N"** count (`LyrebirdScratchModel.loadedSnippetCount`), and once it crosses ``LyrebirdScratchModel/snippetRestartThreshold`` (50) the count turns orange and a warning banner appears — nudging the user to restart to reclaim the memory, or to switch to Graph DSL mode (which maps no dylibs). It is a nudge, not a hard stop: the choice stays with the user. ## Graph DSL mode (instant, no compile) The status-bar toggle switches the editor between two evaluators: - **Swift** — the full snippet path above: swiftc compiles a dylib, which is `dlopen`'d and run. The whole language, `SynthesizerBase` subclasses, arbitrary code — at the cost of a compile and a permanently mapped dylib. - **Graph DSL** — the interpreted graph-DSL. The buffer is lexed, parsed, and built into a generator graph **in-process**: no swiftc, no dylib, microseconds instead of a compile round-trip, and nothing leaks. The trade is scope — only generator-graph *expressions*, not arbitrary Swift. A DSL buffer is one statement per line: ``` bass = OscSawtooth.Audio(freq: 55, mul: 0.15) Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0) ``` - A **bare** line plays anonymously and is tracked, so a non-additive re-run (⌘↩) replaces it — exactly like `context.play { … }`. - A **named** line (`name = …`) installs a persistent, hot-swappable named slot (like `context.play(slot:)`): it survives a non-additive re-run and is swapped in place on the next evaluation, so you can mutate one voice while others keep playing. Quantized swaps apply here too. Generators are spelled **exactly** as in a Lyrebird `build()` — `OscSin.Audio(freq:)`, `.Control` for the control-rate variant — so a graph you like in the editor pastes into a project unchanged (only the wrapping differs; see the `LyrebirdGraphDSL` design notes). The bare `OscSin(…)` no-rate form is a DSL shorthand for the audio variant. The whole program is built **before** any engine mutation, so a syntax or build error leaves the currently-playing graph untouched — a bad edit never drops audio. Errors surface in the same gutter as swiftc diagnostics: a parse error points at its line/column; a build error (unknown generator, bad argument) reports at file scope. See ``LyrebirdScratchModel/switchMode(to:)`` and ``LiveSession/runGraphDSL(_:additive:resources:)``. ## Topics - ``LyrebirdScratchView`` - ``LyrebirdScratchModel`` - ``ScratchEvalMode``