SPB Git

Repository Public

Values.swift 7.2 KB 190 lines swift

1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXScript/Values.swift3// Description: ORIX Script value model: static types, runtime values, units and their textual form.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89/// Version of the ORIX Script language implemented by this module. Stored in saved scripts and projects.10public enum ORIXScriptLanguage {11    public static let version = "1.0"12    public static let fileExtension = "orixdj"13    public static let beatsPerBar = 4.014}1516/// Static type of an expression.17public indirect enum ScriptType: Hashable, Sendable, CustomStringConvertible {18    case number, duration, gain, frequency, bool, string, deck, void19    case array(ScriptType)2021    public var description: String {22        switch self {23        case .number: "number"24        case .duration: "duration"25        case .gain: "gain"26        case .frequency: "frequency"27        case .bool: "bool"28        case .string: "string"29        case .deck: "deck"30        case .void: "void"31        case let .array(e): "[\(e)]"32        }33    }3435    public static func named(_ name: String) -> ScriptType? {36        switch name {37        case "number": .number38        case "duration": .duration39        case "gain": .gain40        case "frequency": .frequency41        case "bool": .bool42        case "string": .string43        case "deck": .deck44        default: nil45        }46    }47}4849/// A length of time: musical (beats, follows the tempo) or absolute (seconds).50public enum TimeSpan: Equatable, Sendable, Codable {51    case beats(Double)52    case seconds(Double)5354    public func beats(atBPM bpm: Double) -> Double {55        switch self {56        case let .beats(b): b57        case let .seconds(s): s * bpm / 6058        }59    }6061    public func seconds(atBPM bpm: Double) -> Double {62        switch self {63        case let .beats(b): b * 60 / max(bpm, 1)64        case let .seconds(s): s65        }66    }6768    public var magnitude: Double {69        switch self { case let .beats(b): b; case let .seconds(s): s }70    }71}7273/// Runtime value.74public enum Value: Equatable, Sendable {75    case number(Double)76    case duration(TimeSpan)77    /// Decibels. -60 dB and below is silence.78    case gain(Double)79    /// Hertz.80    case frequency(Double)81    case bool(Bool)82    case string(String)83    /// Zero-based deck index (0 = A).84    case deck(Int)85    case array([Value])86    case void8788    public var type: ScriptType {89        switch self {90        case .number: .number91        case .duration: .duration92        case .gain: .gain93        case .frequency: .frequency94        case .bool: .bool95        case .string: .string96        case .deck: .deck97        case let .array(a): .array(a.first?.type ?? .number)98        case .void: .void99        }100    }101102    /// Scalar magnitude in the canonical unit (dB, Hz, beats or seconds, 0/1), when the value has one.103    public var scalar: Double? {104        switch self {105        case let .number(n): n106        case let .gain(d): d107        case let .frequency(f): f108        case let .duration(t): t.magnitude109        case let .bool(b): b ? 1 : 0110        default: nil111        }112    }113114    public var boolValue: Bool? { if case let .bool(b) = self { b } else { nil } }115    public var numberValue: Double? { if case let .number(n) = self { n } else { nil } }116    public var stringValue: String? { if case let .string(s) = self { s } else { nil } }117    public var deckIndex: Int? { if case let .deck(d) = self { d } else { nil } }118}119120public let deckLetters = ["A", "B", "C", "D"]121122func formatNumber(_ x: Double, maxDecimals: Int = 3) -> String {123    if x.isNaN { return "nan" }124    if x.isInfinite { return x < 0 ? "-inf" : "inf" }125    if x == x.rounded(), abs(x) < 1e12 { return String(Int64(x)) }126    var s = String(format: "%.\(maxDecimals)f", locale: Locale(identifier: "en_US_POSIX"), x)127    while s.hasSuffix("0") { s.removeLast() }128    if s.hasSuffix(".") { s.removeLast() }129    return s130}131132extension Value: CustomStringConvertible {133    /// Text form that is also valid ORIX Script source for the value.134    public var description: String {135        switch self {136        case let .number(n): return formatNumber(n)137        case let .duration(.beats(b)): return formatNumber(b) + (b == 1 ? "beat" : "beats")138        case let .duration(.seconds(s)): return abs(s) < 1 && s != 0 ? formatNumber(s * 1000) + "ms" : formatNumber(s) + "s"139        case let .gain(d): return formatNumber(d, maxDecimals: 2) + "dB"140        case let .frequency(f): return f >= 1000 ? formatNumber(f / 1000) + "kHz" : formatNumber(f) + "Hz"141        case let .bool(b): return b ? "true" : "false"142        case let .string(s): return "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""143        case let .deck(d): return "deck." + (deckLetters.indices.contains(d) ? deckLetters[d] : "?")144        case let .array(a): return "[" + a.map(\.description).joined(separator: ", ") + "]"145        case .void: return "void"146        }147    }148149    /// Human form used by the console and the inspector ("-6 dB", "128 BPM").150    public func display(unit: String = "") -> String {151        switch self {152        case let .number(n): return unit.isEmpty ? formatNumber(n) : (unit == "%" ? formatNumber(n * 100, maxDecimals: 1) + " %" : formatNumber(n, maxDecimals: unit == "BPM" ? 2 : 3) + " " + unit)153        case let .duration(.beats(b)): return formatNumber(b) + (b == 1 ? " beat" : " beats")154        case let .duration(.seconds(s)): return formatNumber(s, maxDecimals: 2) + " s"155        case let .gain(d): return d <= -60 ? "-inf dB" : formatNumber(d, maxDecimals: 1) + " dB"156        case let .frequency(f): return f >= 1000 ? formatNumber(f / 1000, maxDecimals: 2) + " kHz" : formatNumber(f, maxDecimals: 1) + " Hz"157        case let .string(s): return s158        case let .deck(d): return "Deck " + (deckLetters.indices.contains(d) ? deckLetters[d] : "?")159        case let .array(a): return "[" + a.map { $0.display() }.joined(separator: ", ") + "]"160        default: return description161        }162    }163}164165/// Position in source text (1-based line and column).166public struct SourceLocation: Equatable, Sendable, Hashable, Codable {167    public var line: Int168    public var column: Int169    public init(line: Int, column: Int) { self.line = line; self.column = column }170}171172public enum DiagnosticSeverity: String, Sendable, Codable { case error, warning, note }173174/// A compiler or runtime message tied to a source position.175public struct Diagnostic: Equatable, Sendable, Error, CustomStringConvertible, Codable {176    public var severity: DiagnosticSeverity177    public var message: String178    public var location: SourceLocation179    /// Length in characters of the offending token (for editor underlines); 1 when unknown.180    public var length: Int181    /// Stable identifier ("E-TYPE", "E-RANGE"…) documented in the Error Handling chapter.182    public var code: String183184    public init(_ severity: DiagnosticSeverity = .error, code: String, _ message: String, at location: SourceLocation, length: Int = 1) {185        self.severity = severity; self.code = code; self.message = message; self.location = location; self.length = max(1, length)186    }187188    public var description: String { "\(location.line):\(location.column): \(severity.rawValue): \(message) [\(code)]" }189}190
Files main
Menu

Theme