Repository Public
1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXScript/Compiler.swift3// Description: ORIX Script semantic analysis and lowering: name resolution, type and unit checking, range and4// capability validation, loop-bound and recursion checks, constant folding. Output: a Program or diagnostics.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import ORIXDSP1011/// What the host can run. Scripts that need more are rejected before execution.12public struct Capabilities: Sendable, Equatable {13 public var deckCount: Int14 public var effects: Set<EffectKind>1516 public init(deckCount: Int = ScriptSchema.deckCount, effects: Set<EffectKind> = Set(EffectKind.allCases)) {17 self.deckCount = deckCount; self.effects = effects18 }19}2021/// Static resource limits enforced by the compiler; the run-time limits live in `RuntimeLimits`.22public enum CompileLimits {23 public static let maxLoopIterations = 1000024 public static let maxArrayLength = 25625 public static let maxSourceBytes = 256 * 102426 public static let maxStatements = 2000027 public static let minEveryPeriodBeats = 1.0 / 6428 public static let maxHandlers = 3229}3031public struct CompileResult: Sendable {32 public var program: Program?33 public var diagnostics: [Diagnostic]34 public var errors: [Diagnostic] { diagnostics.filter { $0.severity == .error } }35 public var warnings: [Diagnostic] { diagnostics.filter { $0.severity == .warning } }36 public var succeeded: Bool { program != nil }37}3839public enum ScriptCompiler {40 /// Compiles a script file. A program is returned only when there is no error.41 public static func compile(_ source: String, capabilities: Capabilities = .init()) -> CompileResult {42 if source.utf8.count > CompileLimits.maxSourceBytes {43 return CompileResult(program: nil, diagnostics: [Diagnostic(code: "E-LIMIT", "Script larger than \(CompileLimits.maxSourceBytes / 1024) KB.", at: SourceLocation(line: 1, column: 1))])44 }45 let (file, parseDiagnostics) = Parser.parse(source)46 var c = Compilation(capabilities: capabilities)47 c.diagnostics = parseDiagnostics48 let program = c.compile(file)49 if file.automations.isEmpty, c.diagnostics.allSatisfy({ $0.severity != .error }) {50 c.diagnostics.append(Diagnostic(code: "E-EMPTY", "The script defines no automation. Start with: automation \"Name\" { … }", at: SourceLocation(line: 1, column: 1)))51 }52 let ok = !c.diagnostics.contains { $0.severity == .error }53 return CompileResult(program: ok ? program : nil, diagnostics: c.diagnostics.sorted { ($0.location.line, $0.location.column) < ($1.location.line, $1.location.column) })54 }5556 /// Compiles console input: loose statements become one anonymous automation named "console".57 public static func compileConsole(_ source: String, capabilities: Capabilities = .init()) -> CompileResult {58 let (file, parseDiagnostics) = Parser.parse(source, console: true)59 var c = Compilation(capabilities: capabilities)60 c.diagnostics = parseDiagnostics61 var wrapped = file62 if !file.loose.isEmpty {63 wrapped.automations.append(AutomationDecl(name: "console", quantize: .none, body: file.loose, location: file.loose[0].location))64 wrapped.loose = []65 }66 let program = c.compile(wrapped)67 let ok = !c.diagnostics.contains { $0.severity == .error }68 return CompileResult(program: ok ? program : nil, diagnostics: c.diagnostics)69 }70}7172private struct VarInfo {73 var slot: Int74 var type: ScriptType75 var mutable: Bool76}7778private struct FnInfo {79 var index: Int80 var decl: FnDecl81}8283private enum BodyContext { case automation, procedure, pureFunction }8485struct Compilation {86 let capabilities: Capabilities87 var diagnostics: [Diagnostic] = []8889 private var constants: [String: Value] = [:]90 private var functions: [String: FnInfo] = [:]91 private var compiledFunctions: [PFunction] = []92 private var callGraph: [Int: Set<Int>] = [:]9394 // Per-body state.95 private var scopes: [[String: VarInfo]] = []96 private var slotNames: [String] = []97 private var context = BodyContext.automation98 private var currentFunction: Int?99 private var loopDepth = 0100 private var overDepth = 0101 private var handlerCount = 0102 private var statementCount = 0103 private var requirements = AutomationRequirements()104105 init(capabilities: Capabilities) { self.capabilities = capabilities }106107 private mutating func error(_ code: String, _ message: String, at loc: SourceLocation, length: Int = 1) {108 diagnostics.append(Diagnostic(.error, code: code, message, at: loc, length: length))109 }110111 private mutating func warn(_ code: String, _ message: String, at loc: SourceLocation, length: Int = 1) {112 diagnostics.append(Diagnostic(.warning, code: code, message, at: loc, length: length))113 }114115 // MARK: File116117 mutating func compile(_ file: ScriptFile) -> Program {118 // File-level constants must fold to a value.119 for stmt in file.constants {120 guard case let .declare(name, type, value, _) = stmt.kind else { continue }121 scopes = [[:]]; slotNames = []122 guard let (e, t) = expression(value) else { continue }123 guard let v = e.constant else { error("E-CONST", "A top-level 'let' must be a constant expression; read live values inside an automation.", at: stmt.location); continue }124 if let type, type != t { error("E-TYPE", "'\(name)' is declared as \(type) but its value is \(t).", at: stmt.location) }125 if constants[name] != nil { error("E-REDECLARED", "'\(name)' is already defined.", at: stmt.location) }126 constants[name] = v127 }128 // Declare every function first so they can call each other in any order.129 for (i, f) in file.functions.enumerated() {130 if functions[f.name] != nil || ScriptSchema.builtins.contains(where: { $0.name == f.name }) || ScriptSchema.keywords.contains(f.name) {131 error("E-REDECLARED", "A function or builtin named '\(f.name)' already exists.", at: f.location)132 }133 functions[f.name] = FnInfo(index: i, decl: f)134 compiledFunctions.append(PFunction(name: f.name, paramCount: f.params.count, slotNames: [], body: [], returnType: f.returnType))135 }136 for (i, f) in file.functions.enumerated() { compileFunction(i, f) }137 detectRecursion(file.functions)138139 var automations: [CompiledAutomation] = []140 var seen: Set<String> = []141 for a in file.automations {142 if !seen.insert(a.name).inserted { error("E-REDECLARED", "An automation named \"\(a.name)\" is already defined in this script.", at: a.location) }143 if a.name.isEmpty { error("E-SYNTAX", "The automation name cannot be empty.", at: a.location) }144 scopes = [[:]]; slotNames = []; context = .automation; currentFunction = nil; loopDepth = 0; overDepth = 0; handlerCount = 0145 requirements = AutomationRequirements()146 let body = block(a.body, newScope: false)147 requirements.lengthBeats = requirements.usesEvents ? nil : Self.extent(body, functions: compiledFunctions).map { max($0.cursor, $0.extent) }148 automations.append(CompiledAutomation(name: a.name, quantize: a.quantize, body: body, slotNames: slotNames, requirements: requirements, location: a.location))149 }150 if statementCount > CompileLimits.maxStatements {151 error("E-LIMIT", "The script has more than \(CompileLimits.maxStatements) statements.", at: SourceLocation(line: 1, column: 1))152 }153 return Program(automations: automations, functions: compiledFunctions, languageVersion: ORIXScriptLanguage.version)154 }155156 private mutating func compileFunction(_ index: Int, _ f: FnDecl) {157 scopes = [[:]]; slotNames = []; loopDepth = 0; overDepth = 0158 context = f.returnType == nil ? .procedure : .pureFunction159 currentFunction = index160 let savedRequirements = requirements161 for p in f.params {162 if scopes[0][p.name] != nil { error("E-REDECLARED", "Parameter '\(p.name)' appears twice.", at: p.location) }163 scopes[0][p.name] = VarInfo(slot: slotNames.count, type: p.type, mutable: false)164 slotNames.append(p.name)165 }166 let body = block(f.body, newScope: false)167 if f.returnType != nil, !Self.alwaysReturns(body) {168 error("E-RETURN", "Function '\(f.name)' must return a \(f.returnType!) on every path.", at: f.location)169 }170 compiledFunctions[index].slotNames = slotNames171 compiledFunctions[index].body = body172 requirements = savedRequirements173 currentFunction = nil174 }175176 private static func alwaysReturns(_ body: [PStmt]) -> Bool {177 guard let last = body.last else { return false }178 switch last.kind {179 case .returnValue: return true180 case let .ifElse(_, a, b): return !b.isEmpty && alwaysReturns(a) && alwaysReturns(b)181 default: return false182 }183 }184185 private mutating func detectRecursion(_ decls: [FnDecl]) {186 var state = [Int](repeating: 0, count: decls.count) // 0 new, 1 visiting, 2 done187 var reported: Set<Int> = []188 func visit(_ i: Int, _ c: inout Compilation) {189 state[i] = 1190 for j in c.callGraph[i, default: []].sorted() {191 if state[j] == 1 {192 if reported.insert(j).inserted {193 c.error("E-RECURSION", "Function '\(decls[j].name)' calls itself, directly or through other functions. Recursion is not allowed: automations must be bounded.", at: decls[j].location)194 }195 } else if state[j] == 0 { visit(j, &c) }196 }197 state[i] = 2198 }199 for i in decls.indices where state[i] == 0 { visit(i, &self) }200 }201202 // MARK: Scopes203204 private func lookup(_ name: String) -> VarInfo? {205 for scope in scopes.reversed() { if let v = scope[name] { return v } }206 return nil207 }208209 private mutating func declare(_ name: String, _ type: ScriptType, mutable: Bool, at loc: SourceLocation) -> Int {210 if scopes[scopes.count - 1][name] != nil { error("E-REDECLARED", "'\(name)' is already declared in this block.", at: loc) }211 if constants[name] != nil { warn("W-SHADOW", "'\(name)' hides the top-level constant of the same name.", at: loc) }212 if slotNames.count >= 512 { error("E-LIMIT", "More than 512 variables in one automation or function.", at: loc) }213 let slot = slotNames.count214 slotNames.append(name)215 scopes[scopes.count - 1][name] = VarInfo(slot: slot, type: type, mutable: mutable)216 return slot217 }218219 private mutating func block(_ stmts: [Stmt], newScope: Bool = true) -> [PStmt] {220 if newScope { scopes.append([:]) }221 defer { if newScope { scopes.removeLast() } }222 var out: [PStmt] = []223 var terminated = false224 for s in stmts {225 if terminated { warn("W-UNREACHABLE", "This statement is never reached.", at: s.location); terminated = false }226 statementCount += 1227 if let p = statement(s) { out.append(PStmt(kind: p, location: s.location)) }228 switch s.kind { case .stop, .breakLoop, .continueLoop, .returnValue: terminated = true; default: break }229 }230 return out231 }232233 // MARK: Statements234235 private mutating func requireTiming(_ what: String, at loc: SourceLocation) -> Bool {236 if context == .pureFunction { error("E-PURE", "\(what) is not allowed in a function that returns a value. Use a function without a return type for timed procedures.", at: loc); return false }237 if overDepth > 0 { error("E-OVER", "\(what) is not allowed inside an 'over' block; put it before or after the block.", at: loc); return false }238 return true239 }240241 private mutating func requireEffects(_ what: String, at loc: SourceLocation) -> Bool {242 if context == .pureFunction { error("E-PURE", "\(what) is not allowed in a function that returns a value: such functions only compute.", at: loc); return false }243 return true244 }245246 private mutating func statement(_ s: Stmt) -> PStmtKind? {247 let loc = s.location248 switch s.kind {249 case let .declare(name, declared, value, mutable):250 guard let (e, t) = expression(value) else { _ = declare(name, declared ?? .number, mutable: mutable, at: loc); return nil }251 if t == .void { error("E-TYPE", "This expression has no value.", at: value.location); return nil }252 if let declared, declared != t { error("E-TYPE", "'\(name)' is declared as \(declared) but its value is \(t).", at: value.location) }253 let slot = declare(name, t, mutable: mutable, at: loc)254 return .setLocal(slot, e)255256 case let .assign(path, value):257 if path.segments.count == 1, let v = lookup(path.segments[0]) {258 guard let (e, t) = expression(value) else { return nil }259 if !v.mutable { error("E-CONST", "'\(path.text)' was declared with 'let' and cannot change. Declare it with 'var'.", at: path.location, length: path.length); return nil }260 if t != v.type { error("E-TYPE", "Cannot assign \(t) to '\(path.text)' of type \(v.type).", at: value.location); return nil }261 return .setLocal(v.slot, e)262 }263 if path.segments.count == 1, constants[path.segments[0]] != nil {264 error("E-CONST", "'\(path.text)' is a top-level constant and cannot change.", at: path.location, length: path.length); return nil265 }266 if path.segments.count == 1, !["deck", "mixer", "fx", "master"].contains(path.segments[0]) {267 error("E-UNDECLARED", "'\(path.text)' is not declared. Declare it first: let \(path.text) = … (or 'var' if it changes).", at: path.location, length: path.length)268 _ = expression(value); return nil269 }270 guard requireEffects("Changing '\(path.text)'", at: loc) else { return nil }271 guard let target = resolveParam(path) else { _ = expression(value); return nil }272 guard target.def.writable else { error("E-READONLY", "'\(path.text)' is read-only.", at: path.location, length: path.length); return nil }273 guard let e = coerced(value, to: target.def, name: path.text) else { return nil }274 return .write(target, e)275276 case let .ramp(path, value):277 guard overDepth > 0 else {278 error("E-RAMP", "'->' ramps a parameter over time and is only valid inside an 'over' block, e.g. over 8bars { \(path.text) -> … }. Use '=' to set a value now.", at: loc); return nil279 }280 // Handled by the enclosing `over`.281 _ = value282 return nil283284 case let .call(path, args):285 return call(path, args, at: loc)286287 case let .wait(spec):288 guard requireTiming("'wait'", at: loc) else { return nil }289 switch spec {290 case .nextBeat: return .wait(.nextBeat)291 case .nextBar: return .wait(.nextBar)292 case let .until(a): return anchor(a).map { .wait(.until($0)) }293 case let .duration(e):294 guard let (d, t) = expression(e) else { return nil }295 guard t == .duration else { error("E-TYPE", "'wait' needs a duration such as 4beats, 2bars or 500ms, not \(t).", at: e.location); return nil }296 checkNonNegative(d, "A wait", at: e.location)297 return .wait(.duration(d))298 }299300 case let .at(a, body):301 guard requireTiming("'at'", at: loc) else { return nil }302 if context != .automation, case .bar = a { warn("W-AT", "'at bar' inside a function counts from the start of the automation, not from the call.", at: loc) }303 guard let pa = anchor(a) else { _ = block(body); return nil }304 let savedLoop = loopDepth; loopDepth = 0305 let b = block(body)306 loopDepth = savedLoop307 return .spawn(pa, b)308309 case let .over(duration, curveName, body):310 guard requireTiming("'over'", at: loc) else { return nil }311 var curve = RampCurve.linear312 if let curveName {313 if let c = RampCurve(rawValue: curveName) { curve = c }314 else { error("E-CURVE", "Unknown curve '\(curveName)'. Curves: \(ScriptSchema.rampCurves.joined(separator: ", ")).", at: loc) }315 }316 guard let (d, t) = expression(duration) else { return nil }317 guard t == .duration else { error("E-TYPE", "'over' needs a duration such as 8bars, not \(t).", at: duration.location); return nil }318 checkNonNegative(d, "An 'over' duration", at: duration.location, allowZero: false)319 var ramps: [PRamp] = []320 var immediates: [PStmt] = []321 overDepth += 1322 scopes.append([:])323 var seen: Set<String> = []324 for inner in body {325 statementCount += 1326 switch inner.kind {327 case let .ramp(path, value):328 guard let target = resolveParam(path) else { _ = expression(value); continue }329 guard target.def.writable else { error("E-READONLY", "'\(path.text)' is read-only.", at: path.location, length: path.length); continue }330 guard target.def.rampable else {331 error("E-RAMP", "'\(path.text)' (\(target.def.type)) cannot be ramped; set it with '='.", at: path.location, length: path.length); continue332 }333 guard let e = coerced(value, to: target.def, name: path.text) else { continue }334 if target.deck?.constant != nil || target.deck == nil, !seen.insert(path.text).inserted {335 warn("W-RAMP", "'\(path.text)' is ramped twice in the same block; the last ramp wins.", at: path.location, length: path.length)336 }337 ramps.append(PRamp(path: target, target: e, location: inner.location))338 case .assign, .call, .declare:339 if let p = statement(inner) { immediates.append(PStmt(kind: p, location: inner.location)) }340 default:341 error("E-OVER", "Only ramps ('->'), assignments and actions are allowed inside 'over'. Move this statement outside the block.", at: inner.location)342 }343 }344 scopes.removeLast()345 overDepth -= 1346 if ramps.isEmpty { warn("W-OVER", "This 'over' block ramps nothing; it only waits. Use 'wait' if that is intended.", at: loc) }347 return .over(d, curve, ramps, immediates)348349 case let .every(period, total, body):350 guard requireTiming("'every'", at: loc) else { return nil }351 guard let (pe, pt) = expression(period), let (te, tt) = expression(total) else { _ = block(body); return nil }352 guard pt == .duration, tt == .duration else { error("E-TYPE", "'every' needs two durations: every 1beat for 8beats { … }.", at: loc); return nil }353 if case let .duration(p)? = pe.constant, case let .duration(t)? = te.constant {354 if p.magnitude <= 0 { error("E-RANGE", "The 'every' period must be greater than zero.", at: period.location) }355 else if case let .beats(b) = p, b < CompileLimits.minEveryPeriodBeats { error("E-LIMIT", "The 'every' period cannot be shorter than 1/64 beat.", at: period.location) }356 else if case .beats = p, case .beats = t, t.magnitude / p.magnitude > Double(CompileLimits.maxLoopIterations) {357 error("E-LIMIT", "This 'every' loop would run more than \(CompileLimits.maxLoopIterations) times.", at: loc)358 }359 }360 loopDepth += 1361 let b = block(body)362 loopDepth -= 1363 return .every(pe, te, b)364365 case let .repeatLoop(count, body):366 guard let (ce, ct) = expression(count) else { _ = block(body); return nil }367 guard ct == .number else { error("E-TYPE", "'repeat' needs a whole number of iterations, not \(ct).", at: count.location); return nil }368 if case let .number(n)? = ce.constant { checkLoopCount(n, at: count.location) }369 loopDepth += 1370 let b = block(body)371 loopDepth -= 1372 return .repeatLoop(ce, b)373374 case let .forRange(name, from, to, inclusive, body):375 guard let (fe, ft) = expression(from), let (te, tt) = expression(to) else { _ = block(body); return nil }376 guard ft == .number, tt == .number else { error("E-TYPE", "Range bounds must be numbers.", at: from.location); return nil }377 if case let .number(a)? = fe.constant, case let .number(b)? = te.constant { checkLoopCount(b - a + (inclusive ? 1 : 0), at: from.location) }378 scopes.append([:])379 let slot = declare(name, .number, mutable: false, at: loc)380 loopDepth += 1381 let b = block(body)382 loopDepth -= 1383 scopes.removeLast()384 return .forRange(slot, fe, te, inclusive, b)385386 case let .forIn(name, arrayExpr, body):387 guard let (ae, at) = expression(arrayExpr) else { _ = block(body); return nil }388 guard case let .array(element) = at else { error("E-TYPE", "'for … in' needs an array or a range (1...8), not \(at).", at: arrayExpr.location); return nil }389 scopes.append([:])390 let slot = declare(name, element, mutable: false, at: loc)391 loopDepth += 1392 let b = block(body)393 loopDepth -= 1394 scopes.removeLast()395 return .forIn(slot, ae, b)396397 case let .whileLoop(cond, limit, body):398 guard let (ce, ct) = expression(cond), let (le, _) = expression(limit) else { _ = block(body); return nil }399 guard ct == .bool else { error("E-TYPE", "The 'while' condition must be true or false, not \(ct).", at: cond.location); return nil }400 guard case let .number(n)? = le.constant, n == n.rounded(), n >= 1, n <= Double(CompileLimits.maxLoopIterations) else {401 error("E-UNBOUNDED", "The 'while' limit must be a constant whole number from 1 to \(CompileLimits.maxLoopIterations).", at: limit.location); return nil402 }403 loopDepth += 1404 let b = block(body)405 loopDepth -= 1406 return .whileLoop(ce, Int(n), b)407408 case let .ifElse(cond, thenBody, elseBody):409 let c = expression(cond)410 if let c, c.1 != .bool { error("E-TYPE", "The condition must be true or false, not \(c.1). Compare it, e.g. deck.A.bpm > 120.", at: cond.location) }411 let a = block(thenBody)412 let b = elseBody.map { block($0) } ?? []413 guard let c, c.1 == .bool else { return nil }414 return .ifElse(c.0, a, b)415416 case let .on(spec, once, body):417 guard requireTiming("'on'", at: loc) else { return nil }418 if context != .automation { error("E-EVENT", "Event handlers can only be declared inside an automation.", at: loc); return nil }419 if loopDepth > 0 { error("E-EVENT", "Event handlers cannot be declared inside a loop.", at: loc); return nil }420 handlerCount += 1421 if handlerCount > CompileLimits.maxHandlers { error("E-LIMIT", "More than \(CompileLimits.maxHandlers) event handlers in one automation.", at: loc) }422 requirements.usesEvents = true423 guard let ev = event(spec) else { _ = block(body); return nil }424 let savedLoop = loopDepth; loopDepth = 0425 let b = block(body)426 loopDepth = savedLoop427 return .on(ev, once, b)428429 case let .returnValue(value):430 switch context {431 case .automation:432 error("E-RETURN", "'return' is only valid inside a function. Use 'stop' to end the automation.", at: loc); return nil433 case .procedure:434 if value != nil { error("E-RETURN", "This function has no return type, so it cannot return a value. Add '-> type' to its header.", at: loc); return nil }435 return .returnValue(nil)436 case .pureFunction:437 guard let value else { error("E-RETURN", "This function must return a value.", at: loc); return nil }438 guard let (e, t) = expression(value) else { return nil }439 let expected = currentFunction.flatMap { compiledFunctions[$0].returnType }440 if let expected, expected != t { error("E-TYPE", "The function returns \(expected) but this value is \(t).", at: value.location); return nil }441 return .returnValue(e)442 }443444 case .stop:445 if context == .pureFunction { error("E-PURE", "'stop' is not allowed in a function that returns a value.", at: loc); return nil }446 return .stop447 case .breakLoop:448 guard loopDepth > 0 else { error("E-LOOP", "'break' is only valid inside a loop.", at: loc); return nil }449 return .breakLoop450 case .continueLoop:451 guard loopDepth > 0 else { error("E-LOOP", "'continue' is only valid inside a loop.", at: loc); return nil }452 return .continueLoop453 }454 }455456 private mutating func checkLoopCount(_ n: Double, at loc: SourceLocation) {457 if n != n.rounded() { error("E-RANGE", "A loop count must be a whole number.", at: loc) }458 else if n < 0 { error("E-RANGE", "A loop count cannot be negative.", at: loc) }459 else if n > Double(CompileLimits.maxLoopIterations) { error("E-LIMIT", "A loop cannot run more than \(CompileLimits.maxLoopIterations) times.", at: loc) }460 }461462 private mutating func checkNonNegative(_ e: PExpr, _ what: String, at loc: SourceLocation, allowZero: Bool = true) {463 guard case let .duration(t)? = e.constant else { return }464 if case .seconds = t { requirements.usesAbsoluteTime = true }465 if t.magnitude < 0 || (!allowZero && t.magnitude == 0) { error("E-RANGE", "\(what) must be \(allowZero ? "zero or more" : "greater than zero").", at: loc) }466 if case let .beats(b) = t, b > 100_000 { error("E-LIMIT", "\(what) cannot exceed 100000 beats.", at: loc) }467 }468469 private mutating func anchor(_ a: Anchor) -> PAnchor? {470 switch a {471 case .nextBeat: return .nextBeat472 case .nextBar: return .nextBar473 case let .bar(e), let .beat(e):474 let isBar: Bool = { if case .bar = a { true } else { false } }()475 guard let (pe, t) = expression(e) else { return nil }476 guard t == .number else { error("E-TYPE", "'at \(isBar ? "bar" : "beat")' needs a number (bars and beats count from 1).", at: e.location); return nil }477 if case let .number(n)? = pe.constant {478 if n < 1 { error("E-RANGE", "\(isBar ? "Bars" : "Beats") count from 1: 'at \(isBar ? "bar" : "beat") 1' is the start of the automation.", at: e.location); return nil }479 return .offsetBeats(.const(.number((n - 1) * (isBar ? ORIXScriptLanguage.beatsPerBar : 1))))480 }481 let one = PExpr.binary("-", pe, .const(.number(1)), e.location)482 return .offsetBeats(isBar ? .binary("*", one, .const(.number(ORIXScriptLanguage.beatsPerBar)), e.location) : one)483 case let .offset(e):484 guard let (pe, t) = expression(e) else { return nil }485 guard t == .duration else { error("E-TYPE", "'at' needs a position: at bar 5, at beat 17, at 30s, at nextBar.", at: e.location); return nil }486 checkNonNegative(pe, "An 'at' position", at: e.location)487 return .offset(pe)488 }489 }490491 private mutating func event(_ spec: EventSpec) -> PEvent? {492 let segs = spec.path.segments493 let loc = spec.path.location494 if segs == ["beat"] { return .beat }495 if segs == ["bar"] { return .bar }496 if segs == ["trigger"] {497 guard let arg = spec.argument, let (e, t) = expression(arg), t == .number else {498 error("E-EVENT", "'on trigger' needs a trigger number: on trigger(1) { … }.", at: loc); return nil499 }500 if case let .number(n)? = e.constant, n < 1 || n > Double(ScriptSchema.triggerCount) || n != n.rounded() {501 error("E-RANGE", "Triggers are numbered 1 to \(ScriptSchema.triggerCount).", at: arg.location); return nil502 }503 return .trigger(e)504 }505 guard segs.count >= 2, let (deckExpr, rest) = deckPrefix(spec.path), rest.count == 1 else {506 error("E-EVENT", "Unknown event '\(spec.path.text)'. Events: beat, bar, trigger(n), deck.X.\(ScriptSchema.deckEvents.map(\.name).joined(separator: " / ")).", at: loc, length: spec.path.length)507 return nil508 }509 guard ScriptSchema.deckEvents.contains(where: { $0.name == rest[0] }) else {510 error("E-EVENT", "Unknown deck event '\(rest[0])'.\(suggestion(for: rest[0], in: ScriptSchema.deckEvents.map(\.name))) Events: \(ScriptSchema.deckEvents.map(\.name).joined(separator: ", ")).", at: loc, length: spec.path.length)511 return nil512 }513 return .deck(deckExpr, rest[0])514 }515516 // MARK: Paths517518 /// Splits `deck.A.rest…` or `<deck variable>.rest…` into the deck expression and the remaining segments.519 private mutating func deckPrefix(_ path: PathExpr) -> (PExpr, [String])? {520 let segs = path.segments521 if segs[0] == "deck" {522 guard segs.count >= 2 else { error("E-PATH", "Name the deck: deck.A, deck.B, deck.C or deck.D.", at: path.location, length: path.length); return nil }523 guard let idx = deckLetters.firstIndex(of: segs[1]) else {524 error("E-DECK", "Unknown deck '\(segs[1])'. Decks are A, B, C and D.", at: path.location, length: path.length); return nil525 }526 guard idx < capabilities.deckCount else {527 error("E-CAPABILITY", "Deck \(segs[1]) is not available: this setup has \(capabilities.deckCount) decks.", at: path.location, length: path.length); return nil528 }529 requirements.decks.insert(idx)530 return (.const(.deck(idx)), Array(segs.dropFirst(2)))531 }532 if let v = lookup(segs[0]), v.type == .deck { return (.local(v.slot), Array(segs.dropFirst())) }533 if case let .deck(d)? = constants[segs[0]] { requirements.decks.insert(d); return (.const(.deck(d)), Array(segs.dropFirst())) }534 return nil535 }536537 private mutating func effectKind(_ name: String, deck: PExpr?, at path: PathExpr) -> EffectKind? {538 guard let kind = EffectKind(rawValue: name) else {539 error("E-EFFECT", "Unknown effect '\(name)'.\(suggestion(for: name, in: EffectKind.allCases.map(\.rawValue))) Effects: \(EffectKind.allCases.map(\.rawValue).joined(separator: ", ")).", at: path.location, length: path.length)540 return nil541 }542 guard capabilities.effects.contains(kind) else {543 error("E-CAPABILITY", "The effect '\(name)' is not available in this setup.", at: path.location, length: path.length); return nil544 }545 let rack: String = { if case let .deck(d)? = deck?.constant { return "deck.\(deckLetters[d])." }; return deck == nil ? "" : "deck.*." }()546 requirements.effects.insert(rack + "fx." + name)547 return kind548 }549550 /// Resolves a parameter or property path. Reports an error and returns nil when it does not exist.551 private mutating func resolveParam(_ path: PathExpr) -> PPath? {552 let segs = path.segments553 func unknown(_ c: inout Compilation, _ key: String, _ candidates: [String], _ what: String) {554 c.error("E-PATH", "Unknown \(what) '\(key)' in '\(path.text)'.\(suggestion(for: key, in: candidates))", at: path.location, length: path.length)555 }556 switch segs[0] {557 case "mixer":558 if segs.count >= 2, segs[1] == "channel" {559 guard segs.count >= 4, let idx = deckLetters.firstIndex(of: segs[2]) else {560 error("E-PATH", "Write mixer.channel.A.<parameter> (channels are A, B, C, D).", at: path.location, length: path.length); return nil561 }562 guard idx < capabilities.deckCount else { error("E-CAPABILITY", "Channel \(segs[2]) is not available: this setup has \(capabilities.deckCount) decks.", at: path.location, length: path.length); return nil }563 let alias = segs.dropFirst(3).joined(separator: ".")564 guard let key = ScriptSchema.mixerChannelAliases[alias], let def = ScriptSchema.deckParam(key) else {565 unknown(&self, alias, Array(ScriptSchema.mixerChannelAliases.keys), "mixer channel parameter"); return nil566 }567 requirements.decks.insert(idx)568 return PPath(area: .deck, deck: .const(.deck(idx)), effect: nil, key: key, def: def)569 }570 let key = segs.dropFirst().joined(separator: ".")571 guard let def = ScriptSchema.mixerParam(key) else { unknown(&self, key, ScriptSchema.mixerParams.map(\.key), "mixer parameter"); return nil }572 return PPath(area: .mixer, deck: nil, effect: nil, key: key, def: def)573 case "master":574 let key = segs.dropFirst().joined(separator: ".")575 guard let def = ScriptSchema.masterParam(key) else { unknown(&self, key, ScriptSchema.masterParams.map(\.key), "master clock property"); return nil }576 return PPath(area: .master, deck: nil, effect: nil, key: key, def: def)577 case "fx":578 guard segs.count >= 3 else { error("E-PATH", "Write fx.<effect>.<parameter>, e.g. fx.delay.feedback.", at: path.location, length: path.length); return nil }579 guard let kind = effectKind(segs[1], deck: nil, at: path) else { return nil }580 let key = segs.dropFirst(2).joined(separator: ".")581 guard let def = ScriptSchema.fxParam(kind, key) else { unknown(&self, key, ScriptSchema.fxParams(kind).map(\.key), "\(kind.rawValue) parameter"); return nil }582 return PPath(area: .fx, deck: nil, effect: kind, key: key, def: def)583 default:584 guard let (deckExpr, rest) = deckPrefix(path) else {585 if segs[0] != "deck", !diagnostics.contains(where: { $0.location == path.location }) {586 error("E-UNDECLARED", "'\(segs[0])' is not declared.\(suggestion(for: segs[0], in: scopes.flatMap(\.keys) + Array(constants.keys) + ["deck", "mixer", "fx", "master"]))", at: path.location, length: path.length)587 }588 return nil589 }590 guard !rest.isEmpty else { error("E-PATH", "'\(path.text)' is a deck, not a parameter.", at: path.location, length: path.length); return nil }591 if rest[0] == "fx" {592 guard rest.count >= 3 else { error("E-PATH", "Write \(segs[0] == "deck" ? "deck.\(segs[1])" : segs[0]).fx.<effect>.<parameter>.", at: path.location, length: path.length); return nil }593 guard let kind = effectKind(rest[1], deck: deckExpr, at: path) else { return nil }594 let key = rest.dropFirst(2).joined(separator: ".")595 guard let def = ScriptSchema.fxParam(kind, key) else { unknown(&self, key, ScriptSchema.fxParams(kind).map(\.key), "\(kind.rawValue) parameter"); return nil }596 return PPath(area: .fx, deck: deckExpr, effect: kind, key: key, def: def)597 }598 let key = rest.joined(separator: ".")599 guard let def = ScriptSchema.deckParam(key) else {600 if ScriptSchema.deckAction(key) != nil { error("E-PATH", "'\(key)' is an action: call it with parentheses, \(path.text)().", at: path.location, length: path.length) }601 else { unknown(&self, key, ScriptSchema.deckParams.map(\.key), "deck parameter") }602 return nil603 }604 return PPath(area: .deck, deck: deckExpr, effect: nil, key: key, def: def)605 }606 }607608 /// Checks and converts a value assigned to a parameter.609 private mutating func coerced(_ value: Expr, to def: ParamDef, name: String) -> PExpr? {610 guard let (e0, t) = expression(value) else { return nil }611 var e = e0612 if def.type == .gain, t == .number {613 // A plain number or percentage is a linear amplitude.614 if case let .number(n)? = e.constant, n < 0 || n > 4 { error("E-RANGE", "A linear level must be between 0 and 4 (use dB for gains: -6dB).", at: value.location); return nil }615 e = fold(.builtin("linearToGain", [e], value.location))616 } else if t != def.type {617 var hint = ""618 switch def.type {619 case .gain: hint = " Write a gain such as -6dB."620 case .frequency: hint = " Write a frequency such as 800Hz or 12kHz."621 case .duration: hint = " Write a duration such as 1/4beat, 2beats or 250ms."622 case .bool: hint = " Write true or false."623 case .number where t == .gain || t == .frequency: hint = " This parameter is a plain number (\(def.rangeText))."624 default: break625 }626 error("E-TYPE", "'\(name)' expects \(def.type), not \(t).\(hint)", at: value.location)627 return nil628 }629 if let c = e.constant {630 switch c {631 case let .number(n), let .gain(n), let .frequency(n):632 if n < def.min - 1e-9 || n > def.max + 1e-9 {633 error("E-RANGE", "\(Value.description(of: c)) is outside the range of '\(name)' (\(def.rangeText)).", at: value.location); return nil634 }635 case let .duration(span):636 switch (span, def.durationUnit) {637 case let (.beats(b), .beats) where b < def.min - 1e-9 || b > def.max + 1e-9:638 error("E-RANGE", "\(Value.description(of: c)) is outside the range of '\(name)' (\(def.rangeText)).", at: value.location); return nil639 case let (.seconds(s), .milliseconds) where s * 1000 < def.min - 1e-9 || s * 1000 > def.max + 1e-9:640 error("E-RANGE", "\(Value.description(of: c)) is outside the range of '\(name)' (\(def.rangeText)).", at: value.location); return nil641 case (.beats, .milliseconds):642 break // converted with the tempo at run time, clamped there643 default: break644 }645 case let .string(s):646 if !def.allowed.isEmpty, !def.allowed.contains(s) {647 error("E-RANGE", "'\(name)' accepts \(def.rangeText), not \"\(s)\".", at: value.location); return nil648 }649 default: break650 }651 }652 return e653 }654655 // MARK: Calls656657 private mutating func call(_ path: PathExpr, _ args: [Expr], at loc: SourceLocation) -> PStmtKind? {658 let segs = path.segments659 if segs.count == 1 {660 let name = segs[0]661 if name == "print" {662 var out: [PExpr] = []663 for a in args { if let (e, t) = expression(a) { if t == .void { error("E-TYPE", "This expression has no value.", at: a.location) } else { out.append(e) } } }664 if context == .pureFunction { error("E-PURE", "print() is not allowed in a function that returns a value.", at: loc); return nil }665 return .print(out)666 }667 if let info = functions[name] {668 guard let lowered = arguments(args, for: info.decl, at: loc) else { return nil }669 if let cur = currentFunction { callGraph[cur, default: []].insert(info.index) }670 if info.decl.returnType != nil {671 warn("W-UNUSED", "The result of '\(name)' is not used.", at: loc)672 return .setLocal(scratchSlot(), .callFunction(info.index, lowered, loc))673 }674 if context == .pureFunction { error("E-PURE", "'\(name)' is a procedure and cannot be called from a function that returns a value.", at: loc); return nil }675 if overDepth > 0 { error("E-OVER", "Procedures cannot be called inside an 'over' block.", at: loc); return nil }676 return .callProcedure(info.index, lowered)677 }678 if ScriptSchema.builtins.contains(where: { $0.name == name }) {679 guard let (e, _) = expression(.call(path, args)) else { return nil }680 warn("W-UNUSED", "The result of '\(name)' is not used.", at: loc)681 return .setLocal(scratchSlot(), e)682 }683 error("E-UNDECLARED", "Unknown function '\(name)'.\(suggestion(for: name, in: Array(functions.keys) + ScriptSchema.builtins.map(\.name)))", at: loc, length: path.length)684 for a in args { _ = expression(a) }685 return nil686 }687 guard requireEffects("Calling '\(path.text)'", at: loc) else { return nil }688 let actionName = segs[segs.count - 1]689 let prefix = PathExpr(segments: Array(segs.dropLast()), location: path.location, length: path.length)690 var action: PAction?691 var def: ActionDef?692 if prefix.segments[0] == "fx" {693 guard prefix.segments.count == 2 else { error("E-PATH", "Write fx.<effect>.enable(), fx.<effect>.disable() or fx.<effect>.toggle().", at: loc, length: path.length); return nil }694 guard let kind = effectKind(prefix.segments[1], deck: nil, at: path) else { return nil }695 def = ScriptSchema.fxAction(actionName)696 if def == nil { error("E-PATH", "Unknown effect action '\(actionName)'.\(suggestion(for: actionName, in: ScriptSchema.fxActions.map(\.name)))", at: loc, length: path.length); return nil }697 action = PAction(area: .fx, deck: nil, effect: kind, name: actionName)698 } else if prefix.segments[0] == "mixer" || prefix.segments[0] == "master" {699 error("E-PATH", "'\(prefix.segments[0])' has no actions; set its parameters with '='.", at: loc, length: path.length); return nil700 } else {701 guard let (deckExpr, rest) = deckPrefix(prefix) else {702 if prefix.segments[0] != "deck", !diagnostics.contains(where: { $0.location == path.location }) {703 error("E-UNDECLARED", "'\(prefix.segments[0])' is not declared.", at: loc, length: path.length)704 }705 for a in args { _ = expression(a) }706 return nil707 }708 if rest.first == "fx" {709 guard rest.count == 2 else { error("E-PATH", "Write deck.X.fx.<effect>.enable().", at: loc, length: path.length); return nil }710 guard let kind = effectKind(rest[1], deck: deckExpr, at: path) else { return nil }711 def = ScriptSchema.fxAction(actionName)712 if def == nil { error("E-PATH", "Unknown effect action '\(actionName)'.\(suggestion(for: actionName, in: ScriptSchema.fxActions.map(\.name)))", at: loc, length: path.length); return nil }713 action = PAction(area: .fx, deck: deckExpr, effect: kind, name: actionName)714 } else {715 guard rest.isEmpty else { error("E-PATH", "'\(path.text)' is not an action.", at: loc, length: path.length); return nil }716 def = ScriptSchema.deckAction(actionName)717 if def == nil {718 let isParam = ScriptSchema.deckParam(actionName) != nil719 error("E-PATH", isParam ? "'\(actionName)' is a parameter, not an action: write \(path.text) = value." : "Unknown deck action '\(actionName)'.\(suggestion(for: actionName, in: ScriptSchema.deckActions.map(\.name)))", at: loc, length: path.length)720 return nil721 }722 action = PAction(area: .deck, deck: deckExpr, effect: nil, name: actionName)723 }724 }725 guard let action, let def else { return nil }726 let required = def.params.filter { !$0.optional }.count727 guard args.count >= required, args.count <= def.params.count else {728 error("E-ARGS", "\(def.signature) takes \(required == def.params.count ? "\(required)" : "\(required) to \(def.params.count)") argument\(def.params.count == 1 ? "" : "s"), not \(args.count).", at: loc, length: path.length)729 return nil730 }731 var lowered: [PExpr] = []732 for (a, pdef) in zip(args, def.params) {733 guard let (e, t) = expression(a) else { return nil }734 guard t == pdef.type else { error("E-TYPE", "Argument '\(pdef.name)' of \(def.name)() expects \(pdef.type), not \(t).", at: a.location); return nil }735 if ["hotcue", "setHotcue", "clearHotcue"].contains(def.name), case let .number(n)? = e.constant, n < 1 || n > Double(ScriptSchema.hotCueCount) || n != n.rounded() {736 error("E-RANGE", "Hot cues are numbered 1 to \(ScriptSchema.hotCueCount).", at: a.location); return nil737 }738 if def.name == "loop", case let .duration(.beats(b))? = e.constant, b < 1.0 / 64 || b > 256 {739 error("E-RANGE", "A loop length must be between 1/64 beat and 256 beats.", at: a.location); return nil740 }741 lowered.append(e)742 }743 return .action(action, lowered)744 }745746 private mutating func scratchSlot() -> Int {747 if let i = slotNames.firstIndex(of: "$discard") { return i }748 slotNames.append("$discard")749 return slotNames.count - 1750 }751752 private mutating func arguments(_ args: [Expr], for decl: FnDecl, at loc: SourceLocation) -> [PExpr]? {753 guard args.count == decl.params.count else {754 error("E-ARGS", "'\(decl.name)' takes \(decl.params.count) argument\(decl.params.count == 1 ? "" : "s"), not \(args.count).", at: loc); return nil755 }756 var out: [PExpr] = []757 for (a, p) in zip(args, decl.params) {758 guard let (e, t) = expression(a) else { return nil }759 guard t == p.type else { error("E-TYPE", "Argument '\(p.name)' of '\(decl.name)' expects \(p.type), not \(t).", at: a.location); return nil }760 out.append(e)761 }762 return out763 }764765 // MARK: Expressions766767 private mutating func fold(_ e: PExpr) -> PExpr {768 switch e {769 case let .unary(op, a, loc):770 if let v = a.constant, let r = try? Evaluator.unary(op, v, at: loc) { return .const(r) }771 case let .binary(op, a, b, loc):772 // Mixed beat/second arithmetic depends on the tempo and is left for run time.773 if let x = a.constant, let y = b.constant {774 if case let (.duration(dx), .duration(dy)) = (x, y) {775 let sameKind: Bool = { switch (dx, dy) { case (.beats, .beats), (.seconds, .seconds): true; default: false } }()776 if !sameKind { return e }777 }778 do { return .const(try Evaluator.binary(op, x, y, bpm: 120, at: loc)) }779 catch let err as ScriptRuntimeError { error(err.code, err.message, at: loc) } catch {}780 }781 case let .builtin(name, args, loc):782 if !["random", "toBeats", "toSeconds"].contains(name), args.allSatisfy({ $0.constant != nil }), let r = try? Evaluator.builtin(name, args.compactMap(\.constant), bpm: 120, at: loc) { return .const(r) }783 case let .array(items):784 if items.allSatisfy({ $0.constant != nil }) { return .const(.array(items.compactMap(\.constant))) }785 default: break786 }787 return e788 }789790 /// Type checks an expression. Returns nil after reporting an error.791 private mutating func expression(_ e: Expr) -> (PExpr, ScriptType)? {792 switch e {793 case let .literal(v, _): return (.const(v), v.type)794795 case let .path(path):796 let segs = path.segments797 if segs.count == 1 {798 if let v = lookup(segs[0]) { return (.local(v.slot), v.type) }799 if let c = constants[segs[0]] { return (.const(c), c.type) }800 if functions[segs[0]] != nil || ScriptSchema.builtins.contains(where: { $0.name == segs[0] }) {801 error("E-SYNTAX", "'\(segs[0])' is a function: call it with parentheses.", at: path.location, length: path.length); return nil802 }803 }804 if segs.count == 2, segs[0] == "deck" {805 guard let (d, _) = deckPrefix(path) else { return nil }806 return (d, .deck)807 }808 guard let p = resolveParam(path) else { return nil }809 if context == .pureFunction { error("E-PURE", "A function that returns a value cannot read live values such as '\(path.text)'; pass them as arguments.", at: path.location, length: path.length); return nil }810 return (.read(p, path.location), p.def.type)811812 case let .call(path, args):813 guard path.segments.count == 1 else {814 error("E-TYPE", "'\(path.text)()' is an action and has no value; it cannot be used in an expression.", at: path.location, length: path.length); return nil815 }816 let name = path.segments[0]817 if let info = functions[name] {818 guard let ret = info.decl.returnType else { error("E-TYPE", "'\(name)' does not return a value (add '-> type' to its declaration).", at: path.location, length: path.length); return nil }819 guard let lowered = arguments(args, for: info.decl, at: path.location) else { return nil }820 if let cur = currentFunction { callGraph[cur, default: []].insert(info.index) }821 return (.callFunction(info.index, lowered, path.location), ret)822 }823 return builtinCall(name, args, at: path)824825 case let .unary(op, operand, loc):826 guard let (o, t) = expression(operand) else { return nil }827 let ok = op == "!" ? t == .bool : [.number, .gain, .frequency, .duration].contains(t)828 guard ok else { error("E-TYPE", "Operator '\(op == "!" ? "not" : op)' cannot be applied to \(t).", at: loc); return nil }829 return (fold(.unary(op, o, loc)), t)830831 case let .binary(op, lhs, rhs, loc):832 let l = expression(lhs), r = expression(rhs)833 guard let (a, ta) = l, let (b, tb) = r else { return nil }834 guard let t = Evaluator.binaryType(op, ta, tb) else {835 var hint = ""836 if Set([ta, tb]) == [.gain, .number], ["+", "-"].contains(op) { hint = " Add the unit: 3dB." }837 if Set([ta, tb]) == [.duration, .number], ["+", "-", "<", ">", "<=", ">=", "=="].contains(op) { hint = " Add the unit: 4beats." }838 if Set([ta, tb]) == [.frequency, .number], ["+", "-", "<", ">", "<=", ">=", "=="].contains(op) { hint = " Add the unit: 200Hz." }839 error("E-TYPE", "Operator '\(op)' cannot combine \(ta) and \(tb).\(hint)", at: loc); return nil840 }841 return (fold(.binary(op, a, b, loc)), t)842843 case let .array(items, loc):844 guard !items.isEmpty else { error("E-TYPE", "An empty array has no element type; arrays need at least one element.", at: loc); return nil }845 guard items.count <= CompileLimits.maxArrayLength else { error("E-LIMIT", "Arrays hold at most \(CompileLimits.maxArrayLength) elements.", at: loc); return nil }846 var lowered: [PExpr] = []; var elementType: ScriptType?847 for item in items {848 guard let (pe, t) = expression(item) else { return nil }849 if let elementType, elementType != t { error("E-TYPE", "All elements of an array must have the same type (\(elementType) and \(t) found).", at: item.location); return nil }850 if case .array = t { error("E-TYPE", "Arrays cannot contain arrays.", at: item.location); return nil }851 elementType = t; lowered.append(pe)852 }853 return (fold(.array(lowered)), .array(elementType!))854855 case let .index(base, idx, loc):856 guard let (b, tb) = expression(base), let (i, ti) = expression(idx) else { return nil }857 guard case let .array(element) = tb else { error("E-TYPE", "Only arrays can be indexed, not \(tb).", at: loc); return nil }858 guard ti == .number else { error("E-TYPE", "An array index must be a number (the first element is 0).", at: loc); return nil }859 if case let .array(items)? = b.constant, case let .number(n)? = i.constant {860 guard n == n.rounded(), n >= 0, Int(n) < items.count else { error("E-RANGE", "Index \(formatNumber(n)) is outside the array (0 to \(items.count - 1)).", at: loc); return nil }861 return (.const(items[Int(n)]), element)862 }863 return (.index(b, i, loc), element)864 }865 }866867 private mutating func builtinCall(_ name: String, _ args: [Expr], at path: PathExpr) -> (PExpr, ScriptType)? {868 let loc = path.location869 guard ScriptSchema.builtins.contains(where: { $0.name == name }), name != "print" else {870 if name == "print" { error("E-TYPE", "print() has no value.", at: loc) }871 else { error("E-UNDECLARED", "Unknown function '\(name)'.\(suggestion(for: name, in: Array(functions.keys) + ScriptSchema.builtins.map(\.name)))", at: loc, length: path.length) }872 for a in args { _ = expression(a) }873 return nil874 }875 var lowered: [PExpr] = []; var types: [ScriptType] = []876 for a in args { guard let (e, t) = expression(a) else { return nil }; lowered.append(e); types.append(t) }877 func bad(_ c: inout Compilation, _ expected: String) -> (PExpr, ScriptType)? {878 c.error("E-ARGS", "\(name)() expects \(expected). Signature: \(ScriptSchema.builtins.first { $0.name == name }!.signature)", at: loc, length: path.length); return nil879 }880 let ordered: [ScriptType] = [.number, .gain, .frequency, .duration]881 var result: ScriptType882 switch name {883 case "min", "max":884 guard types.count == 2, types[0] == types[1], ordered.contains(types[0]) else { return bad(&self, "two values of the same numeric type") }885 result = types[0]886 case "clamp":887 guard types.count == 3, types[0] == types[1], types[1] == types[2], ordered.contains(types[0]) else { return bad(&self, "three values of the same numeric type") }888 result = types[0]889 case "abs", "round", "floor", "ceil":890 guard types == [.number] else { return bad(&self, "one number") }891 result = .number892 case "lerp":893 guard types.count == 3, types[0] == types[1], ordered.contains(types[0]), types[2] == .number else { return bad(&self, "two values of the same numeric type and a number") }894 result = types[0]895 case "random":896 guard types.isEmpty else { return bad(&self, "no argument") }897 if context == .pureFunction { error("E-PURE", "random() is not allowed in a function that returns a value.", at: loc); return nil }898 result = .number899 case "len":900 guard types.count == 1, { if case .array = types[0] { true } else { types[0] == .string } }() else { return bad(&self, "an array or a string") }901 result = .number902 case "db": guard types == [.number] else { return bad(&self, "one number") }; result = .gain903 case "hz": guard types == [.number] else { return bad(&self, "one number") }; result = .frequency904 case "beats", "bars", "seconds": guard types == [.number] else { return bad(&self, "one number") }; result = .duration905 case "toBeats", "toSeconds": guard types == [.duration] else { return bad(&self, "one duration") }; result = .number906 case "toNumber": guard types.count == 1, [.gain, .frequency].contains(types[0]) else { return bad(&self, "a gain or a frequency") }; result = .number907 default: return bad(&self, "different arguments")908 }909 return (fold(.builtin(name, lowered, loc)), result)910 }911912 // MARK: Static duration913914 /// Cursor advance and furthest scheduled point of a body, in beats, when every duration is a constant number of beats.915 static func extent(_ body: [PStmt], functions: [PFunction], depth: Int = 0) -> (cursor: Double, extent: Double)? {916 if depth > 32 { return nil }917 func beats(_ e: PExpr) -> Double? { if case let .duration(.beats(b))? = e.constant { b } else { nil } }918 var cursor = 0.0, far = 0.0919 for s in body {920 switch s.kind {921 case let .wait(w):922 guard case let .duration(e) = w, let b = beats(e) else { return nil }923 cursor += b924 case let .over(e, _, _, _):925 guard let b = beats(e) else { return nil }926 cursor += b927 case let .every(_, total, inner):928 guard let b = beats(total), extent(inner, functions: functions, depth: depth + 1) != nil else { return nil }929 cursor += b930 case let .repeatLoop(n, inner):931 guard case let .number(k)? = n.constant, let e = extent(inner, functions: functions, depth: depth + 1) else { return nil }932 far = max(far, cursor + max(0, k - 1) * e.cursor + e.extent)933 cursor += k * e.cursor934 case let .forRange(_, a, b, inclusive, inner):935 guard let e = extent(inner, functions: functions, depth: depth + 1) else { return nil }936 if e.cursor == 0, e.extent == 0 { continue }937 guard case let .number(x)? = a.constant, case let .number(y)? = b.constant else { return nil }938 let k = max(0, y - x + (inclusive ? 1 : 0))939 far = max(far, cursor + max(0, k - 1) * e.cursor + e.extent)940 cursor += k * e.cursor941 case let .forIn(_, _, inner), let .whileLoop(_, _, inner):942 guard let e = extent(inner, functions: functions, depth: depth + 1) else { return nil }943 if e.cursor != 0 || e.extent != 0 { return nil }944 case let .ifElse(_, a, b):945 guard let ea = extent(a, functions: functions, depth: depth + 1), let eb = extent(b, functions: functions, depth: depth + 1) else { return nil }946 if ea.cursor != eb.cursor { return nil }947 far = max(far, cursor + max(ea.extent, eb.extent)); cursor += ea.cursor948 case let .spawn(anchor, inner):949 guard case let .offsetBeats(e) = anchor, case let .number(off)? = e.constant, let ei = extent(inner, functions: functions, depth: depth + 1) else {950 if case let .offset(e) = anchor, let off = beats(e), let ei = extent(inner, functions: functions, depth: depth + 1) { far = max(far, off + max(ei.cursor, ei.extent)); continue }951 return nil952 }953 far = max(far, off + max(ei.cursor, ei.extent))954 case let .callProcedure(i, _):955 guard let e = extent(functions[i].body, functions: functions, depth: depth + 1) else { return nil }956 far = max(far, cursor + e.extent); cursor += e.cursor957 case .on: return nil958 default: break959 }960 far = max(far, cursor)961 }962 return (cursor, far)963 }964}965966extension Value {967 static func description(of v: Value) -> String { v.display() }968}969