SPB Git

Repository Public

Plan.swift 14.7 KB 337 lines swift

1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXScript/Plan.swift3// Description: The automation plan: the validated, resolved form of a script that the runtime executes.4//              Plus the pure evaluation rules (operators, builtins) shared by constant folding and the runtime.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import ORIXDSP1011/// A resolved parameter reference. `deck` is nil for mixer, master and master-rack effects.12public struct PPath: Sendable {13    public var area: SchemaArea14    public var deck: PExpr?15    public var effect: EffectKind?16    public var key: String17    public var def: ParamDef18}1920public struct PAction: Sendable {21    public var area: SchemaArea22    public var deck: PExpr?23    public var effect: EffectKind?24    public var name: String25}2627public indirect enum PExpr: Sendable {28    case const(Value)29    case local(Int)30    case read(PPath, SourceLocation)31    case unary(String, PExpr, SourceLocation)32    case binary(String, PExpr, PExpr, SourceLocation)33    case builtin(String, [PExpr], SourceLocation)34    case callFunction(Int, [PExpr], SourceLocation)35    case array([PExpr])36    case index(PExpr, PExpr, SourceLocation)3738    var constant: Value? { if case let .const(v) = self { v } else { nil } }39}4041public enum PAnchor: Sendable {42    /// Beats after the start of the automation.43    case offsetBeats(PExpr)44    /// A duration after the start of the automation.45    case offset(PExpr)46    case nextBeat47    case nextBar48}4950public enum PWait: Sendable {51    case duration(PExpr)52    case nextBeat53    case nextBar54    case until(PAnchor)55}5657public enum PEvent: Sendable {58    case deck(PExpr, String)59    case beat60    case bar61    case trigger(PExpr)62}6364public enum RampCurve: String, Sendable, CaseIterable, Codable {65    case linear, easeIn, easeOut, smooth, exp6667    public func shape(_ t: Double) -> Double {68        let x = min(max(t, 0), 1)69        switch self {70        case .linear: return x71        case .easeIn: return x * x72        case .easeOut: return 1 - (1 - x) * (1 - x)73        case .smooth: return x * x * (3 - 2 * x)74        case .exp: return (Foundation.exp(4 * x) - 1) / (Foundation.exp(4) - 1)75        }76    }77}7879public struct PRamp: Sendable {80    public var path: PPath81    public var target: PExpr82    public var location: SourceLocation83}8485public indirect enum PStmtKind: Sendable {86    case setLocal(Int, PExpr)87    case write(PPath, PExpr)88    case action(PAction, [PExpr])89    case callProcedure(Int, [PExpr])90    case print([PExpr])91    case wait(PWait)92    case spawn(PAnchor, [PStmt])93    case over(PExpr, RampCurve, [PRamp], [PStmt])94    case every(PExpr, PExpr, [PStmt])95    case repeatLoop(PExpr, [PStmt])96    case forRange(Int, PExpr, PExpr, Bool, [PStmt])97    case forIn(Int, PExpr, [PStmt])98    case whileLoop(PExpr, Int, [PStmt])99    case ifElse(PExpr, [PStmt], [PStmt])100    case on(PEvent, Bool, [PStmt])101    case returnValue(PExpr?)102    case stop103    case breakLoop104    case continueLoop105}106107public struct PStmt: Sendable {108    public var kind: PStmtKind109    public var location: SourceLocation110}111112public struct PFunction: Sendable {113    public var name: String114    public var paramCount: Int115    public var slotNames: [String]116    public var body: [PStmt]117    public var returnType: ScriptType?118}119120/// What an automation needs and how long it runs, computed at compile time.121public struct AutomationRequirements: Sendable, Equatable {122    /// Zero-based decks addressed by a constant path.123    public var decks: Set<Int> = []124    /// Effects addressed, with their rack (nil = master).125    public var effects: Set<String> = []126    /// Length in beats when it can be determined statically; nil when it depends on run-time values or waits for events.127    public var lengthBeats: Double?128    public var usesEvents = false129    public var usesAbsoluteTime = false130131    public var deckLetters: [String] { decks.sorted().map { ORIXScript.deckLetters[$0] } }132}133134public struct CompiledAutomation: Sendable {135    public var name: String136    public var quantize: StartQuantize137    public var body: [PStmt]138    public var slotNames: [String]139    public var requirements: AutomationRequirements140    public var location: SourceLocation141}142143public struct Program: Sendable {144    public var automations: [CompiledAutomation]145    public var functions: [PFunction]146    public var languageVersion: String147148    public func automation(named name: String) -> CompiledAutomation? { automations.first { $0.name == name } }149}150151/// A failure while a script runs. The automation is cancelled; the audio engine is unaffected.152public struct ScriptRuntimeError: Error, Equatable, Sendable, CustomStringConvertible {153    public var code: String154    public var message: String155    public var location: SourceLocation?156    public init(_ code: String, _ message: String, at location: SourceLocation? = nil) { self.code = code; self.message = message; self.location = location }157    public var description: String { (location.map { "line \($0.line): " } ?? "") + message + " [\(code)]" }158}159160/// Operator and builtin semantics. Pure: the same code folds constants in the compiler and evaluates at run time.161enum Evaluator {162    static func unary(_ op: String, _ v: Value, at loc: SourceLocation) throws -> Value {163        switch (op, v) {164        case ("+", _): return v165        case let ("-", .number(n)): return .number(-n)166        case let ("-", .gain(d)): return .gain(-d)167        case let ("-", .frequency(f)): return .frequency(-f)168        case let ("-", .duration(.beats(b))): return .duration(.beats(-b))169        case let ("-", .duration(.seconds(s))): return .duration(.seconds(-s))170        case let ("!", .bool(b)): return .bool(!b)171        default: throw ScriptRuntimeError("E-TYPE", "Operator '\(op)' cannot be applied to \(v.type).", at: loc)172        }173    }174175    static func addDurations(_ a: TimeSpan, _ b: TimeSpan, sign: Double, bpm: Double) -> TimeSpan {176        switch (a, b) {177        case let (.beats(x), .beats(y)): .beats(x + sign * y)178        case let (.seconds(x), .seconds(y)): .seconds(x + sign * y)179        default: .beats(a.beats(atBPM: bpm) + sign * b.beats(atBPM: bpm))180        }181    }182183    static func scale(_ t: TimeSpan, _ k: Double) -> TimeSpan {184        switch t { case let .beats(b): .beats(b * k); case let .seconds(s): .seconds(s * k) }185    }186187    static func binary(_ op: String, _ a: Value, _ b: Value, bpm: Double, at loc: SourceLocation) throws -> Value {188        func finite(_ x: Double) throws -> Double {189            if x.isFinite { return x }190            throw ScriptRuntimeError("E-MATH", "The result of '\(op)' is not a finite number (division by zero?).", at: loc)191        }192        switch op {193        case "+", "-":194            let s: Double = op == "+" ? 1 : -1195            switch (a, b) {196            case let (.number(x), .number(y)): return .number(try finite(x + s * y))197            case let (.gain(x), .gain(y)): return .gain(x + s * y)198            case let (.frequency(x), .frequency(y)): return .frequency(x + s * y)199            case let (.duration(x), .duration(y)): return .duration(addDurations(x, y, sign: s, bpm: bpm))200            case let (.string(x), .string(y)) where op == "+":201                if x.count + y.count > 2048 { throw ScriptRuntimeError("E-LIMIT", "String longer than 2048 characters.", at: loc) }202                return .string(x + y)203            default: break204            }205        case "*":206            switch (a, b) {207            case let (.number(x), .number(y)): return .number(try finite(x * y))208            case let (.duration(t), .number(k)), let (.number(k), .duration(t)): return .duration(scale(t, k))209            case let (.frequency(f), .number(k)), let (.number(k), .frequency(f)): return .frequency(f * k)210            case let (.gain(g), .number(k)), let (.number(k), .gain(g)): return .gain(g * k)211            default: break212            }213        case "/":214            switch (a, b) {215            case let (.number(x), .number(y)): return .number(try finite(x / y))216            case let (.duration(t), .number(k)): _ = try finite(1 / k); return .duration(scale(t, 1 / k))217            case let (.duration(x), .duration(y)): return .number(try finite(x.beats(atBPM: bpm) / y.beats(atBPM: bpm)))218            case let (.frequency(f), .number(k)): return .frequency(try finite(f / k))219            case let (.frequency(x), .frequency(y)): return .number(try finite(x / y))220            case let (.gain(g), .number(k)): return .gain(try finite(g / k))221            default: break222            }223        case "%":224            if case let (.number(x), .number(y)) = (a, b) { return .number(try finite(x.truncatingRemainder(dividingBy: y))) }225        case "==": return .bool(a == b || compare(a, b, bpm: bpm) == 0)226        case "!=": return .bool(!(a == b || compare(a, b, bpm: bpm) == 0))227        case "<", "<=", ">", ">=":228            if let c = compare(a, b, bpm: bpm) {229                switch op { case "<": return .bool(c < 0); case "<=": return .bool(c <= 0); case ">": return .bool(c > 0); default: return .bool(c >= 0) }230            }231        case "&&": if case let (.bool(x), .bool(y)) = (a, b) { return .bool(x && y) }232        case "||": if case let (.bool(x), .bool(y)) = (a, b) { return .bool(x || y) }233        default: break234        }235        throw ScriptRuntimeError("E-TYPE", "Operator '\(op)' cannot combine \(a.type) and \(b.type).", at: loc)236    }237238    /// -1, 0, 1 for ordered values of the same kind; nil when they are not comparable.239    static func compare(_ a: Value, _ b: Value, bpm: Double) -> Int? {240        func ord(_ x: Double, _ y: Double) -> Int { x < y ? -1 : (x > y ? 1 : 0) }241        switch (a, b) {242        case let (.number(x), .number(y)), let (.gain(x), .gain(y)), let (.frequency(x), .frequency(y)): return ord(x, y)243        case let (.duration(x), .duration(y)): return ord(x.beats(atBPM: bpm), y.beats(atBPM: bpm))244        default: return nil245        }246    }247248    /// Result type of a binary operator, or nil when the operand types are not accepted.249    static func binaryType(_ op: String, _ a: ScriptType, _ b: ScriptType) -> ScriptType? {250        switch op {251        case "+", "-":252            if a == b, [.number, .gain, .frequency, .duration].contains(a) { return a }253            if op == "+", a == .string, b == .string { return .string }254        case "*":255            if a == .number, b == .number { return .number }256            if b == .number, [.duration, .frequency, .gain].contains(a) { return a }257            if a == .number, [.duration, .frequency, .gain].contains(b) { return b }258        case "/":259            if b == .number, [.number, .duration, .frequency, .gain].contains(a) { return a }260            if a == b, [.duration, .frequency].contains(a) { return .number }261        case "%": if a == .number, b == .number { return .number }262        case "==", "!=":263            if a == b { if case .array = a { return nil }; return a == .void ? nil : .bool }264        case "<", "<=", ">", ">=": if a == b, [.number, .gain, .frequency, .duration].contains(a) { return .bool }265        case "&&", "||": if a == .bool, b == .bool { return .bool }266        default: break267        }268        return nil269    }270271    /// Builtins that do not depend on run-time state other than the tempo.272    static func builtin(_ name: String, _ args: [Value], bpm: Double, at loc: SourceLocation) throws -> Value {273        func num(_ i: Int) throws -> Double {274            if case let .number(n) = args[i] { return n }275            throw ScriptRuntimeError("E-TYPE", "\(name)() expects a number.", at: loc)276        }277        switch name {278        case "min", "max":279            guard let c = compare(args[0], args[1], bpm: bpm) else { throw ScriptRuntimeError("E-TYPE", "\(name)() needs two values of the same ordered type.", at: loc) }280            return (name == "min") == (c <= 0) ? args[0] : args[1]281        case "clamp":282            guard let lo = compare(args[0], args[1], bpm: bpm), let hi = compare(args[0], args[2], bpm: bpm) else {283                throw ScriptRuntimeError("E-TYPE", "clamp() needs three values of the same ordered type.", at: loc)284            }285            return lo < 0 ? args[1] : (hi > 0 ? args[2] : args[0])286        case "abs": return .number(abs(try num(0)))287        case "round": return .number(try num(0).rounded())288        case "floor": return .number(try num(0).rounded(.down))289        case "ceil": return .number(try num(0).rounded(.up))290        case "lerp":291            let t = try num(2)292            switch (args[0], args[1]) {293            case let (.number(x), .number(y)): return .number(x + (y - x) * t)294            case let (.gain(x), .gain(y)): return .gain(x + (y - x) * t)295            case let (.frequency(x), .frequency(y)): return .frequency(x + (y - x) * t)296            case let (.duration(x), .duration(y)): return .duration(addDurations(scale(x, 1 - t), scale(y, t), sign: 1, bpm: bpm))297            default: throw ScriptRuntimeError("E-TYPE", "lerp() needs two values of the same numeric type.", at: loc)298            }299        case "len":300            if case let .array(a) = args[0] { return .number(Double(a.count)) }301            if case let .string(s) = args[0] { return .number(Double(s.count)) }302            throw ScriptRuntimeError("E-TYPE", "len() expects an array or a string.", at: loc)303        case "db": return .gain(try num(0))304        case "hz": return .frequency(try num(0))305        case "beats": return .duration(.beats(try num(0)))306        case "bars": return .duration(.beats(try num(0) * ORIXScriptLanguage.beatsPerBar))307        case "seconds": return .duration(.seconds(try num(0)))308        case "toBeats": if case let .duration(t) = args[0] { return .number(t.beats(atBPM: bpm)) }309        case "toSeconds": if case let .duration(t) = args[0] { return .number(t.seconds(atBPM: bpm)) }310        case "toNumber": if let s = args[0].scalar { return .number(s) }311        case "linearToGain":312            let x = try num(0)313            return .gain(x <= 0.001 ? -60 : max(-60, 20 * log10(x)))314        default: break315        }316        throw ScriptRuntimeError("E-TYPE", "\(name)() cannot be applied to these values.", at: loc)317    }318}319320/// Levenshtein distance, for "did you mean" hints.321func editDistance(_ a: String, _ b: String) -> Int {322    let x = Array(a.lowercased()), y = Array(b.lowercased())323    if x.isEmpty { return y.count }; if y.isEmpty { return x.count }324    var prev = Array(0 ... y.count), cur = [Int](repeating: 0, count: y.count + 1)325    for i in 1 ... x.count {326        cur[0] = i327        for j in 1 ... y.count { cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x[i - 1] == y[j - 1] ? 0 : 1)) }328        swap(&prev, &cur)329    }330    return prev[y.count]331}332333func suggestion(for name: String, in candidates: [String]) -> String {334    guard let best = candidates.min(by: { editDistance(name, $0) < editDistance(name, $1) }), editDistance(name, best) <= max(2, name.count / 3) else { return "" }335    return " Did you mean '\(best)'?"336}337
Files main
Menu

Theme