SPB Git

Repository Public

Runtime.swift 41.8 KB 786 lines swift

1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXScript/Runtime.swift3// Description: ORIX Script runtime: executes an automation plan in beat time against an AutomationTarget.4//              Cooperative tasks, parameter ramps, event handlers, strict budgets, breakpoints. Never runs on the5//              audio render thread: it only emits timestamped parameter writes and actions.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import ORIXDSP1112/// What a running automation talks to: the live DJ engine, or the simulator.13public protocol AutomationTarget: AnyObject {14    /// Current value of a parameter or property; nil when it cannot be read (e.g. the effect is not in the rack).15    func read(_ address: ParamAddress) -> Value?16    /// Applies a validated value at `beat` of the master clock, smoothing over `rampBeats`.17    func write(_ address: ParamAddress, _ value: Value, atBeat beat: Double, rampBeats: Double)18    /// Runs an action. Returns an error message when it cannot be performed.19    func perform(_ action: ActionAddress, _ arguments: [Value], atBeat beat: Double) -> String?20    /// Tempo of the master clock.21    var clockBPM: Double { get }22}2324public struct RuntimeLimits: Sendable, Equatable {25    /// Operations (statements, loop turns, expression nodes) allowed in one scheduler step without waiting.26    public var maxOperationsPerStep = 2000027    /// Operations allowed over the whole life of one automation.28    public var maxTotalOperations = 5_000_00029    public var maxTasks = 25630    public var maxRamps = 12831    public var maxHandlers = CompileLimits.maxHandlers32    /// Statement-issued writes and actions allowed per beat (ramps are not counted).33    public var maxCommandsPerBeat = 51234    public var maxLoopIterations = CompileLimits.maxLoopIterations35    public var maxCallDepth = 1636    public var maxArrayLength = CompileLimits.maxArrayLength37    /// Longest wait or ramp, in beats.38    public var maxSpanBeats = 100_000.039    /// Events queued while a handler is still running are dropped beyond this many pending handler tasks.40    public var maxPendingHandlerTasks = 644142    public init() {}43}4445public enum AutomationState: Equatable, Sendable {46    case running47    case paused48    case finished49    case stopped50    case failed(ScriptRuntimeError)5152    public var isAlive: Bool { self == .running || self == .paused }53}5455public enum TraceKind: String, Sendable, Codable { case start, write, action, wait, spawn, ramp, rampEnd, handler, event, print, warning, error, finish, breakpoint }5657/// One entry of the execution trace (debugger, simulator, live log).58public struct TraceEvent: Sendable, Equatable {59    public var beat: Double60    public var kind: TraceKind61    public var text: String62    public var line: Int63    public var address: ParamAddress?64    public var value: Value?6566    public init(beat: Double, kind: TraceKind, text: String, line: Int = 0, address: ParamAddress? = nil, value: Value? = nil) {67        self.beat = beat; self.kind = kind; self.text = text; self.line = line; self.address = address; self.value = value68    }69}7071public struct AutomationStats: Sendable, Equatable {72    public var operations = 073    public var writes = 074    public var rampWrites = 075    public var actions = 076    public var clampedValues = 077    public var droppedEvents = 078    public var peakTasks = 079    public var peakRamps = 080    /// Largest distance, in beats, between the time a task was due and the clock position at which it ran.81    public var maxLatenessBeats = 0.082}8384public struct TaskSnapshot: Sendable, Equatable { public var id: Int; public var wakeBeat: Double; public var line: Int; public var isHandler: Bool }85public struct RampSnapshot: Sendable, Equatable { public var address: ParamAddress; public var from: Double; public var to: Double; public var startBeat: Double; public var endBeat: Double; public var curve: RampCurve }86public struct VariableSnapshot: Sendable, Equatable { public var name: String; public var value: Value }8788final class Frame {89    var slots: [Value]90    init(count: Int) { slots = [Value](repeating: .void, count: count) }91    init(copying other: Frame) { slots = other.slots }92}9394private enum LoopKind {95    case plain96    case procedure97    case repeatLoop(remaining: Int)98    case forRange(slot: Int, next: Double, end: Double, inclusive: Bool)99    case forArray(slot: Int, items: [Value], next: Int)100    case whileLoop(PExpr, remaining: Int, SourceLocation)101    case every(period: Double, end: Double, next: Double)102103    var isLoop: Bool { switch self { case .plain, .procedure: false; default: true } }104}105106private struct Activation {107    var body: [PStmt]108    var pc = 0109    var frame: Frame110    var kind: LoopKind111}112113private final class ScriptTask {114    let id: Int115    var wake: Double116    var stack: [Activation]117    let isHandler: Bool118    var line = 0119    init(id: Int, wake: Double, stack: [Activation], isHandler: Bool) { self.id = id; self.wake = wake; self.stack = stack; self.isHandler = isHandler }120}121122private struct ActiveRamp {123    var address: ParamAddress124    var def: ParamDef125    var from: Double126    var to: Double127    var start: Double128    var end: Double129    var curve: RampCurve130    var lastWritten: Double131    var line: Int132}133134private struct Handler {135    var key: EventKey136    var once: Bool137    var body: [PStmt]138    var frame: Frame139    var line: Int140}141142private enum Flow { case normal, breakLoop, continueLoop, returned(Value) }143144/// One running automation. Single-threaded: create, advance and inspect it from one queue.145public final class AutomationInstance {146    public let program: Program147    public let automation: CompiledAutomation148    public let limits: RuntimeLimits149    public private(set) var state: AutomationState = .running150    public private(set) var stats = AutomationStats()151    /// Clock beat at which the automation's own timeline starts (bar 1, beat 1).152    public private(set) var startBeat: Double153    /// Receives every trace event. Called synchronously from `advance`.154    public var onTrace: ((TraceEvent) -> Void)?155156    // Debugging.157    public var breakpoints: Set<Int> = []158    public var stepping = false159    public private(set) var pausedAtLine: Int?160161    private unowned let target: AutomationTarget162    private var tasks: [ScriptTask] = []163    private var ramps: [ActiveRamp] = []164    private var handlers: [Handler] = []165    private var enabledEffects: Set<ActionAddress> = []166    private let rootFrame: Frame167    private var nextTaskID = 1168    private var lastBeat: Double169    private var stepOperations = 0170    private var commandWindowStart = 0.0171    private var commandsInWindow = 0172    private var rngState: UInt64 = 0x2545_F491_4F6C_DD1D173    private var skipBreakpointOnce = false174    private var pauseBeat: Double?175    private var currentBeat: Double176    private var currentLine = 0177178    /// - Parameter nowBeat: current master clock position. The start is moved to the next beat or bar when the automation asks for it.179    public init(program: Program, automation: CompiledAutomation, target: AutomationTarget, nowBeat: Double, limits: RuntimeLimits = .init()) {180        self.program = program; self.automation = automation; self.target = target; self.limits = limits181        switch automation.quantize {182        case .none: startBeat = nowBeat183        case .beat: startBeat = Self.nextBoundary(after: nowBeat, every: 1)184        case .bar: startBeat = Self.nextBoundary(after: nowBeat, every: ORIXScriptLanguage.beatsPerBar)185        }186        rootFrame = Frame(count: automation.slotNames.count)187        lastBeat = nowBeat; currentBeat = startBeat188        let main = ScriptTask(id: 0, wake: startBeat, stack: [Activation(body: automation.body, frame: rootFrame, kind: .plain)], isHandler: false)189        tasks.append(main)190    }191192    static func nextBoundary(after beat: Double, every step: Double) -> Double {193        let k = (beat / step).rounded(.up) * step194        return k - beat < 1e-6 && k >= beat ? k : (k < beat ? k + step : k)195    }196197    // MARK: Control198199    /// Ends the automation. Running ramps stop where they are.200    public func stop() {201        guard state.isAlive else { return }202        finish(.stopped, at: currentBeat)203    }204205    /// Freezes the automation's timeline at `beat`.206    public func pause(atBeat beat: Double) {207        guard state == .running else { return }208        state = .paused; pauseBeat = beat209    }210211    /// Resumes a paused automation; everything pending is shifted by the time spent paused.212    public func resume(atBeat beat: Double) {213        guard state == .paused, let p = pauseBeat else { return }214        let shift = max(0, beat - p)215        for t in tasks { t.wake += shift }216        for i in ramps.indices { ramps[i].start += shift; ramps[i].end += shift }217        startBeat += shift; lastBeat = beat; pauseBeat = nil; state = .running218    }219220    /// Continues after a breakpoint.221    public func continueFromBreakpoint(step: Bool = false) {222        stepping = step; skipBreakpointOnce = true; pausedAtLine = nil223    }224225    /// Delivers an event (deck events, triggers). Beat and bar events are generated by `advance`.226    public func post(_ event: EventKey, atBeat beat: Double) {227        guard state == .running else { return }228        var fired = false229        var i = 0230        while i < handlers.count {231            let h = handlers[i]232            if h.key == event {233                fired = true234                if tasks.lazy.filter(\.isHandler).count >= limits.maxPendingHandlerTasks { stats.droppedEvents += 1 }235                else {236                    spawnTask(body: h.body, frame: h.frame, wake: max(beat, lastBeat), isHandler: true)237                    trace(.handler, "on \(event)", line: h.line, beat: beat)238                }239                if h.once { handlers.remove(at: i); continue }240            }241            i += 1242        }243        _ = fired244    }245246    // MARK: Inspection247248    public var variables: [VariableSnapshot] {249        zip(automation.slotNames, rootFrame.slots).filter { !$0.0.hasPrefix("$") && $0.1 != .void }.map { VariableSnapshot(name: $0.0, value: $0.1) }250    }251252    public var taskSnapshots: [TaskSnapshot] { tasks.map { TaskSnapshot(id: $0.id, wakeBeat: $0.wake, line: $0.line, isHandler: $0.isHandler) } }253    public var rampSnapshots: [RampSnapshot] { ramps.map { RampSnapshot(address: $0.address, from: $0.from, to: $0.to, startBeat: $0.start, endBeat: $0.end, curve: $0.curve) } }254    public var handlerDescriptions: [String] { handlers.map { "on \($0.key)" + ($0.once ? " once" : "") } }255    /// Beat of the next thing this automation will do, for the scheduler display.256    public var nextWakeBeat: Double? { tasks.map(\.wake).min() }257    /// Position on the automation's own timeline.258    public var elapsedBeats: Double { max(0, lastBeat - startBeat) }259260    // MARK: Advance261262    /// Runs everything due up to `beat`. Returns false when execution stopped at a breakpoint (call again to resume).263    @discardableResult public func advance(to beat: Double) -> Bool {264        guard state == .running else { return true }265        stepOperations = 0266        do {267            // Master clock beat and bar events.268            if handlers.contains(where: { $0.key == .beat || $0.key == .bar }), beat > lastBeat {269                var b = lastBeat.rounded(.down) + 1270                var guardCount = 0271                while b <= beat, guardCount < 64 {272                    if b > lastBeat {273                        post(.beat, atBeat: b)274                        if b.truncatingRemainder(dividingBy: ORIXScriptLanguage.beatsPerBar) == 0 { post(.bar, atBeat: b) }275                    }276                    b += 1; guardCount += 1277                }278            }279            while state == .running {280                guard let task = tasks.filter({ $0.wake <= beat }).min(by: { ($0.wake, $0.id) < ($1.wake, $1.id) }) else { break }281                stats.maxLatenessBeats = max(stats.maxLatenessBeats, max(0, lastBeat - task.wake))282                // Ramps that end by now reach their target before the statements that follow them run.283                try finishRamps(upTo: task.wake)284                currentBeat = task.wake285                let completed = try run(task)286                if pausedAtLine != nil { lastBeat = max(lastBeat, min(beat, task.wake)); return false }287                if completed { tasks.removeAll { $0 === task } }288            }289            if state == .running { try updateRamps(at: beat) }290            lastBeat = max(lastBeat, beat)291            if state == .running, tasks.isEmpty, ramps.isEmpty, handlers.isEmpty { finish(.finished, at: beat) }292        } catch let e as ScriptRuntimeError {293            fail(e, at: beat)294        } catch {295            fail(ScriptRuntimeError("E-INTERNAL", "\(error)"), at: beat)296        }297        return true298    }299300    private func finish(_ newState: AutomationState, at beat: Double) {301        state = newState302        tasks.removeAll(); ramps.removeAll(); handlers.removeAll()303        trace(.finish, newState == .finished ? "finished" : "stopped", line: 0, beat: beat)304    }305306    /// Failure: cancel everything and switch off the effects this automation switched on, so a broken script cannot leave the mix processed.307    private func fail(_ error: ScriptRuntimeError, at beat: Double) {308        var e = error309        if e.location == nil, currentLine > 0 { e.location = SourceLocation(line: currentLine, column: 1) }310        tasks.removeAll(); ramps.removeAll(); handlers.removeAll()311        for fx in enabledEffects.sorted(by: { $0.description < $1.description }) {312            _ = target.perform(ActionAddress(area: .fx, deck: fx.deck, effect: fx.effect, name: "disable"), [], atBeat: beat)313            trace(.warning, "bypassed \(ParamAddress(area: .fx, deck: fx.deck, effect: fx.effect, key: "").description.dropLast()) after the failure", line: 0, beat: beat)314        }315        state = .failed(e)316        trace(.error, e.message + " [\(e.code)]", line: e.location?.line ?? 0, beat: beat)317    }318319    private func trace(_ kind: TraceKind, _ text: String, line: Int, beat: Double? = nil, address: ParamAddress? = nil, value: Value? = nil) {320        onTrace?(TraceEvent(beat: beat ?? currentBeat, kind: kind, text: text, line: line, address: address, value: value))321    }322323    private func charge(_ n: Int = 1, at loc: SourceLocation? = nil) throws {324        stepOperations += n; stats.operations += n325        if stepOperations > limits.maxOperationsPerStep {326            throw ScriptRuntimeError("E-BUDGET", "More than \(limits.maxOperationsPerStep) operations without a wait. Add a 'wait' inside the loop or reduce its work.", at: loc)327        }328        if stats.operations > limits.maxTotalOperations {329            throw ScriptRuntimeError("E-BUDGET", "The automation used its total budget of \(limits.maxTotalOperations) operations.", at: loc)330        }331    }332333    private func chargeCommand(at loc: SourceLocation) throws {334        if currentBeat - commandWindowStart >= 1 || currentBeat < commandWindowStart { commandWindowStart = currentBeat; commandsInWindow = 0 }335        commandsInWindow += 1336        if commandsInWindow > limits.maxCommandsPerBeat {337            throw ScriptRuntimeError("E-RATE", "More than \(limits.maxCommandsPerBeat) commands in one beat. The automation was stopped to protect the performance.", at: loc)338        }339    }340341    private func spawnTask(body: [PStmt], frame: Frame, wake: Double, isHandler: Bool) {342        let t = ScriptTask(id: nextTaskID, wake: wake, stack: [Activation(body: body, frame: frame, kind: .plain)], isHandler: isHandler)343        nextTaskID += 1344        tasks.append(t)345        stats.peakTasks = max(stats.peakTasks, tasks.count)346    }347348    // MARK: Task execution349350    /// Runs a task until it waits or ends. Returns true when the task is finished.351    private func run(_ task: ScriptTask) throws -> Bool {352        while state == .running {353            guard var top = task.stack.last else { return true }354            if top.pc >= top.body.count {355                // End of a body: loop again, wait for the next 'every' turn, or leave.356                switch top.kind {357                case .plain, .procedure:358                    task.stack.removeLast()359                case let .repeatLoop(remaining):360                    try charge()361                    if remaining > 0 { top.kind = .repeatLoop(remaining: remaining - 1); top.pc = 0; task.stack[task.stack.count - 1] = top } else { task.stack.removeLast() }362                case let .forRange(slot, next, end, inclusive):363                    try charge()364                    if inclusive ? next <= end : next < end {365                        top.frame.slots[slot] = .number(next); top.kind = .forRange(slot: slot, next: next + 1, end: end, inclusive: inclusive); top.pc = 0366                        task.stack[task.stack.count - 1] = top367                    } else { task.stack.removeLast() }368                case let .forArray(slot, items, next):369                    try charge()370                    if next < items.count {371                        top.frame.slots[slot] = items[next]; top.kind = .forArray(slot: slot, items: items, next: next + 1); top.pc = 0372                        task.stack[task.stack.count - 1] = top373                    } else { task.stack.removeLast() }374                case let .whileLoop(cond, remaining, loc):375                    try charge()376                    guard case .bool(true) = try eval(cond, top.frame) else { task.stack.removeLast(); continue }377                    guard remaining > 0 else { throw ScriptRuntimeError("E-UNBOUNDED", "The 'while' loop reached its limit without its condition becoming false.", at: loc) }378                    top.kind = .whileLoop(cond, remaining: remaining - 1, loc); top.pc = 0379                    task.stack[task.stack.count - 1] = top380                case let .every(period, end, next):381                    try charge()382                    if next < end - 1e-9 {383                        top.kind = .every(period: period, end: end, next: next + period); top.pc = 0384                        task.stack[task.stack.count - 1] = top385                        if next > currentBeat { task.wake = next; return false }386                    } else {387                        task.stack.removeLast()388                        if end > currentBeat { task.wake = end; return false }389                    }390                }391                continue392            }393            let stmt = top.body[top.pc]394            let line = stmt.location.line395            // Breakpoints fire before the statement runs.396            if breakpoints.contains(line) || stepping {397                if skipBreakpointOnce { skipBreakpointOnce = false }398                else {399                    pausedAtLine = line; task.line = line400                    trace(.breakpoint, "paused at line \(line)", line: line)401                    return false402                }403            }404            task.stack[task.stack.count - 1].pc += 1405            task.line = line; currentLine = line406            try charge(1, at: stmt.location)407            if let wake = try execute(stmt, frame: top.frame, task: task) {408                if wake > currentBeat + 1e-12 { task.wake = wake; return false }409            }410        }411        return true412    }413414    private func beats(_ e: PExpr, _ frame: Frame, _ what: String, at loc: SourceLocation) throws -> Double {415        guard case let .duration(span) = try eval(e, frame) else { throw ScriptRuntimeError("E-TYPE", "\(what) is not a duration.", at: loc) }416        let b = span.beats(atBPM: max(20, target.clockBPM))417        guard b.isFinite, b >= 0 else { throw ScriptRuntimeError("E-RANGE", "\(what) must be zero or more.", at: loc) }418        guard b <= limits.maxSpanBeats else { throw ScriptRuntimeError("E-LIMIT", "\(what) cannot exceed \(Int(limits.maxSpanBeats)) beats.", at: loc) }419        return b420    }421422    private func anchorBeat(_ a: PAnchor, _ frame: Frame, at loc: SourceLocation) throws -> Double {423        switch a {424        case .nextBeat: return Self.nextBoundary(after: currentBeat, every: 1)425        case .nextBar: return Self.nextBoundary(after: currentBeat, every: ORIXScriptLanguage.beatsPerBar)426        case let .offsetBeats(e):427            guard case let .number(n) = try eval(e, frame), n.isFinite, n >= 0 else { throw ScriptRuntimeError("E-RANGE", "Bars and beats count from 1.", at: loc) }428            return startBeat + min(n, limits.maxSpanBeats)429        case let .offset(e): return startBeat + (try beats(e, frame, "The position", at: loc))430        }431    }432433    private func deckIndex(_ e: PExpr?, _ frame: Frame, at loc: SourceLocation) throws -> Int? {434        guard let e else { return nil }435        guard case let .deck(d) = try eval(e, frame) else { throw ScriptRuntimeError("E-TYPE", "Expected a deck.", at: loc) }436        return d437    }438439    private func address(_ p: PPath, _ frame: Frame, at loc: SourceLocation) throws -> ParamAddress {440        ParamAddress(area: p.area, deck: try deckIndex(p.deck, frame, at: loc), effect: p.effect, key: p.key)441    }442443    /// Clamps a value to the parameter's range and puts durations in the parameter's unit.444    private func conform(_ v: Value, to def: ParamDef, at loc: SourceLocation) throws -> Value {445        func clamp(_ x: Double) -> Double {446            guard x.isFinite else { return def.min }447            if x < def.min || x > def.max { stats.clampedValues += 1 }448            return min(max(x, def.min), def.max)449        }450        switch (v, def.type) {451        case let (.number(n), .number): return .number(clamp(n))452        case let (.gain(g), .gain): return .gain(clamp(g))453        case let (.frequency(f), .frequency): return .frequency(clamp(f))454        case (.bool, .bool): return v455        case let (.string(s), .string):456            if !def.allowed.isEmpty, !def.allowed.contains(s) { throw ScriptRuntimeError("E-RANGE", "\"\(s)\" is not accepted here (\(def.rangeText)).", at: loc) }457            return v458        case let (.duration(span), .duration):459            let bpm = max(20, target.clockBPM)460            switch def.durationUnit {461            case .beats: return .duration(.beats(clamp(span.beats(atBPM: bpm))))462            case .milliseconds: return .duration(.seconds(clamp(span.seconds(atBPM: bpm) * 1000) / 1000))463            case .seconds: return .duration(.seconds(span.seconds(atBPM: bpm)))464            }465        default: throw ScriptRuntimeError("E-TYPE", "Expected \(def.type), got \(v.type).", at: loc)466        }467    }468469    /// Executes one statement. Returns the beat at which the task must resume, or nil to continue immediately.470    private func execute(_ stmt: PStmt, frame: Frame, task: ScriptTask) throws -> Double? {471        let loc = stmt.location472        switch stmt.kind {473        case let .setLocal(slot, e):474            frame.slots[slot] = try eval(e, frame)475476        case let .write(path, e):477            let addr = try address(path, frame, at: loc)478            let value = try conform(try eval(e, frame), to: path.def, at: loc)479            try chargeCommand(at: loc)480            ramps.removeAll { $0.address == addr }481            target.write(addr, value, atBeat: currentBeat, rampBeats: 0)482            if addr.area == .fx, addr.key == "enabled" {483                let key = ActionAddress(area: .fx, deck: addr.deck, effect: addr.effect, name: "")484                if value == .bool(true) { enabledEffects.insert(key) } else { enabledEffects.remove(key) }485            }486            stats.writes += 1487            trace(.write, "\(addr) = \(value.display(unit: path.def.unit))", line: loc.line, address: addr, value: value)488489        case let .action(action, args):490            let addr = ActionAddress(area: action.area, deck: try deckIndex(action.deck, frame, at: loc), effect: action.effect, name: action.name)491            let values = try args.map { try eval($0, frame) }492            try chargeCommand(at: loc)493            if let message = target.perform(addr, values, atBeat: currentBeat) { throw ScriptRuntimeError("E-ACTION", message, at: loc) }494            if addr.area == .fx {495                let key = ActionAddress(area: .fx, deck: addr.deck, effect: addr.effect, name: "")496                if addr.name == "enable" { enabledEffects.insert(key) } else if addr.name == "disable" { enabledEffects.remove(key) }497                else if addr.name == "toggle" {498                    // A toggle that switched the effect on is tracked like enable(); one that switched it off is forgotten.499                    // Track what the effect really is now, not what this automation believes.500                    let on = target.read(ParamAddress(area: .fx, deck: addr.deck, effect: addr.effect, key: "enabled")) == .bool(true)501                    if on { enabledEffects.insert(key) } else { enabledEffects.remove(key) }502                }503            }504            stats.actions += 1505            trace(.action, "\(addr)(\(values.map(\.description).joined(separator: ", ")))", line: loc.line)506507        case let .callProcedure(index, args):508            let fn = program.functions[index]509            let depth = task.stack.reduce(0) { if case .procedure = $1.kind { return $0 + 1 }; return $0 }510            guard depth < limits.maxCallDepth else { throw ScriptRuntimeError("E-LIMIT", "Procedure calls nested more than \(limits.maxCallDepth) deep.", at: loc) }511            let callee = Frame(count: fn.slotNames.count)512            for (i, a) in args.enumerated() { callee.slots[i] = try eval(a, frame) }513            task.stack.append(Activation(body: fn.body, frame: callee, kind: .procedure))514515        case let .print(args):516            let text = try args.map { try eval($0, frame).display() }.joined(separator: " ")517            trace(.print, String(text.prefix(2048)), line: loc.line)518519        case let .wait(spec):520            switch spec {521            case let .duration(e):522                let b = try beats(e, frame, "The wait", at: loc)523                trace(.wait, "wait \(formatNumber(b)) beats", line: loc.line)524                return currentBeat + b525            case .nextBeat: return Self.nextBoundary(after: currentBeat, every: 1)526            case .nextBar: return Self.nextBoundary(after: currentBeat, every: ORIXScriptLanguage.beatsPerBar)527            case let .until(a):528                let when = try anchorBeat(a, frame, at: loc)529                if when < currentBeat - 1e-9 { trace(.warning, "line \(loc.line): 'wait until' names a position that has already passed", line: loc.line) }530                return max(when, currentBeat)531            }532533        case let .spawn(anchor, body):534            guard tasks.count < limits.maxTasks else { throw ScriptRuntimeError("E-LIMIT", "More than \(limits.maxTasks) scheduled blocks at once.", at: loc) }535            let when = try anchorBeat(anchor, frame, at: loc)536            if when < currentBeat - 1e-9 {537                trace(.warning, "line \(loc.line): 'at' names a position \(formatNumber(currentBeat - when)) beats in the past; running it now", line: loc.line)538            }539            // The block sees the variables as they are now.540            spawnTask(body: body, frame: Frame(copying: frame), wake: max(when, currentBeat), isHandler: false)541            trace(.spawn, "scheduled block at beat \(formatNumber(max(when, currentBeat) - startBeat + 1))", line: loc.line)542543        case let .over(durationExpr, curve, rampSpecs, immediates):544            let length = try beats(durationExpr, frame, "The 'over' duration", at: loc)545            for s in immediates {546                try charge(1, at: s.location)547                if try execute(s, frame: frame, task: task) != nil { throw ScriptRuntimeError("E-OVER", "Timed statements are not allowed inside 'over'.", at: s.location) }548            }549            for r in rampSpecs {550                let addr = try address(r.path, frame, at: r.location)551                let targetValue = try conform(try eval(r.target, frame), to: r.path.def, at: r.location)552                guard let to = targetValue.scalar else { throw ScriptRuntimeError("E-RAMP", "'\(addr)' cannot be ramped.", at: r.location) }553                guard let from = target.read(addr)?.scalar else {554                    throw ScriptRuntimeError("E-UNAVAILABLE", "'\(addr)' cannot be read right now" + (addr.area == .fx ? " (enable the effect first)." : "."), at: r.location)555                }556                try chargeCommand(at: r.location)557                ramps.removeAll { $0.address == addr }558                guard ramps.count < limits.maxRamps else { throw ScriptRuntimeError("E-LIMIT", "More than \(limits.maxRamps) ramps at once.", at: r.location) }559                ramps.append(ActiveRamp(address: addr, def: r.path.def, from: from, to: to, start: currentBeat, end: currentBeat + length, curve: curve, lastWritten: from, line: r.location.line))560                stats.peakRamps = max(stats.peakRamps, ramps.count)561                trace(.ramp, "\(addr) -> \(targetValue.display(unit: r.path.def.unit)) over \(formatNumber(length)) beats", line: r.location.line, address: addr, value: targetValue)562            }563            return currentBeat + length564565        case let .every(periodExpr, totalExpr, body):566            let period = try beats(periodExpr, frame, "The 'every' period", at: loc)567            let total = try beats(totalExpr, frame, "The 'every' length", at: loc)568            guard period >= CompileLimits.minEveryPeriodBeats else { throw ScriptRuntimeError("E-LIMIT", "The 'every' period cannot be shorter than 1/64 beat.", at: loc) }569            guard total / period <= Double(limits.maxLoopIterations) else { throw ScriptRuntimeError("E-LIMIT", "This 'every' loop would run more than \(limits.maxLoopIterations) times.", at: loc) }570            if total > 0 { task.stack.append(Activation(body: body, frame: frame, kind: .every(period: period, end: currentBeat + total, next: currentBeat + period))) }571572        case let .repeatLoop(countExpr, body):573            guard case let .number(n) = try eval(countExpr, frame), n == n.rounded(), n >= 0 else { throw ScriptRuntimeError("E-RANGE", "A loop count must be a whole number, zero or more.", at: loc) }574            guard n <= Double(limits.maxLoopIterations) else { throw ScriptRuntimeError("E-LIMIT", "A loop cannot run more than \(limits.maxLoopIterations) times.", at: loc) }575            if n >= 1 { task.stack.append(Activation(body: body, frame: frame, kind: .repeatLoop(remaining: Int(n) - 1))) }576577        case let .forRange(slot, fromExpr, toExpr, inclusive, body):578            guard case let .number(a) = try eval(fromExpr, frame), case let .number(b) = try eval(toExpr, frame), a.isFinite, b.isFinite else {579                throw ScriptRuntimeError("E-RANGE", "Range bounds must be numbers.", at: loc)580            }581            guard b - a <= Double(limits.maxLoopIterations) else { throw ScriptRuntimeError("E-LIMIT", "A loop cannot run more than \(limits.maxLoopIterations) times.", at: loc) }582            if inclusive ? a <= b : a < b {583                frame.slots[slot] = .number(a)584                task.stack.append(Activation(body: body, frame: frame, kind: .forRange(slot: slot, next: a + 1, end: b, inclusive: inclusive)))585            }586587        case let .forIn(slot, arrayExpr, body):588            guard case let .array(items) = try eval(arrayExpr, frame) else { throw ScriptRuntimeError("E-TYPE", "'for … in' needs an array.", at: loc) }589            if let first = items.first {590                frame.slots[slot] = first591                task.stack.append(Activation(body: body, frame: frame, kind: .forArray(slot: slot, items: items, next: 1)))592            }593594        case let .whileLoop(cond, limit, body):595            if case .bool(true) = try eval(cond, frame) {596                task.stack.append(Activation(body: body, frame: frame, kind: .whileLoop(cond, remaining: limit - 1, loc)))597            }598599        case let .ifElse(cond, thenBody, elseBody):600            guard case let .bool(b) = try eval(cond, frame) else { throw ScriptRuntimeError("E-TYPE", "The condition is not true or false.", at: loc) }601            let chosen = b ? thenBody : elseBody602            if !chosen.isEmpty { task.stack.append(Activation(body: chosen, frame: frame, kind: .plain)) }603604        case let .on(event, once, body):605            guard handlers.count < limits.maxHandlers else { throw ScriptRuntimeError("E-LIMIT", "More than \(limits.maxHandlers) event handlers.", at: loc) }606            let key: EventKey607            switch event {608            case .beat: key = .beat609            case .bar: key = .bar610            case let .trigger(e):611                guard case let .number(n) = try eval(e, frame), n == n.rounded(), n >= 1, n <= Double(ScriptSchema.triggerCount) else {612                    throw ScriptRuntimeError("E-RANGE", "Triggers are numbered 1 to \(ScriptSchema.triggerCount).", at: loc)613                }614                key = .trigger(Int(n))615            case let .deck(e, name):616                guard let d = try deckIndex(e, frame, at: loc) else { throw ScriptRuntimeError("E-TYPE", "Expected a deck.", at: loc) }617                key = .deck(d, name)618            }619            handlers.append(Handler(key: key, once: once, body: body, frame: frame, line: loc.line))620621        case .returnValue:622            // Leave the innermost procedure; at the top level of a task this ends the task.623            while let a = task.stack.popLast() { if case .procedure = a.kind { break } }624625        case .stop:626            finish(.stopped, at: currentBeat)627628        case .breakLoop:629            while let a = task.stack.popLast() { if a.kind.isLoop { break } }630631        case .continueLoop:632            while let a = task.stack.last, !a.kind.isLoop { task.stack.removeLast() }633            if !task.stack.isEmpty { task.stack[task.stack.count - 1].pc = task.stack[task.stack.count - 1].body.count }634        }635        return nil636    }637638    // MARK: Ramps639640    /// Writes the final value of every ramp ending at or before `beat` and removes it.641    private func finishRamps(upTo beat: Double) throws {642        guard !ramps.isEmpty else { return }643        var i = 0644        while i < ramps.count {645            let r = ramps[i]646            guard r.end <= beat + 1e-9 else { i += 1; continue }647            let value: Value = switch r.def.type { case .gain: .gain(r.to); case .frequency: .frequency(r.to); default: .number(r.to) }648            target.write(r.address, value, atBeat: r.end, rampBeats: 0)649            stats.rampWrites += 1650            trace(.rampEnd, "\(r.address) reached \(formatNumber(r.to))", line: r.line, beat: r.end, address: r.address, value: value)651            ramps.remove(at: i)652        }653    }654655    private func updateRamps(at beat: Double) throws {656        guard !ramps.isEmpty else { return }657        let step = max(0, beat - lastBeat)658        var i = 0659        while i < ramps.count {660            var r = ramps[i]661            if beat < r.start { i += 1; continue }662            let t = r.end > r.start ? min(1, (beat - r.start) / (r.end - r.start)) : 1663            let s = r.curve.shape(t)664            var x: Double665            if r.def.type == .frequency, r.from > 0, r.to > 0 { x = r.from * pow(r.to / r.from, s) } else { x = r.from + (r.to - r.from) * s }666            if t >= 1 { x = r.to }667            if x != r.lastWritten || t >= 1 {668                let value: Value = switch r.def.type { case .gain: .gain(x); case .frequency: .frequency(x); default: .number(x) }669                target.write(r.address, value, atBeat: beat, rampBeats: t >= 1 ? 0 : step)670                stats.rampWrites += 1671                r.lastWritten = x672            }673            if t >= 1 {674                trace(.rampEnd, "\(r.address) reached \(formatNumber(r.to))", line: r.line, beat: r.end, address: r.address, value: r.def.type == .gain ? .gain(r.to) : (r.def.type == .frequency ? .frequency(r.to) : .number(r.to)))675                ramps.remove(at: i)676            } else { ramps[i] = r; i += 1 }677        }678    }679680    // MARK: Expressions681682    private func eval(_ e: PExpr, _ frame: Frame, depth: Int = 0) throws -> Value {683        switch e {684        case let .const(v): return v685        case let .local(slot): return frame.slots[slot]686        case let .read(path, loc):687            try charge(1, at: loc)688            let addr = try address(path, frame, at: loc)689            guard let v = target.read(addr) else {690                throw ScriptRuntimeError("E-UNAVAILABLE", "'\(addr)' cannot be read right now" + (addr.area == .fx ? " (the effect is not in the rack; call enable() first)." : "."), at: loc)691            }692            return v693        case let .unary(op, a, loc):694            return try Evaluator.unary(op, try eval(a, frame, depth: depth), at: loc)695        case let .binary(op, a, b, loc):696            try charge(1, at: loc)697            let x = try eval(a, frame, depth: depth)698            // Short-circuit logic.699            if op == "&&", case .bool(false) = x { return x }700            if op == "||", case .bool(true) = x { return x }701            return try Evaluator.binary(op, x, try eval(b, frame, depth: depth), bpm: max(20, target.clockBPM), at: loc)702        case let .builtin(name, args, loc):703            try charge(1, at: loc)704            if name == "random" {705                rngState ^= rngState << 13; rngState ^= rngState >> 7; rngState ^= rngState << 17706                return .number(Double(rngState >> 11) / Double(1 << 53))707            }708            return try Evaluator.builtin(name, try args.map { try eval($0, frame, depth: depth) }, bpm: max(20, target.clockBPM), at: loc)709        case let .callFunction(index, args, loc):710            guard depth < limits.maxCallDepth else { throw ScriptRuntimeError("E-LIMIT", "Function calls nested more than \(limits.maxCallDepth) deep.", at: loc) }711            let fn = program.functions[index]712            let callee = Frame(count: fn.slotNames.count)713            for (i, a) in args.enumerated() { callee.slots[i] = try eval(a, frame, depth: depth) }714            if case let .returned(v) = try runPure(fn.body, callee, depth: depth + 1) { return v }715            throw ScriptRuntimeError("E-RETURN", "Function '\(fn.name)' ended without returning a value.", at: loc)716        case let .array(items):717            return .array(try items.map { try eval($0, frame, depth: depth) })718        case let .index(base, idx, loc):719            guard case let .array(items) = try eval(base, frame, depth: depth), case let .number(n) = try eval(idx, frame, depth: depth) else {720                throw ScriptRuntimeError("E-TYPE", "Only arrays can be indexed with a number.", at: loc)721            }722            guard n == n.rounded(), n >= 0, Int(n) < items.count else {723                throw ScriptRuntimeError("E-RANGE", "Index \(formatNumber(n)) is outside the array (0 to \(items.count - 1)).", at: loc)724            }725            return items[Int(n)]726        }727    }728729    /// Interprets the body of a value-returning function (no timing, no side effects on the rig).730    private func runPure(_ body: [PStmt], _ frame: Frame, depth: Int) throws -> Flow {731        for s in body {732            try charge(1, at: s.location)733            switch s.kind {734            case let .setLocal(slot, e): frame.slots[slot] = try eval(e, frame, depth: depth)735            case let .returnValue(e): return .returned(try e.map { try eval($0, frame, depth: depth) } ?? .void)736            case .breakLoop: return .breakLoop737            case .continueLoop: return .continueLoop738            case let .ifElse(cond, a, b):739                guard case let .bool(c) = try eval(cond, frame, depth: depth) else { throw ScriptRuntimeError("E-TYPE", "The condition is not true or false.", at: s.location) }740                let flow = try runPure(c ? a : b, frame, depth: depth)741                if case .normal = flow { continue }742                return flow743            case let .repeatLoop(countExpr, inner):744                guard case let .number(n) = try eval(countExpr, frame, depth: depth), n >= 0, n <= Double(limits.maxLoopIterations) else {745                    throw ScriptRuntimeError("E-LIMIT", "A loop count must be between 0 and \(limits.maxLoopIterations).", at: s.location)746                }747                var k = 0748                loop: while k < Int(n) {749                    try charge(1, at: s.location)750                    switch try runPure(inner, frame, depth: depth) { case .breakLoop: break loop; case let .returned(v): return .returned(v); default: break }751                    k += 1752                }753            case let .forRange(slot, fromExpr, toExpr, inclusive, inner):754                guard case let .number(a) = try eval(fromExpr, frame, depth: depth), case let .number(b) = try eval(toExpr, frame, depth: depth), b - a <= Double(limits.maxLoopIterations) else {755                    throw ScriptRuntimeError("E-LIMIT", "A loop cannot run more than \(limits.maxLoopIterations) times.", at: s.location)756                }757                var x = a758                loop: while inclusive ? x <= b : x < b {759                    try charge(1, at: s.location)760                    frame.slots[slot] = .number(x)761                    switch try runPure(inner, frame, depth: depth) { case .breakLoop: break loop; case let .returned(v): return .returned(v); default: break }762                    x += 1763                }764            case let .forIn(slot, arrayExpr, inner):765                guard case let .array(items) = try eval(arrayExpr, frame, depth: depth) else { throw ScriptRuntimeError("E-TYPE", "'for … in' needs an array.", at: s.location) }766                loop: for item in items {767                    try charge(1, at: s.location)768                    frame.slots[slot] = item769                    switch try runPure(inner, frame, depth: depth) { case .breakLoop: break loop; case let .returned(v): return .returned(v); default: break }770                }771            case let .whileLoop(cond, limit, inner):772                var remaining = limit773                loop: while case .bool(true) = try eval(cond, frame, depth: depth) {774                    try charge(1, at: s.location)775                    guard remaining > 0 else { throw ScriptRuntimeError("E-UNBOUNDED", "The 'while' loop reached its limit without its condition becoming false.", at: s.location) }776                    remaining -= 1777                    switch try runPure(inner, frame, depth: depth) { case .breakLoop: break loop; case let .returned(v): return .returned(v); default: break }778                }779            default:780                throw ScriptRuntimeError("E-PURE", "This statement is not allowed in a function that returns a value.", at: s.location)781            }782        }783        return .normal784    }785}786
Files main
Menu

Theme