Repository Public
1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXScript/Tools.swift3// Description: Editor and console support for ORIX Script: source formatter, console line parser, autocomplete.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import ORIXDSP910public enum ScriptFormatter {11 /// Re-indents by brace depth (4 spaces), trims trailing spaces, collapses runs of blank lines. Comments and text are kept as written.12 public static func format(_ source: String) -> String {13 var lexer = Lexer(source)14 let tokens = lexer.tokenize()15 // Brace depth changes per line, ignoring braces inside strings and comments (the lexer already did).16 var opens: [Int: Int] = [:], closes: [Int: Int] = [:], leadingCloses: [Int: Int] = [:]17 var firstTokenOnLine: [Int: Bool] = [:]18 for t in tokens {19 let line = t.location.line20 switch t.kind {21 case .symbol("{"): opens[line, default: 0] += 1; firstTokenOnLine[line] = false22 case .symbol("}"):23 closes[line, default: 0] += 124 if firstTokenOnLine[line] ?? true { leadingCloses[line, default: 0] += 1 } else { firstTokenOnLine[line] = false }25 case .newline, .eof: break26 default: firstTokenOnLine[line] = false27 }28 }29 var depth = 030 var out: [String] = []31 var blankRun = 032 for (i, raw) in source.components(separatedBy: "\n").enumerated() {33 let line = i + 134 let text = raw.trimmingCharacters(in: .whitespaces)35 if text.isEmpty {36 blankRun += 137 if blankRun <= 1, !out.isEmpty { out.append("") }38 continue39 }40 blankRun = 041 let indent = max(0, depth - (leadingCloses[line] ?? 0))42 out.append(String(repeating: " ", count: indent) + text)43 depth = max(0, depth + (opens[line] ?? 0) - (closes[line] ?? 0))44 }45 while out.last == "" { out.removeLast() }46 return out.joined(separator: "\n") + "\n"47 }48}4950/// One console line, classified.51public enum ConsoleInput: Sendable {52 /// A console command such as `run "Name"`, `stop`, `list`, `help`.53 case command(name: String, argument: String?)54 /// ORIX Script statements compiled into the anonymous "console" automation.55 case script(Program)56 case invalid([Diagnostic])57 case empty58}5960public enum ConsoleParser {61 public static let commands: [(name: String, usage: String, doc: String)] = [62 ("help", "help [topic]", "Lists the console commands, or looks a path up in the reference (help deck.A.volume)."),63 ("list", "list", "Lists the saved automations."),64 ("run", "run \"Name\"", "Starts a saved automation."),65 ("stop", "stop [\"Name\" | all]", "Stops one running automation, or all of them."),66 ("pause", "pause [\"Name\"]", "Freezes running automations."),67 ("resume", "resume [\"Name\"]", "Resumes paused automations."),68 ("status", "status", "Shows running automations, pending events and the master clock."),69 ("decks", "decks", "Shows the state of every deck."),70 ("fx", "fx", "Shows the effects in every rack."),71 ("trigger", "trigger <n>", "Fires automation trigger n."),72 ("panic", "panic", "Emergency stop: stops every automation and bypasses every effect."),73 ("clear", "clear", "Clears the console."),74 ("version", "version", "Shows the ORIX Script version."),75 ]7677 public static func parse(_ line: String, capabilities: Capabilities = .init()) -> ConsoleInput {78 let text = line.trimmingCharacters(in: .whitespacesAndNewlines)79 if text.isEmpty { return .empty }80 let word = text.prefix { $0.isLetter }.lowercased()81 let rest = text.dropFirst(word.count).trimmingCharacters(in: .whitespaces)82 if commands.contains(where: { $0.name == word }), !rest.hasPrefix("="), !rest.hasPrefix("."), !rest.hasPrefix("(") {83 // `stop` alone is also a statement; as a console command it stops automations.84 var arg: String? = rest.isEmpty ? nil : rest85 if let a = arg, a.hasPrefix("\""), a.hasSuffix("\""), a.count >= 2 { arg = String(a.dropFirst().dropLast()) }86 return .command(name: word, argument: arg)87 }88 let result = ScriptCompiler.compileConsole(text, capabilities: capabilities)89 if let program = result.program, !program.automations.isEmpty { return .script(program) }90 return .invalid(result.errors.isEmpty ? [Diagnostic(code: "E-SYNTAX", "Nothing to run.", at: SourceLocation(line: 1, column: 1))] : result.errors)91 }92}9394public struct Completion: Sendable, Equatable, Identifiable {95 public var id: String { insert }96 /// Text inserted in place of the typed prefix.97 public var insert: String98 public var label: String99 public var detail: String100 public var doc: String101}102103public enum Autocomplete {104 /// Completions for the word that ends at the cursor (`prefix` is the dotted text typed so far, e.g. "deck.A.fi").105 public static func completions(for prefix: String, variables: [String] = [], limit: Int = 40) -> [Completion] {106 var out: [Completion] = []107 let lower = prefix.lowercased()108 if !prefix.contains(".") {109 for k in ScriptSchema.keywords + variables where k.lowercased().hasPrefix(lower) && k != prefix {110 out.append(Completion(insert: k, label: k, detail: variables.contains(k) ? "variable" : "keyword", doc: ""))111 }112 for b in ScriptSchema.builtins where b.name.lowercased().hasPrefix(lower) {113 out.append(Completion(insert: b.name + "(", label: b.signature, detail: "builtin", doc: b.doc))114 }115 return Array(out.prefix(limit))116 }117 // Complete one path segment at a time.118 let parts = prefix.split(separator: ".", omittingEmptySubsequences: false).map(String.init)119 let head = parts.dropLast().joined(separator: ".")120 let partial = (parts.last ?? "").lowercased()121 var candidates: [(String, String, String)] = []122 if parts.count == 2, parts[0] == "deck" { candidates = deckLetters.map { ($0, "deck", "Deck \($0)") } }123 else if parts.count == 4, parts[0] == "mixer", parts[1] == "channel" || true, parts[1] == "channel", false { candidates = [] }124 else {125 let letter = parts.count >= 2 && parts[0] == "deck" && deckLetters.contains(parts[1]) ? parts[1] : (parts.count >= 3 && parts[1] == "channel" && deckLetters.contains(parts[2]) ? parts[2] : "A")126 var seen: Set<String> = []127 if parts.count == 3, parts[0] == "mixer", parts[1] == "channel" { candidates = deckLetters.map { ($0, "channel", "Channel \($0)") } }128 for (path, detail, doc) in ScriptSchema.completionPaths(deck: letter) + deckFxPaths(letter) where path.hasPrefix(head + ".") {129 let remainder = String(path.dropFirst(head.count + 1))130 let segment = String(remainder.prefix { $0 != "." })131 let isLeaf = !remainder.contains(".")132 if seen.insert(segment).inserted { candidates.append((segment, isLeaf ? detail : "…", isLeaf ? doc : "")) }133 }134 }135 for (segment, detail, doc) in candidates where segment.lowercased().hasPrefix(partial) {136 out.append(Completion(insert: head + "." + segment, label: segment, detail: detail, doc: doc))137 }138 return Array(out.prefix(limit))139 }140141 private static func deckFxPaths(_ letter: String) -> [(String, String, String)] {142 var out: [(String, String, String)] = []143 for k in EffectKind.allCases {144 for d in ScriptSchema.fxParams(k) { out.append(("deck.\(letter).fx.\(k.rawValue).\(d.key)", "\(d.type)", d.doc)) }145 for a in ScriptSchema.fxActions { out.append(("deck.\(letter).fx.\(k.rawValue).\(a.name)()", "action", a.doc)) }146 }147 return out148 }149150 /// Documentation for the path under the cursor (hover help and `help <path>` in the console).151 public static func documentation(for path: String) -> String? {152 let clean = path.replacingOccurrences(of: "()", with: "")153 let parts = clean.split(separator: ".").map(String.init)154 guard let first = parts.first else { return nil }155 func describe(_ d: ParamDef, _ full: String) -> String {156 "\(full): \(d.type)\(d.writable ? "" : " (read-only)")\n\(d.doc)\nRange: \(d.rangeText)" + (d.writable ? "\nDefault: \(d.defaultValue.display(unit: d.unit))" : "")157 }158 switch first {159 case "deck" where parts.count >= 3 && deckLetters.contains(parts[1]):160 if parts[2] == "fx", parts.count >= 4, let k = EffectKind(rawValue: parts[3]) { return fxDoc(k, Array(parts.dropFirst(4)), clean) }161 let key = parts.dropFirst(2).joined(separator: ".")162 if let d = ScriptSchema.deckParam(key) { return describe(d, clean) }163 if let a = ScriptSchema.deckAction(key) { return "deck.\(parts[1]).\(a.signature)\n\(a.doc)" + a.params.map { "\n \($0.name): \($0.doc)" }.joined() }164 if let e = ScriptSchema.deckEvents.first(where: { $0.name == key }) { return "on \(clean) { … }\n\(e.doc)" }165 case "mixer":166 if parts.count >= 4, parts[1] == "channel", let key = ScriptSchema.mixerChannelAliases[parts.dropFirst(3).joined(separator: ".")], let d = ScriptSchema.deckParam(key) {167 return describe(d, clean) + "\nSame parameter as deck.\(parts[2]).\(key)."168 }169 if let d = ScriptSchema.mixerParam(parts.dropFirst().joined(separator: ".")) { return describe(d, clean) }170 case "master":171 if let d = ScriptSchema.masterParam(parts.dropFirst().joined(separator: ".")) { return describe(d, clean) }172 case "fx" where parts.count >= 2:173 if let k = EffectKind(rawValue: parts[1]) { return fxDoc(k, Array(parts.dropFirst(2)), clean) }174 default:175 if let b = ScriptSchema.builtins.first(where: { $0.name == first }) { return "\(b.signature)\n\(b.doc)" }176 }177 return nil178 }179180 private static func fxDoc(_ kind: EffectKind, _ rest: [String], _ full: String) -> String? {181 let desc = EffectCatalog.descriptor(kind)182 if rest.isEmpty {183 return "\(desc.displayName): \(desc.summary)\nParameters: " + ScriptSchema.fxParams(kind).map(\.key).joined(separator: ", ") + "\nActions: enable(), disable(), toggle()"184 }185 let key = rest.joined(separator: ".")186 if let d = ScriptSchema.fxParam(kind, key) { return "\(full): \(d.type)\n\(d.doc)\nRange: \(d.rangeText)\nDefault: \(d.defaultValue.display(unit: d.unit))" }187 if let a = ScriptSchema.fxAction(key) { return "\(full)()\n\(a.doc)" }188 return nil189 }190}191