bugfixes, better MusicXML support and 1.1.0

This commit is contained in:
2026-06-10 08:41:07 -07:00
parent 6d3a0930a1
commit f59fd3b55a
228 changed files with 32271 additions and 2586 deletions
-109
View File
@@ -1,109 +0,0 @@
// CLICommand.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Top-level commands parsed from `CommandLine.arguments`.
public enum CLICommand: Equatable {
/// Build the current package, then launch `swift repl` with Lyrebird available.
case repl
/// Enter the LineNoise-powered `lyrebird>` interactive shell (no subcommand given).
case interactive
/// Print usage help.
case help
/// Print the lyrebird version string.
case version
/// Scaffold a new Lyrebird project in a directory named `name` using `template`.
/// When `lyrebirdPath` is set, the generated `Package.swift` and (where
/// applicable) `.xcodeproj` reference Lyrebird as a local SPM package at
/// that absolute path instead of pulling from the published Git URL.
case new(name: String, template: ProjectTemplate, lyrebirdPath: String?)
/// Run the current project with `swift run`.
case run(release: Bool)
/// Export a named Synthesizer template to a Swift source file.
/// When `overwrite` is `true`, an existing file at the destination is replaced.
case export(name: String, to: String?, overwrite: Bool)
/// Install Lyrebird Xcode file templates to the user template directory.
/// When `force` is `true`, replaces any existing installation.
case installTemplates(force: Bool)
/// Remove Lyrebird Xcode file templates from the user template directory.
case uninstallTemplates
/// Parse the command from a raw arguments array (typically `CommandLine.arguments`).
///
/// - Parameter arguments: The full argument vector. `arguments[0]` is the binary name;
/// `arguments[1]` (if present) is the subcommand.
/// - Returns: The matching command, or `.help` for unrecognised or malformed subcommands.
public static func parse(_ arguments: [String]) -> CLICommand {
guard arguments.count > 1 else { return .interactive }
switch arguments[1].lowercased() {
case "repl":
return .repl
case "version", "--version":
return .version
case "help", "--help", "-h":
return .help
case "new":
guard arguments.count > 2, !arguments[2].isEmpty else { return .help }
// If the positional argument looks like a flag, the user omitted the name.
guard !arguments[2].hasPrefix("-") else { return .help }
let template: ProjectTemplate
if let tIdx: Array<String>.Index = arguments.firstIndex(of: "--template"),
tIdx + 1 < arguments.count,
let t: ProjectTemplate = ProjectTemplate(string: arguments[tIdx + 1]) {
template = t
} else {
template = .basic
}
// Optional `--lyrebird-path <abs-path>` for local-checkout use.
// Value must not be a flag token.
let lyrebirdPath: String?
if let pIdx: Array<String>.Index = arguments.firstIndex(of: "--lyrebird-path"),
pIdx + 1 < arguments.count,
!arguments[pIdx + 1].hasPrefix("-") {
lyrebirdPath = arguments[pIdx + 1]
} else {
lyrebirdPath = nil
}
return .new(name: arguments[2],
template: template,
lyrebirdPath: lyrebirdPath)
case "run":
let release: Bool = arguments.contains("--release")
return .run(release: release)
case "install-templates":
let force: Bool = arguments.contains("--force")
return .installTemplates(force: force)
case "uninstall-templates":
return .uninstallTemplates
case "export":
guard arguments.count > 2, !arguments[2].isEmpty else { return .help }
let synthName: String = arguments[2]
// If the positional argument looks like a flag, the user omitted the name.
guard !synthName.hasPrefix("-") else { return .help }
// Look for `--to <path>` anywhere after the subcommand.
// Guard that the value following `--to` is not itself a flag token.
let toPath: String?
if let toIdx: Array<String>.Index = arguments.firstIndex(of: "--to"),
toIdx + 1 < arguments.count,
!arguments[toIdx + 1].hasPrefix("-") {
toPath = arguments[toIdx + 1]
} else {
toPath = nil
}
let overwrite: Bool = arguments.contains("--overwrite")
return .export(name: synthName, to: toPath, overwrite: overwrite)
default:
return .help
}
}
}
+1 -1
View File
@@ -285,7 +285,7 @@ public enum InteractiveShell {
print("""
Commands:
new <name> [--template <t>] Scaffold a new Lyrebird Swift Package
Templates: basic (default), demo, ui-demo, nrt
Templates: basic (default), demo, ui-demo, nrt, score
run [--release] Build and run the current project
export <name> [--to p] Export a Synthesizer template to a .swift file
install-templates [--force] Install Xcode file templates to user dir
+15 -2
View File
@@ -116,11 +116,24 @@ struct LyrebirdCLIMain {
} else {
resolvedPath = nil
}
// Report which Lyrebird dependency the generated Package.swift will pin.
let effectivePath: String? = resolvedPath ?? ProjectScaffolder.defaultLyrebirdCheckoutPath
if let path: String = effectivePath {
print("Lyrebird dependency: local checkout at \(path)")
} else {
fputs("""
warning: no local Lyrebird checkout found; pinning published \
\(ProjectScaffolder.lyrebirdPackageURL)@\(ProjectScaffolder.lyrebirdMinimumVersion). \
The generated template may use API newer than that release — if it \
fails to build, re-run with --lyrebird-path <checkout>.
""", stderr)
}
do {
try ProjectScaffolder.scaffold(
name: name,
template: template,
lyrebirdPath: resolvedPath
lyrebirdPath: effectivePath
)
print("Created \(name)/")
} catch ProjectScaffolder.Error.projectExists(let n) {
@@ -182,7 +195,7 @@ struct LyrebirdCLIMain {
Commands:
new <name> [--template <t>] Scaffold a new Lyrebird Swift Package
Templates: basic (default), demo, ui-demo, nrt
Templates: basic (default), demo, ui-demo, nrt, score
run [--release] Build and run the current project
export <name> [--to p] Export a Synthesizer template to a .swift file
install-templates [--force] Install Xcode file templates (Generator,
-100
View File
@@ -1,100 +0,0 @@
// ProjectRunner.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
// MARK: - ProjectRunner
/// Wraps `swift run` to build and launch the current Lyrebird project.
///
/// `lyrebird run` and `lyrebird run --release` are thin wrappers: they locate the
/// `swift` binary and exec `swift run` (optionally with `-c release`) in the current
/// working directory. stdin / stdout / stderr are inherited so compiler output and
/// runtime output appear directly in the user's terminal.
///
/// The runner does **not** verify that a `Package.swift` is present before launching —
/// SPM provides a clear error message in that case.
public enum ProjectRunner {
// MARK: - Errors
/// Errors thrown by `ProjectRunner`.
public enum Error: Swift.Error, Equatable {
/// The `swift` binary could not be found on this system.
case swiftNotFound
/// The process exited with a non-zero status.
case buildFailed(exitCode: Int32)
}
// MARK: - Public API
/// Build and run the Swift package in `directory`.
///
/// - Parameters:
/// - release: When `true`, passes `-c release` to `swift run` for an optimised build.
/// - directory: The directory containing `Package.swift`.
/// Defaults to the current working directory.
/// - Throws: `ProjectRunner.Error.swiftNotFound` if the toolchain is absent;
/// `ProjectRunner.Error.buildFailed` if `swift run` exits non-zero.
public static func run(
release: Bool = false,
in directory: String = FileManager.default.currentDirectoryPath
) throws {
let process: Process = try makeProcess(release: release, in: directory)
try process.run()
process.waitUntilExit()
let exitCode: Int32 = process.terminationStatus
guard exitCode == 0 else {
throw Error.buildFailed(exitCode: exitCode)
}
}
// MARK: - Internal
/// Builds a `Process` configured to run `swift run` (or `swift run -c release`).
///
/// Exposed for testing so callers can inspect the process configuration without
/// actually launching a build.
///
/// - Parameters:
/// - release: When `true`, appends `-c release` to the swift arguments.
/// - directory: Working directory for the SPM invocation.
/// - Throws: `ProjectRunner.Error.swiftNotFound` if the toolchain is absent.
public static func makeProcess(
release: Bool = false,
in directory: String = FileManager.default.currentDirectoryPath
) throws -> Process {
let swiftPath: String = try findSwift()
var arguments: [String] = ["run"]
if release {
arguments += ["-c", "release"]
}
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: swiftPath)
process.arguments = arguments
process.currentDirectoryURL = URL(fileURLWithPath: directory)
// stdin / stdout / stderr intentionally not set — inherited for interactive output.
return process
}
// MARK: - Helpers
/// Returns the path to the `swift` binary.
///
/// Checks, in order:
/// - `/usr/bin/swift` — Xcode Command Line Tools / Xcode toolchain
/// - `/usr/local/bin/swift` — standalone toolchain (Intel Mac default)
/// - `/opt/homebrew/bin/swift` — Homebrew toolchain on Apple Silicon
///
/// Throws `ProjectRunner.Error.swiftNotFound` if none of the candidates exist.
static func findSwift() throws -> String {
let candidates: [String] = ["/usr/bin/swift", "/usr/local/bin/swift", "/opt/homebrew/bin/swift"]
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
return path
}
throw Error.swiftNotFound
}
}
+230 -14
View File
@@ -18,6 +18,9 @@ public enum ProjectTemplate: String, CaseIterable, Equatable {
case uiDemo = "ui-demo"
/// Non-real-time render: `NRTDriver` writes a `.caf` file and exits.
case nrt = "nrt"
/// Score / MusicXML render: builds a `Score` with the DSL, exports a
/// `.musicxml` document, and renders the score offline with `NRTDriver`.
case score = "score"
/// macOS `.app` bundle wrapping an AppKit + SwiftUI host of a `@UIParam` synth.
/// Generates a full `<name>.xcodeproj` referencing Lyrebird via remote SPM dep.
case macosUIXcode = "macos-ui-xcode"
@@ -35,6 +38,8 @@ public enum ProjectTemplate: String, CaseIterable, Equatable {
case "demo": self = .demo
case "ui-demo", "uidemo", "ui_demo": self = .uiDemo
case "nrt": self = .nrt
case "score", "score-musicxml", "scoremusicxml", "musicxml":
self = .score
case "macos-ui-xcode", "macosuixcode", "macos_ui_xcode":
self = .macosUIXcode
case "ios-ui", "iosui", "ios_ui":
@@ -52,7 +57,7 @@ public enum ProjectTemplate: String, CaseIterable, Equatable {
/// (auv3) an `.appex` extension target — none of which SwiftPM can express.
public var shipsXcodeProject: Bool {
switch self {
case .basic, .demo, .uiDemo, .nrt: return false
case .basic, .demo, .uiDemo, .nrt, .score: return false
case .macosUIXcode, .iosUI, .auv3: return true
}
}
@@ -95,6 +100,44 @@ public enum ProjectScaffolder {
// MARK: - Public API
/// Absolute path to the Lyrebird checkout this CLI was *built* from, derived
/// from the compile-time source location of this file
/// (`<root>/Sources/LyrebirdCLI/ProjectScaffolder.swift`).
///
/// Used as the default SPM dependency for scaffolded projects when the caller
/// passes no explicit `--lyrebird-path`, so generated projects track the
/// current `main` API rather than the published `from:` tag — which lags
/// unreleased Score/Generator features (e.g. `Part(clef:)`,
/// `ScoreEvent.performedDuration`). This is the pre-1.0-stable policy: the
/// template source and the dependency it pins both come from one checkout, so
/// they never drift.
///
/// Returns `nil` when the derived root no longer holds the Lyrebird
/// `Package.swift` (the binary was installed away from its source tree);
/// callers then fall back to the remote versioned dependency.
static var defaultLyrebirdCheckoutPath: String? {
lyrebirdCheckoutRoot(forSourceFile: #filePath)
}
/// Testable core of ``defaultLyrebirdCheckoutPath``. Given a source file at
/// `<root>/Sources/LyrebirdCLI/<file>.swift`, walks up three directory
/// levels to `<root>` and returns it iff `<root>/Package.swift` exists and
/// names Lyrebird. Returns `nil` otherwise. Split out so the happy- and
/// nil-paths can be unit-tested with synthetic paths (the computed property
/// is hard-wired to its own `#filePath`).
static func lyrebirdCheckoutRoot(forSourceFile sourceFile: String) -> String? {
let root: URL = URL(fileURLWithPath: sourceFile)
.deletingLastPathComponent() // strip <file>.swift → Sources/LyrebirdCLI/
.deletingLastPathComponent() // → Sources/
.deletingLastPathComponent() // → <root>/
let manifest: String = root.appendingPathComponent("Package.swift").path
guard FileManager.default.fileExists(atPath: manifest) else { return nil }
// Guard against pointing at an unrelated parent Package.swift.
guard let contents: String = try? String(contentsOfFile: manifest, encoding: .utf8),
contents.contains("Lyrebird") else { return nil }
return root.path
}
/// Scaffold a new Lyrebird project named `name` inside `parentDirectory`.
///
/// - Parameters:
@@ -102,10 +145,13 @@ public enum ProjectScaffolder {
/// - template: Starter template style (default `.basic`).
/// - parentDirectory: Directory in which to create the project folder.
/// Defaults to the current working directory.
/// - lyrebirdPath: Optional absolute path to a local Lyrebird checkout
/// to wire into the generated `Package.swift` as a `path:` dependency
/// (useful when developing against an unmerged Lyrebird branch).
/// `nil` → use the published GitHub package as the dependency.
/// - lyrebirdPath: Absolute path to a local Lyrebird checkout to wire into
/// the generated `Package.swift` as a `path:` dependency. `nil` → use
/// the published remote package. This is a faithful passthrough: the
/// `new` CLI command resolves `nil` to ``defaultLyrebirdCheckoutPath``
/// *before* calling this (see `LyrebirdCLI.runNew`), so default
/// scaffolds track current `main`; direct library callers get the
/// documented `nil` → remote behaviour.
/// - Throws: `ProjectScaffolder.Error` on name validation failure or file system errors.
public static func scaffold(
name: String,
@@ -252,7 +298,7 @@ public enum ProjectScaffolder {
case .auv3:
try writeAUv3Files(name: name, projectRoot: projectRoot,
lyrebirdPath: lyrebirdPath, fm: fm)
case .basic, .demo, .uiDemo, .nrt:
case .basic, .demo, .uiDemo, .nrt, .score:
// Unreachable — shipsXcodeProject filters these out at dispatch.
try? fm.removeItem(atPath: projectRoot)
throw Error.fileSystemError(
@@ -324,7 +370,7 @@ public enum ProjectScaffolder {
// the dep is local or remote.
let targetDeps: String
switch template {
case .basic, .demo, .nrt:
case .basic, .demo, .nrt, .score:
targetDeps = #""Lyrebird""#
case .uiDemo:
targetDeps = #""Lyrebird", .product(name: "LyrebirdUI", package: "Lyrebird")"#
@@ -382,6 +428,7 @@ public enum ProjectScaffolder {
case .demo: return mainSwiftDemo(name: name)
case .uiDemo: return mainSwiftUIDemo(name: name)
case .nrt: return mainSwiftNRT(name: name)
case .score: return mainSwiftScore(name: name)
case .macosUIXcode, .iosUI, .auv3:
// Xcode-bearing templates don't emit a `main.swift` under
// `Sources/<name>/`. Dispatch never reaches this function for
@@ -416,7 +463,7 @@ public enum ProjectScaffolder {
fatalError("Engine failed to start: \\(error)")
}
print("\\(name) running — press Ctrl+C to stop")
print("\(name) running — press Ctrl+C to stop")
RunLoop.main.run()
"""
}
@@ -464,7 +511,7 @@ public enum ProjectScaffolder {
fatalError("Engine.add failed: \\(error)")
}
print("\\(name) running — press Ctrl+C to stop")
print("\(name) running — press Ctrl+C to stop")
print("Update tone.freq or tone.amp from the REPL to change parameters.")
RunLoop.main.run()
"""
@@ -548,6 +595,170 @@ public enum ProjectScaffolder {
"""
}
// MARK: score
private static func mainSwiftScore(name: String) -> String {
"""
// \(name) — Score / MusicXML render
import Foundation
import LyrebirdSynth
// MARK: - ScoreVoice
/// One self-freeing voice per score event. The envelope's `freeNode`
/// done-action removes the synth when its note finishes, so scheduled
/// voices never accumulate during the offline render.
final class ScoreVoice: SynthesizerBase {
let freqHz: Double
let amp: Double
let durSeconds: Double
let pan: Double
init(freqHz: Double, amp: Double, durSeconds: Double, pan: Double = 0.0) {
self.freqHz = freqHz
self.amp = amp
self.durSeconds = durSeconds
self.pan = pan
super.init()
}
override func build() {
let attack = 0.01
let release = 0.06
let sustain = max(0.0, durSeconds - attack - release)
let envelope = Envelope(
levels: [0.0, 1.0, 0.8, 0.0],
durations: [attack, sustain, release],
curves: [-4.0, 0.0, -6.0]
)
let osc = OscSawtooth.Audio(freq: freqHz)
let env = EnvelopeGen.Control(envelope: envelope, doneAction: .freeNode)
output(bus: 0, source: Pan2(input: osc * env * amp, pan: pan))
}
}
// MARK: - Build the score
let bpm = 120.0
let secondsPerBeat = 60.0 / bpm
// Author music with the Score DSL: Note, Rest, Chord, Tuplet, dynamics,
// and articulations. Pitch spelling (letter + accidental) is preserved
// through MusicXML export. `Generate` and `PatternNotes` add algorithmic
// generation (see the "texture" part below).
//
// Further notation (see the Lyrebird ScoreSystem docs): Slur / Crescendo /
// Diminuendo spans, per-note `spanners:` (overlapping spans, glissandi /
// slides), per-note `display:` (NoteDisplay — notehead/size/hide stem or
// beam), `Section("…") { }` blocks with rehearsal marks, and a `pageLayout:`
// (PageLayout — page size, orientation, margins).
let score = Score(bpm: bpm, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
// A crescendo hairpin over the opening arpeggio (notation-only).
Crescendo {
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
Note(.named(.e, 5), dur: .quarter, dyn: .mf, art: .staccato)
Note(.named(.g, 5), dur: .quarter, dyn: .f, art: .accent)
}
Rest(dur: .quarter)
Tuplet(3, inTimeOf: 2) {
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
}
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .tenuto)
}
Part("bass", channel: 1, clef: .bass) {
Note(.named(.c, 3), dur: .whole, dyn: .mp)
Note(.named(.g, 2), dur: .half, dyn: .p)
Note(.named(.c, 3), dur: .half, dyn: .mp, art: .tenuto)
}
// Texture — algorithmic generation. `Generate` maps an index range
// through the builder; `PatternNotes` pulls from a `Pattern` source.
Part("texture", channel: 2) {
Generate(8) { i in
Note(midi: 72 + (i % 6) * 2, dur: .sixteenth, dyn: .pp, art: .staccato)
}
PatternNotes(count: 4, midi: Pattern.series(start: 60, step: 3, length: 4), dur: .eighth, dyn: .p)
}
}
// MARK: - Output location
// Write next to this project's source rather than the launch directory.
// `LyrebirdPaths.projectRoot()` walks up from this file to the folder
// containing Package.swift, so output lands in the project regardless of
// how the binary is launched (lyrebird run, swift run, or Xcode — whose
// working directory is DerivedData). Dev-time convenience; for a shipped
// app writing user data, use `LyrebirdPaths.documents` instead.
let outputDir = LyrebirdPaths.projectRoot() ?? LyrebirdPaths.currentWorkingDirectory
// MARK: - Export MusicXML
let xmlURL = outputDir.appendingPathComponent("score.musicxml")
do {
let xml = score.toMusicXMLString()
try xml.write(to: xmlURL, atomically: true, encoding: .utf8)
print("MusicXML written → \\(xmlURL.path)")
} catch {
fputs("MusicXML export failed: \\(error)\\n", stderr)
exit(1)
}
// Round-trip sanity check: parse the document back in and compare counts.
do {
let restored = try Score.fromMusicXML(data: score.toMusicXMLData())
print("Round-trip events: \\(score.allEvents.count) → \\(restored.allEvents.count)")
} catch {
fputs("MusicXML round-trip failed: \\(error)\\n", stderr)
}
// MARK: - Render the score offline
let tailSeconds = 1.5
let renderDuration = score.totalBeats * secondsPerBeat + tailSeconds
let outputURL = outputDir.appendingPathComponent("score.caf")
let engine = SynthesisEngine(
blockSize: \(scaffoldDefaultBlockSize),
sampleRate: \(scaffoldDefaultSampleRate),
numOutputChannels: \(scaffoldDefaultOutputChannels),
numInputChannels: 0,
driver: NRTDriver(outputURL: outputURL, duration: renderDuration)
)
// Schedule one voice per sounding event BEFORE start() — NRTDriver
// renders synchronously inside start().
var scheduled = 0
for event in score.allEvents {
guard !event.isRest else { continue }
guard let freqHz = event.pitch.frequency else { continue }
let pan = event.channel == 0 ? -0.4 : 0.5
let voice = ScoreVoice(
freqHz: freqHz,
amp: event.velocity * 0.35,
durSeconds: event.performedDuration * secondsPerBeat,
pan: pan
)
do {
try engine.schedule(voice, after: event.beat * secondsPerBeat)
scheduled += 1
} catch {
fputs("engine.schedule failed: \\(error)\\n", stderr)
}
}
print("Scheduled \\(scheduled) voices.")
do {
try engine.start()
print("Rendered \\(renderDuration)s → \\(outputURL.path)")
} catch {
fputs("Render failed: \\(error)\\n", stderr)
exit(1)
}
"""
}
// MARK: - ui-demo additional files
/// `AppDelegate.swift` content for a ui-demo project.
@@ -563,6 +774,7 @@ public enum ProjectScaffolder {
let synth: \(name)Synth
var window: LyrebirdWindow?
@MainActor
init(engine: SynthesisEngine) {
self.engine = engine
self.synth = \(name)Synth()
@@ -629,17 +841,21 @@ public enum ProjectScaffolder {
// MARK: - Xcode workspace
/// `contents.xcworkspacedata` body. Single `FileRef` to `Package.swift`
/// so opening the workspace in Xcode loads the SPM package with full
/// project navigation, debugging, and SwiftUI previews. Identical for
/// every template — the file lives at `<name>.xcworkspace/contents.xcworkspacedata`.
/// `contents.xcworkspacedata` body. The single `FileRef` points at the
/// workspace's enclosing directory (`group:.`) — the package root that
/// holds `Package.swift` — so Xcode recognises it as a Swift package and
/// opens the full `Sources/` / `Tests/` tree with a runnable scheme.
/// (Referencing the `Package.swift` *file* instead loads a single loose
/// document with no schemes — `xcodebuild -list` reports "no schemes".)
/// Identical for every SPM template — the file lives at
/// `<name>.xcworkspace/contents.xcworkspacedata`.
public static func workspaceContents() -> String {
"""
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Package.swift">
location = "group:.">
</FileRef>
</Workspace>
"""
-118
View File
@@ -1,118 +0,0 @@
// REPLLauncher.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Errors thrown by `REPLLauncher`.
public enum CLIError: Error {
/// The `swift` binary could not be found on this system.
case swiftNotFound
/// `swift build` exited non-zero. REPL launch was aborted.
case buildFailed(exitCode: Int32)
}
/// Locates the Swift toolchain, builds the current package, and launches `swift repl`
/// with module/library flags pointing at the package's `.build/debug` artifacts so
/// `import LyrebirdSynth` works immediately.
///
/// The Swift Package Manager's `swift package repl` subcommand was removed from the
/// toolchain. The replacement is a two-step invocation: `swift build` to produce the
/// package's `.swiftmodule` + library, then `swift repl` with `-I` / `-L` / `-l` flags
/// pointing at `.build/debug`. See `docs/tooling/repl.md`.
public enum REPLLauncher {
/// Arguments passed to `swift` for the build step that precedes the REPL.
public static let buildArguments: [String] = ["build"]
/// Arguments passed to `swift` to start the REPL. Resolves modules from the package's
/// `.build/debug` directory:
/// - `-I .build/debug/Modules` — Swift modules (LyrebirdSynth.swiftmodule, ...)
/// - `-I .build/debug/LyrebirdC.build` — LyrebirdC C-module modulemap
/// - `-L .build/debug -lLyrebird` — link the Lyrebird dylib
///
/// Paths are relative; `makeProcess(in:)` sets the working directory so the user can
/// run from a project root whose `Package.swift` depends on Lyrebird (or from the
/// Lyrebird package directory itself).
public static let replArguments: [String] = [
"repl",
"-I", ".build/debug/Modules",
"-I", ".build/debug/LyrebirdC.build",
"-L", ".build/debug",
"-lLyrebird"
]
/// Path to the shared Lyrebird history file used by the interactive shell
/// and other tooling that needs persistent command history.
public static var historyFilePath: String {
FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent(".lyrebird_history").path
}
/// Returns the path to the `swift` binary.
///
/// Checks `/usr/bin/swift` (Xcode toolchain on macOS) and `/usr/local/bin/swift`
/// (standalone toolchain). Throws `CLIError.swiftNotFound` if neither exists.
public static func findSwift() throws -> String {
let candidates: [String] = ["/usr/bin/swift", "/usr/local/bin/swift"]
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
return path
}
throw CLIError.swiftNotFound
}
/// Builds a `Process` that runs `swift` with the given arguments in `directory`.
/// stdin / stdout / stderr inherited from the calling process.
public static func makeProcess(
arguments: [String],
in directory: String = FileManager.default.currentDirectoryPath
) throws -> Process {
let swiftPath: String = try findSwift()
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: swiftPath)
process.arguments = arguments
process.currentDirectoryURL = URL(fileURLWithPath: directory)
return process
}
/// Builds a `Process` configured to run `swift repl` with module/library flags in `directory`.
public static func makeProcess(
in directory: String = FileManager.default.currentDirectoryPath
) throws -> Process {
try makeProcess(arguments: replArguments, in: directory)
}
/// Runs `swift build` and waits for it to finish. Throws `CLIError.buildFailed`
/// if the build exited non-zero. If the build was killed by a signal,
/// `exitCode` is reported as `1` (rather than the raw signal number, which
/// would mislead callers that propagate it through `exit(_:)`).
public static func build(
in directory: String = FileManager.default.currentDirectoryPath
) throws {
let process: Process = try makeProcess(arguments: buildArguments, in: directory)
try process.run()
process.waitUntilExit()
if process.terminationReason != .exit {
throw CLIError.buildFailed(exitCode: 1)
}
if process.terminationStatus != 0 {
throw CLIError.buildFailed(exitCode: process.terminationStatus)
}
}
/// Builds the package, then launches `swift repl` with Lyrebird available.
/// Blocks until the REPL session ends.
///
/// - Parameter directory: Working directory for the SPM + REPL invocation.
/// Defaults to the current directory. Must contain a `Package.swift`.
public static func launch(
in directory: String = FileManager.default.currentDirectoryPath
) throws {
try build(in: directory)
let process: Process = try makeProcess(in: directory)
try process.run()
process.waitUntilExit()
}
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Kind</key>
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
<key>Platforms</key>
<array>
<string>com.apple.platform.macosx</string>
<string>com.apple.platform.iphoneos</string>
</array>
<key>Description</key>
<string>A Score factory function — emits a make&lt;Name&gt;() that builds a two-part Score with the DSL (Note, Rest, Chord, Tuplet, dynamics, articulations) and shows how to export MusicXML with toMusicXMLString() / toMusicXMLData() and round-trip via Score.fromMusicXML(). Pitch spelling is preserved through export.</string>
<key>Summary</key>
<string>Lyrebird Score (MusicXML factory)</string>
<key>SortOrder</key>
<string>26</string>
<key>AllowedTypes</key>
<array>
<string>public.swift-source</string>
</array>
<key>DefaultCompletionName</key>
<string>MyScore</string>
<key>MainTemplateFile</key>
<string>___FILEBASENAME___.swift</string>
<key>Options</key>
<array>
<dict>
<key>Identifier</key>
<string>productName</string>
<key>Required</key>
<true/>
<key>Name</key>
<string>Score name:</string>
<key>Description</key>
<string>Name of the score factory (also used as the file name). The factory function is named make&lt;Name&gt;().</string>
<key>Type</key>
<string>text</string>
<key>Default</key>
<string>MyScore</string>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,80 @@
//___FILEHEADER___
import Foundation
import LyrebirdSynth
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// Factory for a `Score` authored with the Lyrebird score DSL.
///
/// The DSL covers every notated element:
/// - `Note(letter, octave, dur:dyn:art:)` — a single pitch
/// - `Rest(dur:)` — silence that advances the cursor
/// - `Chord([(letter, octave), …], dur:dyn:art:)` — simultaneous pitches
/// - `Tuplet(n, inTimeOf: m) { … }` — exact-ratio tuplets (`Fraction` math)
/// - `Generate(count) { i in … }` — index-driven algorithmic generation
/// - `PatternNotes(count:midi:…)` — notes pulled from a `Pattern` source
///
/// Expressive and layout features (see the Lyrebird ScoreSystem docs):
/// - `Crescendo { }` / `Diminuendo { }` hairpins and `Slur { }` spans
/// - per-note `spanners:` for overlapping spans, `.beginGlissando` / slides
/// - per-note `display:` (`NoteDisplay`) — notehead shape, size, hide stem/beam
/// - `Section("…") { … }` blocks assembled into one score (rehearsal marks)
/// - `pageLayout:` (`PageLayout`) — page size, orientation, margins, scaling
///
/// Pitch spelling (letter + accidental, including double accidentals and
/// quarter-tones) is preserved through MusicXML export.
///
/// ## Usage
/// ```swift
/// let score = make___FILEBASENAMEASIDENTIFIER___()
///
/// // Export to MusicXML 4.0 (score-partwise).
/// let xml = score.toMusicXMLString()
/// try xml.write(to: URL(fileURLWithPath: "score.musicxml"),
/// atomically: true, encoding: .utf8)
///
/// // Round-trip back into a Score.
/// let restored = try Score.fromMusicXML(data: score.toMusicXMLData())
///
/// // Walk the flattened, beat-sorted events to drive playback or rendering.
/// for event in score.allEvents where !event.isRest {
/// // event.beat, event.performedDuration (sounding beats),
/// // event.duration (notated beats), event.pitch.frequency (Hz),
/// // event.velocity ([0, 1]), event.articulation, event.channel
/// }
/// ```
public func make___FILEBASENAMEASIDENTIFIER___() -> Score {
Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
// Lead — melody covering dynamics, articulations, a hairpin, and a tuplet.
Part("lead") {
// A crescendo hairpin over the opening arpeggio (notation-only).
Crescendo {
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
Note(.named(.e, 5), dur: .quarter, dyn: .mf, art: .staccato)
Note(.named(.g, 5), dur: .quarter, dyn: .f, art: .accent)
}
Rest(dur: .quarter)
Tuplet(3, inTimeOf: 2) {
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
}
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .tenuto)
}
// Bass — sustained harmonic support on a second MIDI channel.
Part("bass", channel: 1) {
Note(.named(.c, 3), dur: .whole, dyn: .mp)
Note(.named(.g, 2), dur: .half, dyn: .p)
Note(.named(.c, 3), dur: .half, dyn: .mp, art: .tenuto)
}
// Texture — algorithmic generation. `Generate` maps an index range
// through the builder; `PatternNotes` pulls from a `Pattern` source.
Part("texture", channel: 2) {
Generate(8) { i in
Note(midi: 72 + (i % 6) * 2, dur: .sixteenth, dyn: .pp, art: .staccato)
}
PatternNotes(count: 4, midi: Pattern.series(start: 60, step: 3, length: 4), dur: .eighth, dyn: .p)
}
}
}
@@ -31,7 +31,12 @@ public func make___FILEBASENAMEASIDENTIFIER___() -> LyrebirdTask {
// The example below schedules one short Synthesizer every 250 ms
// until `stop()` is called.
while true {
let note: ExampleNote = ExampleNote()
// SynthesizerBase subclasses are @MainActor-isolated; construct on the
// main thread synchronously, then hand the instance to ctx.add which
// dispatches the engine.add to main via DispatchQueue.main.async.
let note: ExampleNote = DispatchQueue.main.sync {
MainActor.assumeIsolated { ExampleNote() }
}
ctx.add(note)
try ctx.wait(seconds: 0.25)
}
-130
View File
@@ -1,130 +0,0 @@
// TemplateInstaller.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Installs the bundled Lyrebird Xcode file templates into the user template
/// directory so Xcode's New File dialog (⌘N) discovers them.
///
/// The templates ship as a copied SPM resource on the `LyrebirdCLI` target —
/// `Bundle.module.resourceURL.appendingPathComponent("XcodeTemplates")` resolves
/// to the directory holding every `.xctemplate` bundle.
///
/// User template destination:
/// `~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`
///
/// Apple guarantees this path is the user-scoped template scan root used by
/// every recent Xcode version. No Xcode restart is required — the dialog
/// rescans on next open.
public enum TemplateInstaller {
/// Errors thrown by `install` / `uninstall`.
public enum Error: Swift.Error, Equatable {
/// Resource bundle did not contain the expected `XcodeTemplates` directory.
/// Indicates a build configuration problem, not a user error.
case bundleMissingTemplates(expectedPath: String)
/// Destination exists already and `force` was `false`.
case destinationExists(path: String)
/// Underlying `FileManager` error wrapped with the path that failed.
case fileSystemError(path: String, reason: String)
}
/// Subdirectory name inside the LyrebirdCLI resource bundle.
static let resourceSubdir: String = "XcodeTemplates"
/// Last path component under the user's Xcode template dir. The "File Templates"
/// parent is fixed by Xcode; only this trailing segment is owned by Lyrebird and
/// can therefore be safely removed by `uninstall`.
public static let installDirName: String = "Lyrebird"
/// `~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`
public static var destinationURL: URL {
FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Library/Developer/Xcode/Templates/File Templates/\(installDirName)", isDirectory: true)
}
/// Resolves `Bundle.module`'s `XcodeTemplates` resource subdir, or throws if missing.
static func sourceURL() throws -> URL {
guard let resourceURL: URL = Bundle.module.resourceURL else {
throw Error.bundleMissingTemplates(expectedPath: "<no resourceURL>")
}
let candidate: URL = resourceURL.appendingPathComponent(resourceSubdir, isDirectory: true)
guard FileManager.default.fileExists(atPath: candidate.path) else {
throw Error.bundleMissingTemplates(expectedPath: candidate.path)
}
return candidate
}
/// Lists the `.xctemplate` bundle names inside the source resource directory.
public static func availableTemplates() throws -> [String] {
let src: URL = try sourceURL()
let contents: [String] = try FileManager.default.contentsOfDirectory(atPath: src.path)
return contents.filter { $0.hasSuffix(".xctemplate") }.sorted()
}
/// Copies every `.xctemplate` from the bundle to `destinationURL`.
///
/// - Parameter force: When `true`, overwrites an existing destination directory.
/// When `false`, throws `Error.destinationExists` if the destination already
/// exists. Per-template overwrite is unconditional once we've decided to write
/// — `force` is the top-level guard.
/// - Returns: Number of templates copied.
@discardableResult
public static func install(force: Bool = false) throws -> Int {
let src: URL = try sourceURL()
let dest: URL = destinationURL
let fm: FileManager = FileManager.default
if fm.fileExists(atPath: dest.path) {
if !force {
throw Error.destinationExists(path: dest.path)
}
do {
try fm.removeItem(at: dest)
} catch {
throw Error.fileSystemError(path: dest.path, reason: error.localizedDescription)
}
}
// Recreate the destination dir.
do {
try fm.createDirectory(at: dest, withIntermediateDirectories: true)
} catch {
throw Error.fileSystemError(path: dest.path, reason: error.localizedDescription)
}
// Copy each .xctemplate bundle.
let templates: [String] = try availableTemplates()
for name: String in templates {
let from: URL = src.appendingPathComponent(name, isDirectory: true)
let to: URL = dest.appendingPathComponent(name, isDirectory: true)
do {
try fm.copyItem(at: from, to: to)
} catch {
throw Error.fileSystemError(path: to.path, reason: error.localizedDescription)
}
}
return templates.count
}
/// Removes the entire `~/Library/.../File Templates/Lyrebird/` directory.
///
/// - Returns: `true` if the directory existed and was removed; `false` if it
/// was not installed.
@discardableResult
public static func uninstall() throws -> Bool {
let dest: URL = destinationURL
let fm: FileManager = FileManager.default
guard fm.fileExists(atPath: dest.path) else { return false }
do {
try fm.removeItem(at: dest)
} catch {
throw Error.fileSystemError(path: dest.path, reason: error.localizedDescription)
}
return true
}
}