// SnippetHarness.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT // LyrebirdLiveCompile — Phase 143 // // `SnippetHarness.wrap(userBody:)` produces the full Swift source that // `LiveCompiler.compile(source:)` feeds to swiftc. The preamble imports the // modules the snippet needs, declares the C ABI entry, and binds `context: SnippetContext` // from the opaque pointer the host hands in. The user's body is dropped in as // the function body. #if os(macOS) public enum SnippetHarness { /// Wraps `userBody` in the standard preamble. public static func wrap(userBody: String) -> WrappedSnippet { let preamble: String = """ import LyrebirdSynth import LyrebirdLiveCompile @_cdecl("lyrebird_snippet_entry") public func lyrebird_snippet_entry(_ ctx: UnsafeMutableRawPointer?) { guard let ctx else { return } let context = Unmanaged.fromOpaque(ctx).takeUnretainedValue() _ = context """ // Count newlines in the preamble: the user's body starts on the next line. // `components(separatedBy: "\n")` over a string ending in "\n" yields N+1 // elements (the last is empty); offset = count of those elements = lines // before the user body + 1 (the line on which the body starts). let lineOffset: Int = preamble.components(separatedBy: "\n").count let suffix: String = "\n}\n" let source: String = preamble + userBody + suffix return WrappedSnippet(source: source, userBodyLineOffset: lineOffset) } } #endif