Repository Public
1// ORIX DJ2// File: Packages/ORIXDJCore/Tests/ORIXScriptTests/LanguageTests.swift3// Description: ORIX Script tests: lexer, parser, type and unit checking, validation, timing semantics, events, loops,4// limits, cancellation, simulator and debugger.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import ORIXDSP10@testable import ORIXScript11import Testing1213func compileOK(_ source: String, sourceLocation: Testing.SourceLocation = #_sourceLocation) -> Program {14 let r = ScriptCompiler.compile(source)15 #expect(r.errors.isEmpty, "unexpected errors: \(r.errors)", sourceLocation: sourceLocation)16 return r.program ?? Program(automations: [], functions: [], languageVersion: "")17}1819func errorCodes(_ source: String) -> [String] { ScriptCompiler.compile(source).errors.map(\.code) }2021func simulate(_ source: String, _ configure: (inout SimulationConfig) -> Void = { _ in }, sourceLocation: Testing.SourceLocation = #_sourceLocation) -> SimulationResult {22 var config = SimulationConfig()23 configure(&config)24 let program = compileOK(source, sourceLocation: sourceLocation)25 return Simulator.run(program, config: config) ?? SimulationResult(trace: [], curves: [:], playSpans: [], state: .stopped, beats: 0, timedOut: false, stats: .init(), finalVariables: [])26}2728func wrap(_ body: String) -> String { "automation \"T\" {\n\(body)\n}" }2930extension SimulationResult {31 func writes(_ path: String) -> [(beat: Double, value: Double)] {32 trace.filter { $0.kind == .write && $0.address?.description == path }.map { ($0.beat, $0.value?.scalar ?? .nan) }33 }3435 func actionBeats(_ text: String) -> [Double] { trace.filter { $0.kind == .action && $0.text.hasPrefix(text) }.map(\.beat) }36 func prints() -> [String] { trace.filter { $0.kind == .print }.map(\.text) }37 func curve(_ path: String) -> [CurvePoint] { curves.first { $0.key.description == path }?.value ?? [] }38 func value(_ path: String, at beat: Double) -> Double? { curve(path).last { $0.beat <= beat + 1e-9 }?.value }39}4041@Suite struct LexerTests {42 @Test func unitLiterals() {43 var lexer = Lexer("-12dB 20Hz 12kHz 4bars 8 bars 1/4beat 3/2bars 50% 250ms 2s 128bpm 7 % 3 1_000 9%2")44 let kinds = lexer.tokenize().map(\.kind)45 #expect(lexer.diagnostics.isEmpty)46 #expect(kinds == [47 .symbol("-"), .literal(.gain(12)), .literal(.frequency(20)), .literal(.frequency(12000)), .literal(.duration(.beats(16))),48 .literal(.duration(.beats(32))), .literal(.duration(.beats(0.25))), .literal(.duration(.beats(6))), .literal(.number(0.5)),49 .literal(.duration(.seconds(0.25))), .literal(.duration(.seconds(2))), .literal(.number(128)),50 .number(7), .symbol("%"), .number(3), .number(1000), .number(9), .symbol("%"), .number(2), .eof,51 ])52 }5354 @Test func commentsStringsAndLocations() {55 var lexer = Lexer("// hello\nlet a = \"x\\\"y\" /* block\n */ deck.A")56 let tokens = lexer.tokenize()57 #expect(lexer.comments.count == 2)58 #expect(tokens.contains { $0.kind == .string("x\"y") })59 let deck = tokens.first { $0.kind == .identifier("deck") }!60 #expect(deck.location == SourceLocation(line: 3, column: 5))61 }6263 @Test func errors() {64 var a = Lexer("let x = 5parsecs"); _ = a.tokenize()65 #expect(a.diagnostics.map(\.code) == ["E-UNIT"])66 var b = Lexer("\"open"); _ = b.tokenize()67 #expect(b.diagnostics.map(\.code) == ["E-LEX"])68 var c = Lexer("a # b"); _ = c.tokenize()69 #expect(c.diagnostics.map(\.code) == ["E-LEX"])70 }7172 @Test func highlightCoversInvalidSource() {73 let spans = Lexer.highlight("automation \"x\" { deck.A.volume = -6dB // c\n !!! ")74 #expect(spans.contains { $0.tokenClass == .keyword })75 #expect(spans.contains { $0.tokenClass == .comment })76 #expect(spans.contains { $0.tokenClass == .root })77 }78}7980@Suite struct ParserTests {81 @Test func briefExampleParsesAndCompiles() {82 // The example of the product brief, with `let` for the variable (explicit declarations catch typos).83 let source = """84 automation "Eight Bar Transition" {85 let tempo = master.bpm8687 at bar 1 {88 deck.A.filter.highpass = 20Hz89 deck.B.volume = -12dB90 }9192 over 8 bars {93 deck.A.filter.highpass -> 12000Hz94 deck.A.volume -> -60dB95 deck.B.volume -> 0dB96 }9798 at bar 8 {99 deck.B.play()100 deck.A.pause()101 }102 }103 """104 let program = compileOK(source)105 #expect(program.automations.first?.requirements.deckLetters == ["A", "B"])106 #expect(program.automations.first?.requirements.lengthBeats == 32)107 }108109 @Test func syntaxErrorsCarryLineAndColumn() {110 let r = ScriptCompiler.compile("automation \"X\" {\n deck.A.volume = \n wait 4beats\n}")111 #expect(r.program == nil)112 #expect(r.errors.first?.location.line == 2)113 let r2 = ScriptCompiler.compile("automation \"X\" {\n wait 4beats")114 #expect(r2.errors.contains { $0.code == "E-SYNTAX" })115 let r3 = ScriptCompiler.compile("deck.A.play()")116 #expect(r3.errors.first?.location == SourceLocation(line: 1, column: 1))117 }118119 @Test func recoversAndReportsSeveralErrors() {120 let r = ScriptCompiler.compile(wrap("deck.A.volume = = 3\nwait\ndeck.B.play("))121 #expect(r.errors.count >= 3)122 }123124 @Test func emptyAndUnboundedRejected() {125 #expect(errorCodes("") == ["E-EMPTY"])126 #expect(errorCodes(wrap("while true { wait 1beat }")).contains("E-UNBOUNDED"))127 }128129 @Test func deepNestingIsBounded() {130 let deep = String(repeating: "if true {\n", count: 80) + String(repeating: "}\n", count: 80)131 #expect(errorCodes(wrap(deep)).contains("E-LIMIT"))132 let parens = "let x = " + String(repeating: "(", count: 500) + "1" + String(repeating: ")", count: 500)133 #expect(errorCodes(wrap(parens)).contains("E-LIMIT"))134 }135}136137@Suite struct CheckerTests {138 @Test(arguments: [139 ("deck.A.volume = 20Hz", "E-TYPE"),140 ("deck.A.filter.highpass = -6dB", "E-TYPE"),141 ("deck.A.filter.highpass = 500", "E-TYPE"),142 ("deck.A.volume = 6dB", "E-RANGE"),143 ("deck.A.filter.highpass = 30kHz", "E-RANGE"),144 ("mixer.crossfader = 1.5", "E-RANGE"),145 ("mixer.curve = \"wobbly\"", "E-RANGE"),146 ("deck.E.play()", "E-DECK"),147 ("deck.A.plya()", "E-PATH"),148 ("deck.A.volumee = -6dB", "E-PATH"),149 ("deck.A.position = 4s", "E-READONLY"),150 ("fx.warp.enable()", "E-EFFECT"),151 ("fx.delay.feedbak = 0.3", "E-PATH"),152 ("fx.delay.feedback = 2", "E-RANGE"),153 ("fx.delay.time = 8beats", "E-RANGE"),154 ("deck.A.volume -> -60dB", "E-RAMP"),155 ("over 4beats { deck.A.keylock -> true }", "E-RAMP"),156 ("over 4beats { wait 1beat }", "E-OVER"),157 ("over 0beats { deck.A.volume -> -6dB }", "E-RANGE"),158 ("wait 4", "E-TYPE"),159 ("wait -1beat", "E-RANGE"),160 ("x = 3", "E-UNDECLARED"),161 ("let x = 3\nx = 4", "E-CONST"),162 ("let x = 3\nlet x = 4", "E-REDECLARED"),163 ("var x = 3\nx = 4dB", "E-TYPE"),164 ("let x = 3 + 4dB", "E-TYPE"),165 ("let x = 1 / 0", "E-MATH"),166 ("if deck.A.bpm { }", "E-TYPE"),167 ("repeat 1000000 { }", "E-LIMIT"),168 ("repeat 2.5 { }", "E-RANGE"),169 ("for i in 1...50000 { }", "E-LIMIT"),170 ("every 1/128beat for 4beats { }", "E-LIMIT"),171 ("while deck.A.playing limit 1000000 { wait 1beat }", "E-UNBOUNDED"),172 ("break", "E-LOOP"),173 ("return", "E-RETURN"),174 ("at bar 0 { }", "E-RANGE"),175 ("deck.A.hotcue(9)", "E-RANGE"),176 ("deck.A.seek()", "E-ARGS"),177 ("deck.A.seek(3)", "E-TYPE"),178 ("on deck.A.finished { }", "E-EVENT"),179 ("on trigger(40) { }", "E-RANGE"),180 ("repeat 2 { on beat { } }", "E-EVENT"),181 ("let a = [1, 2dB]", "E-TYPE"),182 ("let b = [1, 2][5]", "E-RANGE"),183 ("let a = min(1, 2dB)", "E-ARGS"),184 ("nothing(3)", "E-UNDECLARED"),185 ("let v = deck.A.play()", "E-TYPE"),186 ("mixer.channel.A.wobble = 1", "E-PATH"),187 ("master.beat = 4", "E-READONLY"),188 ])189 func rejects(_ body: String, _ code: String) {190 let codes = errorCodes(wrap(body))191 #expect(codes.contains(code), "\(body) -> \(codes)")192 }193194 @Test func helpfulMessages() {195 let r = ScriptCompiler.compile(wrap("deck.A.volum = -6dB"))196 #expect(r.errors.first?.message.contains("Did you mean 'volume'?") == true)197 let r2 = ScriptCompiler.compile(wrap("deck.A.play = true"))198 #expect(r2.errors.first?.message.contains("action") == true)199 }200201 @Test func capabilityValidation() {202 let two = Capabilities(deckCount: 2, effects: [.delay])203 #expect(ScriptCompiler.compile(wrap("deck.C.play()"), capabilities: two).errors.map(\.code) == ["E-CAPABILITY"])204 #expect(ScriptCompiler.compile(wrap("fx.reverb.enable()"), capabilities: two).errors.map(\.code) == ["E-CAPABILITY"])205 #expect(ScriptCompiler.compile(wrap("fx.delay.enable()\ndeck.B.play()"), capabilities: two).succeeded)206 }207208 @Test func functionsAndRecursion() {209 let ok = """210 let fade = 4bars211 fn half(x: number) -> number { return x / 2 }212 fn fadeOut(d: deck, len: duration) {213 over len { d.volume -> -60dB }214 d.pause()215 }216 automation "F" {217 let n = half(8)218 fadeOut(deck.A, fade)219 }220 """221 let program = compileOK(ok)222 // The length depends on an argument, so it is not known statically.223 #expect(program.automations[0].requirements.lengthBeats == nil)224 let rec = "fn a(x: number) -> number { return b(x) }\nfn b(x: number) -> number { return a(x) }\nautomation \"R\" { let v = a(1) }"225 #expect(errorCodes(rec).contains("E-RECURSION"))226 #expect(errorCodes("fn f(x: number) -> number { wait 1beat\n return x }\nautomation \"R\" { let v = f(1) }").contains("E-PURE"))227 #expect(errorCodes("fn f(x: number) -> number { if x > 1 { return x } }\nautomation \"R\" { let v = f(1) }").contains("E-RETURN"))228 #expect(errorCodes("fn f(x: number) -> number { return deck.A.bpm }\nautomation \"R\" { let v = f(1) }").contains("E-PURE"))229 }230231 @Test func implicitLinearGain() {232 let r = simulate(wrap("deck.A.volume = 50%\ndeck.B.volume = 0"))233 #expect(abs(r.writes("deck.A.volume")[0].value - -6.0206) < 1e-3)234 #expect(r.writes("deck.B.volume")[0].value == -60)235 }236}237238@Suite struct RuntimeTests {239 @Test func sequentialTiming() {240 let r = simulate(wrap("deck.A.volume = -6dB\nwait 4beats\ndeck.A.volume = -12dB\nwait 2bars\ndeck.A.pause()"))241 #expect(r.writes("deck.A.volume").map(\.beat) == [0, 4])242 #expect(r.actionBeats("deck.A.pause") == [12])243 #expect(r.state == .finished)244 #expect(r.beats == 12)245 }246247 @Test func atBlocksAreAbsoluteAndDoNotMoveTheCursor() {248 let r = simulate(wrap("at bar 3 { deck.B.play() }\nat beat 2 { deck.A.setCue() }\nat 6beats { deck.A.loopExit() }\ndeck.A.pause()"))249 #expect(r.actionBeats("deck.B.play") == [8])250 #expect(r.actionBeats("deck.A.setCue") == [1])251 #expect(r.actionBeats("deck.A.loopExit") == [6])252 #expect(r.actionBeats("deck.A.pause") == [0])253 }254255 @Test func rampsReachTargetsExactly() {256 let r = simulate(wrap("deck.A.volume = 0dB\nover 8beats {\n deck.A.volume -> -40dB\n deck.A.filter.highpass -> 2kHz\n mixer.crossfader -> 1\n}\ndeck.A.pause()"))257 #expect(abs(r.value("deck.A.volume", at: 4)! - -20) < 1e-9)258 #expect(r.value("deck.A.volume", at: 8) == -40)259 // Frequencies ramp on a logarithmic scale: the midpoint is the geometric mean.260 #expect(abs(r.value("deck.A.filter.highpass", at: 4)! - (20 * 2000).squareRoot()) < 1e-6)261 #expect(r.value("mixer.crossfader", at: 8) == 1)262 #expect(abs(r.value("mixer.crossfader", at: 2)! - 0.625) < 1e-9)263 #expect(r.actionBeats("deck.A.pause") == [8])264 }265266 @Test func rampTargetIsReachedBeforeTheNextStatement() {267 // The statement after an `over` block sees the target, a second ramp starts from it, and `stop` does not lose it.268 let r = simulate(wrap("mixer.crossfader = 0\nover 4 beats { mixer.crossfader -> 1 }\nprint(mixer.crossfader)\nover 4 beats { mixer.crossfader -> 0.5 }\nstop"))269 #expect(r.prints() == ["1"])270 #expect(r.value("mixer.crossfader", at: 6) == 0.75)271 #expect(r.value("mixer.crossfader", at: 8) == 0.5)272 // An effect switched on through its parameter or toggle() is bypassed when the script fails.273 let f = simulate(wrap("fx.echo.enabled = true\nfx.reverb.toggle()\nwait 1beat\ndeck.C.play()"))274 #expect(f.trace.filter { $0.kind == .warning && $0.text.contains("bypassed") }.count == 2)275 // A fraction may be separated from its unit by a space.276 #expect(simulate(wrap("wait 1/4 beat\ndeck.A.pause()")).actionBeats("deck.A.pause") == [0.25])277 if case let .script(p) = ConsoleParser.parse("toSeconds(8 bars)") { #expect(Simulator.run(p)!.prints() == ["15"]) } else { Issue.record("console call") }278 #expect(errorCodes(wrap("for bar in [1, 2] { }")).contains("E-SYNTAX"))279 }280281 @Test func curves() {282 let r = simulate(wrap("mixer.crossfader = 0\nover 4beats curve easeIn { mixer.crossfader -> 1 }"))283 #expect(abs(r.value("mixer.crossfader", at: 2)! - 0.25) < 1e-9)284 #expect(errorCodes(wrap("over 4beats curve wavy { mixer.crossfader -> 1 }")).contains("E-CURVE"))285 for c in RampCurve.allCases { #expect(c.shape(0) == 0); #expect(abs(c.shape(1) - 1) < 1e-12) }286 }287288 @Test func directWriteCancelsRamp() {289 let r = simulate(wrap("at beat 3 { mixer.crossfader = 0.2 }\nover 8beats { mixer.crossfader -> 1 }"))290 #expect(r.value("mixer.crossfader", at: 8) == 0.2)291 }292293 @Test func loops() {294 let r = simulate(wrap("""295 var n = 0296 repeat 3 { n = n + 1 }297 for i in 1...4 { n = n + i }298 for x in [10, 20] { n = n + x }299 var k = 0300 while k < 5 limit 100 { k = k + 1301 if k == 2 { continue }302 if k == 4 { break }303 n = n + 100 }304 print(n)305 """))306 #expect(r.prints() == ["243"])307 }308309 @Test func everyRunsOnAGrid() {310 let r = simulate(wrap("every 1beat for 4beats { deck.A.setCue() }\ndeck.A.pause()"))311 #expect(r.actionBeats("deck.A.setCue") == [0, 1, 2, 3])312 #expect(r.actionBeats("deck.A.pause") == [4])313 }314315 @Test func procedureCallsRunConcurrentlyWithOwnFrames() {316 let source = """317 fn fade(d: deck, target: gain, len: duration) {318 over len { d.volume -> target }319 }320 automation "P" {321 at beat 1 { fade(deck.A, -20dB, 4beats) }322 at beat 1 { fade(deck.B, -10dB, 8beats) }323 }324 """325 let r = simulate(source)326 #expect(r.value("deck.A.volume", at: 4) == -20)327 #expect(r.value("deck.B.volume", at: 8) == -10)328 #expect(abs(r.value("deck.B.volume", at: 4)! - -5) < 1e-9)329 }330331 @Test func atBlocksCaptureValuesWhenScheduled() {332 let r = simulate(wrap("for i in 1...3 {\n at beat i * 2 { print(i) }\n}"))333 #expect(r.prints() == ["1", "2", "3"])334 }335336 @Test func eventsTrackEndBeatBarTrigger() {337 let r = simulate(wrap("""338 var count = 0339 on deck.A.trackEnd once { deck.B.play()340 print("end", count)341 stop }342 on beat { count = count + 1 }343 on bar { print("bar") }344 on trigger(2) { print("trig") }345 """)) { c in346 c.decks[0].lengthBeats = 10; c.maxBeats = 64; c.triggers = [(3.5, 2), (5, 7)]347 }348 #expect(r.actionBeats("deck.B.play").count == 1)349 #expect(abs(r.actionBeats("deck.B.play")[0] - 10) < 0.1)350 #expect(r.prints().contains("trig"))351 #expect(r.prints().filter { $0 == "bar" }.count == 2)352 #expect(r.prints().contains("end 9") || r.prints().contains("end 10"))353 #expect(r.state == .stopped)354 }355356 @Test func handlersKeepAutomationAliveUntilTimeout() {357 let r = simulate(wrap("on beat { }")) { $0.maxBeats = 16 }358 #expect(r.timedOut)359 #expect(r.state == .running)360 }361362 @Test func conditionsReadLiveState() {363 let r = simulate(wrap("if deck.A.playing and not deck.B.playing { deck.B.play() } else { deck.A.play() }\nwait 1beat\nif deck.B.bpm >= 128 { print(deck.B.bpm, master.deck) }"))364 #expect(r.actionBeats("deck.B.play") == [0])365 #expect(r.prints() == ["128 A"])366 }367368 @Test func waitNextBarAndQuantizedStart() {369 let r = simulate("automation \"Q\" quantize bar {\n deck.B.play()\n wait 1beat\n wait nextBar\n deck.A.pause() }")370 #expect(r.actionBeats("deck.B.play") == [0])371 #expect(r.actionBeats("deck.A.pause") == [4])372 }373374 @Test func secondsFollowTheTempo() {375 // 120 BPM: one second is two beats.376 let r = simulate(wrap("wait 1s\ndeck.A.pause()\nwait 500ms\ndeck.B.play()")) { c in c.bpm = 120; c.decks[0].bpm = 120 }377 #expect(r.actionBeats("deck.A.pause") == [2])378 #expect(r.actionBeats("deck.B.play") == [3])379 }380381 @Test func runtimeErrorsCancelAndBypassEffects() {382 let r = simulate(wrap("fx.echo.enable()\nwait 1beat\ndeck.C.play()"))383 #expect(r.error?.code == "E-ACTION")384 #expect(r.error?.location?.line == 4)385 #expect(r.trace.contains { $0.kind == .warning && $0.text.contains("bypassed fx.echo") })386 }387388 @Test func budgetsStopRunawayScripts() {389 var limits = RuntimeLimits(); limits.maxOperationsPerStep = 500390 let r = simulate(wrap("var n = 0\nrepeat 10000 { n = n + 1 }")) { $0.limits = limits }391 #expect(r.error?.code == "E-BUDGET")392 let rate = simulate(wrap("repeat 2000 { mixer.crossfader = 0.5 }"))393 #expect(rate.error?.code == "E-RATE")394 let w = simulate(wrap("var k = 0\nwhile k >= 0 limit 50 { k = k + 1 }"))395 #expect(w.error?.code == "E-UNBOUNDED")396 var few = RuntimeLimits(); few.maxTasks = 8397 let tasks = simulate(wrap("for i in 1...50 { at bar 20 { } }")) { $0.limits = few }398 #expect(tasks.error?.code == "E-LIMIT")399 }400401 @Test func dynamicValuesAreClampedAndCounted() {402 let r = simulate(wrap("let x = deck.A.bpm\nmixer.crossfader = x"))403 #expect(r.writes("mixer.crossfader")[0].value == 1)404 #expect(r.stats.clampedValues == 1)405 }406407 @Test func stopPauseResume() {408 let program = compileOK(wrap("wait 4beats\ndeck.A.pause()\nwait 4beats\ndeck.B.play()"))409 let rig = SimulatedRig()410 let instance = AutomationInstance(program: program, automation: program.automations[0], target: rig, nowBeat: 0)411 var actions: [Double] = []412 instance.onTrace = { if $0.kind == .action { actions.append($0.beat) } }413 instance.advance(to: 2)414 instance.pause(atBeat: 2)415 instance.advance(to: 10)416 #expect(actions.isEmpty)417 instance.resume(atBeat: 10)418 instance.advance(to: 12.5)419 #expect(actions == [12])420 instance.stop()421 instance.advance(to: 40)422 #expect(actions == [12])423 #expect(instance.state == .stopped)424 }425426 @Test func randomIsDeterministic() {427 let a = simulate(wrap("print(random(), random())")).prints()428 let b = simulate(wrap("print(random(), random())")).prints()429 #expect(a == b)430 #expect(a.first?.split(separator: " ").count == 2)431 }432433 @Test func malformedInputNeverCrashes() {434 var rng = SystemRandomNumberGenerator()435 let fragments = ["automation", "\"x\"", "{", "}", "(", ")", "deck.A", ".volume", "=", "->", "-6dB", "over", "8bars", "at", "bar", "1", "wait", "on", "fn", "let", "\n", "[", "]", ",", "if", "else", "repeat", "9999999999999", "1/4beat", "%", "//", "/*", "\"", "for", "in", "...", "while", "limit", "every", "trigger"]436 for _ in 0 ..< 3000 {437 let n = Int.random(in: 1 ... 40, using: &rng)438 let text = (0 ..< n).map { _ in fragments.randomElement(using: &rng)! }.joined(separator: " ")439 let r = ScriptCompiler.compile(text)440 if let p = r.program, let a = p.automations.first {441 var config = SimulationConfig(); config.maxBeats = 32442 let s = DebugSession(program: p, automation: a, config: config)443 s.run()444 }445 }446 for _ in 0 ..< 500 {447 let bytes = (0 ..< Int.random(in: 0 ... 200, using: &rng)).map { _ in UInt8.random(in: 0 ... 255, using: &rng) }448 _ = ScriptCompiler.compile(String(decoding: bytes, as: UTF8.self))449 }450 }451}452453@Suite struct ToolTests {454 @Test func debuggerBreakpointsAndStepping() {455 let program = compileOK(wrap("var x = 1\nwait 2beats\nx = x + 1\ndeck.A.pause()\nx = x + 1"))456 let session = DebugSession(program: program, automation: program.automations[0])457 session.instance.breakpoints = [4]458 session.run()459 #expect(session.instance.pausedAtLine == 4)460 #expect(session.beat == 2)461 #expect(session.instance.variables == [VariableSnapshot(name: "x", value: .number(1))])462 session.stepOver()463 #expect(session.instance.pausedAtLine == 5)464 #expect(session.instance.variables.first?.value == .number(2))465 session.resume()466 #expect(session.isOver)467 #expect(session.result().finalVariables.first?.value == .number(3))468 }469470 @Test func consoleParsing() {471 if case let .command(name, arg) = ConsoleParser.parse("run \"Eight Bar Transition\"") { #expect(name == "run"); #expect(arg == "Eight Bar Transition") } else { Issue.record("not a command") }472 if case .command("stop", nil) = ConsoleParser.parse("stop") {} else { Issue.record("stop") }473 if case let .script(p) = ConsoleParser.parse("deck.B.volume = -8dB") { #expect(p.automations.count == 1) } else { Issue.record("assignment") }474 if case let .script(p) = ConsoleParser.parse("deck.A.bpm") {475 let r = Simulator.run(p)!476 #expect(r.prints() == ["128"])477 } else { Issue.record("expression") }478 if case let .script(p) = ConsoleParser.parse("fx.echo.enable()") { #expect(Simulator.run(p)!.actions.count == 1) } else { Issue.record("action") }479 if case let .script(p) = ConsoleParser.parse("min(3, 4) + 1") { #expect(Simulator.run(p)!.prints() == ["4"]) } else { Issue.record("call expr") }480 if case let .invalid(d) = ConsoleParser.parse("deck.Z.play()") { #expect(d.first?.code == "E-DECK") } else { Issue.record("invalid") }481 if case .empty = ConsoleParser.parse(" ") {} else { Issue.record("empty") }482 }483484 @Test func formatter() {485 let messy = "automation \"A\" {\n wait 4beats \n\n\n\nif true {\ndeck.A.play() // go {\n}\n }\n"486 #expect(ScriptFormatter.format(messy) == "automation \"A\" {\n wait 4beats\n\n if true {\n deck.A.play() // go {\n }\n}\n")487 #expect(ScriptFormatter.format(ScriptFormatter.format(messy)) == ScriptFormatter.format(messy))488 }489490 @Test func autocompleteAndDocs() {491 #expect(Autocomplete.completions(for: "deck.").map(\.label) == ["A", "B", "C", "D"])492 #expect(Autocomplete.completions(for: "deck.A.fil").map(\.label) == ["filter"])493 #expect(Autocomplete.completions(for: "fx.del").map(\.label) == ["delay"])494 #expect(Autocomplete.completions(for: "fx.delay.").map(\.label).contains("feedback"))495 #expect(Autocomplete.completions(for: "ov").map(\.label) == ["over"])496 #expect(Autocomplete.documentation(for: "deck.B.volume")?.contains("-60 dB") == true)497 #expect(Autocomplete.documentation(for: "fx.delay.time") != nil)498 #expect(Autocomplete.documentation(for: "deck.A.loop()")?.contains("length") == true)499 }500501 @Test func everySchemaEntryIsReachableFromSource() {502 // Each writable parameter accepts its default; each readable one can be read; each action can be called.503 var lines: [String] = []504 for d in ScriptSchema.deckParams { lines.append(d.writable ? "deck.A.\(d.key) = \(d.defaultValue)" : "print(deck.A.\(d.key))") }505 for d in ScriptSchema.mixerParams { lines.append(d.writable ? "mixer.\(d.key) = \(d.defaultValue)" : "print(mixer.\(d.key))") }506 for d in ScriptSchema.masterParams { lines.append(d.writable ? "master.\(d.key) = \(d.defaultValue)" : "print(master.\(d.key))") }507 for (alias, _) in ScriptSchema.mixerChannelAliases { lines.append("print(mixer.channel.B.\(alias))") }508 for k in EffectKind.allCases {509 for d in ScriptSchema.fxParams(k) { lines.append("fx.\(k.rawValue).\(d.key) = \(d.defaultValue)"); lines.append("deck.B.fx.\(k.rawValue).\(d.key) = \(d.defaultValue)") }510 for a in ScriptSchema.fxActions { lines.append("fx.\(k.rawValue).\(a.name)()") }511 }512 let sample: [ScriptType: String] = [.duration: "4beats", .number: "1", .bool: "true", .string: "\"Track\""]513 for a in ScriptSchema.deckActions where a.name != "eject" && a.name != "load" && a.name != "loadNext" && a.name != "loopOut" && a.name != "reloop" && a.name != "hotcue" {514 lines.append("deck.A.\(a.name)(\(a.params.map { sample[$0.type]! }.joined(separator: ", ")))")515 }516 for e in ScriptSchema.deckEvents { lines.append("on deck.A.\(e.name) { }") }517 // Split so the per-beat command limit is respected.518 for chunk in stride(from: 0, to: lines.count, by: 100).map({ Array(lines[$0 ..< min($0 + 100, lines.count)]) }) {519 let r = simulate(wrap(chunk.joined(separator: "\n") + "\nstop"))520 #expect(r.error == nil, "\(String(describing: r.error))")521 }522 }523}524